Skip to content

Instantly share code, notes, and snippets.

@Julian
Last active November 30, 2022 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Julian/7d75b7f3fd0394c0ce17621416fa3ca5 to your computer and use it in GitHub Desktop.
Save Julian/7d75b7f3fd0394c0ce17621416fa3ca5 to your computer and use it in GitHub Desktop.
def extend_with_default(validator_class):
validate_properties = validator_class.VALIDATORS["properties"]
def set_defaults(validator, properties, instance, schema):
for error in validate_properties(
validator, properties, instance, schema,
):
yield error
for property, subschema in properties.items():
if "default" in subschema:
instance.setdefault(property, subschema["default"])
def set_defaults_for_oneOf(validator, oneOf, instance, schema):
subschemas = enumerate(oneOf)
all_errors = []
for index, subschema in subschemas:
errs = list(validator.descend(instance, subschema, schema_path=index))
if not errs:
first_valid = subschema
break
all_errors.extend(errs)
else:
yield ValidationError(
f"{instance!r} is not valid under any of the given schemas",
context=all_errors,
)
more_valid = [
each for _, each in subschemas
if validator.evolve(schema=each).is_valid(instance)
]
if more_valid:
more_valid.append(first_valid)
reprs = ", ".join(repr(schema) for schema in more_valid)
yield ValidationError(f"{instance!r} is valid under each of {reprs}")
set_defaults_here()
return validators.extend(
validator_class, {"properties" : set_defaults, "oneOf", set_defaults_for_oneOf},
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment