Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23160

Validate a recursive data structure (e.g. tree) using Python Cerberus (v1.3.5)

$
0
0

What is the right way to model a recursive data structure's schema in Cerberus?

Attempt #1:

from cerberus import Validator, schema_registryschema_registry.add("leaf", {"value": {"type": "integer", "required": True}})schema_registry.add("tree", {"type": "dict", "anyof_schema": ["leaf", "tree"]})v = Validator(schema = {"root":{"type": "dict", "schema": "tree"}})

Error:

cerberus.schema.SchemaError: {'root': [{'schema': ['no definitions validate', {'anyof definition 0': [{'anyof_schema': ['must be of dict type'], 'type': ['null value not allowed'],            }],'anyof definition 1': ['Rules set definition tree not found.'            ],        },    ]},]}

Attempt #2:

The above error indicating the need for a rules set definition for tree:

from cerberus import Validator, schema_registry, rules_set_registryschema_registry.add("leaf", {"value": {"type": "integer", "required": True}})rules_set_registry.add("tree", {"type": "dict", "anyof_schema": ["leaf", "tree"]})v = Validator(schema = {"root":{"type": "dict", "schema": "tree"}})v.validate({"root": {"value": 1}})v.errorsv.validate({"root": {"a":{"value": 1}}})v.errorsv.validate({"root": {"a": {"b": {"c": {"value": 1}}}}})v.errors

Output:

False{'root': ['must be of dict type']}

for all 3 examples.

Expected behaviour

Ideally, I would like all the below documents to pass validation:

v = Validator(schema = {"root":{"type": "dict", "schema": "tree"}})assert v.validate({"root": {"value": 1}}), v.errorsassert v.validate({"root": {"a":{"value": 1}}}), v.errorsassert v.validate({"root": {"a": {"b": {"c": {"value": 1}}}}}), v.errors

Viewing all articles
Browse latest Browse all 23160

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>