Adding relative notation for `_lookup_field`
I need to add dependency on a 'type': 'list', but the current implementation does not allow me to do that. I cannot use the dot notation as my_field is dependent on parent level and the absolute notation ^ does not keep track of the index in the list (not sure its a bug or not).
schema = {
'list_1': {
'type': 'list',
'schema': {
'type': 'dict',
'schema': {
'simple_field': {'type': 'boolean'},
'not_simple_field': {
'type': 'dict',
'schema': {
'my_field': {'dependencies': {'simple_field': True}}
}
}
}
}
}
}
Thus i'd like to propose to extend the _lookup_field with a dot notation similar to how python relative notation works.
This is an example of how I'm extending _lookup_field implementation locally
def _lookup_field(self, path: str) -> Tuple:
"""
Implement relative paths with dot (.) notation, following Python
guidelines: https://www.python.org/dev/peps/pep-0328/#guido-s-decision
- A single leading dot indicates a relative import
starting with the current package.
- Two or more leading dots give a relative import to the parent(s)
of the current package, one level per dot after the first
Return: Tuple(dependency_name: str, dependency_value: Any)
"""
# Python relative imports use a single leading dot
# for the current level, however no dot in Cerberus
# does the same thing, thus we need to check 2 or more dots
if path.startswith('..'):
parts = path.split('.')
dot_count = self.path.count('.')
context = self.root_document
for key in self.document_path[:dot_count]:
context = context[key]
context = context.get(parts[-1])
return parts[-1], context
else:
return super()._lookup_field(path)
If people think this would be a good addition. I can make a pull request.
i see that there would be no other way to solve your use-case.
would it be a good idea to make the lookup-strategy configurable (also regarding ^) per validator instance, so that use-cases that use these characters in fieldnames would still be solvable?
I can make a pull request.
that would be very welcome, but please refrain from it until the bigger code changes for 2.0 version are in the master branch.
btw, relative imports are not encouraged. so, if this gets included, i wouldn't like to see this pep referenced.
we don't intend to add further features to Cerberus.