Container Types: Any
schema.any
- declare
- generate
- validate
- substitute
Declares a schema that defines any type.
from d42 import schema
sch = schema.any
The schema.any object represents a schema that can match any type of value. This can be useful in some cases where the structure of the data is unknown or can vary widely.
Generates a random value of any type.
from d42 import schema, fake
sch = schema.any
generated = fake(sch)
assert isinstance(generated, object)
In the current implementation, the fake function always returns None
Validates any value. The schema.any object can match any value, so it will always return True.
from d42 import schema
sch = schema.any
assert sch == None
assert sch == 42
assert sch == "banana"
Substitutes a value of any type. The schema.any object can match any value, so it can substitute any value.
from d42 import schema
sch = schema.any
assert sch % None == schema.any(schema.none)
assert sch % 42 == schema.any(schema.int(42))
assert sch % "banana" == schema.any(schema.str("banana"))
The from_native function is used to convert the Python objects to d42 types.
schema.any(*types)
- declare
- generate
- validate
- substitute
Declares a schema that can be any of the provided types.
from d42 import schema
sch = schema.any(schema.str, schema.int)
# syntax sugar
sch = schema.str | schema.int
Both of the above examples define a schema that can be either a str or an int.
Generates a random value, limited to the provided types.
from d42 import schema, fake
sch = schema.any(schema.str, schema.int)
generated = fake(sch)
assert isinstance(generated, (str, int))
Validates the value against all the provided types, returning True if any of them match the value.
from d42 import schema
sch = schema.any(schema.str, schema.int)
assert sch == "42"
assert sch == 42
assert sch != None # incorrect type
Substitutes the value into all the provided types where the validation has passed.
from d42 import schema
sch = schema.any(schema.str, schema.int)
assert sch % "42" == schema.any(schema.str("42"))
assert sch % 42 == schema.any(schema.int(42))
with assertRaises(SubstitutionError):
sch % None # incorrect type
If the value matches multiple types, the substitution will be performed for all of them. If the value doesn't match any of the provided types, a SubstitutionError will be raised.