Question/feature request related to only and exclude
See original GitHub issueHi, first off this project it has helped us a lot, so a huge thanks!
I have a question / request related to the only
and exclude
parameters to schemas (and nested fields).
Provided a schema looks like this:
class TestSchema(Schema):
foo = Int()
bar = Str()
baz = Dict()
The following happens:
schema = TestSchema(only=('foo', 'bar', )) // works as expected
schema = TestSchema(only=('foo', 'not_part_of_schema', )) // adds not_part_of_schema
schema = TestSchema(exclude=('bar', 'baz', )) // works as expected
schema = TestSchema(exclude=('bar', 'not_part_of_schema', )) // not_part_of_schema does nothing
The following should happen in my opinion (to avoid leaking input data when schema forbids it):
schema = TestSchema(only=('foo', 'bar', )) // works
schema = TestSchema(only=('foo', 'not_part_of_schema', )) // raises exception
schema = TestSchema(exclude=('bar', 'baz', )) // works
schema = TestSchema(exclude=('bar', 'not_part_of_schema', )) // raises exception
To get the behaviour above we’ve implemented the following override to a base schema:
class BaseSchema(Schema):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs) // sorry py3 only
valid_fields = set(self.declared_fields.keys()) | set(self.opts.additional)
excluded_fields = set(self.exclude) | set(self.opts.exclude)
only_fields = set(self.only) if self.only else set()
if not excluded_fields.issubset(valid_fields):
raise LookupError('Excluded field(s) not part of valid fields')
valid_fields -= excluded_fields
if not only_fields.issubset(valid_fields):
raise LookupError('Only field(s) not part of valid fields')
Is this behaviour possible in the current Marshmallow code? If not, is our solution even recommended (am I missing some really obvious use case for the injection)? If yes, is this something that could be useful in Marshmallow?
Issue Analytics
- State:
- Created 6 years ago
- Reactions:1
- Comments:6 (5 by maintainers)
Top GitHub Comments
Hey !
This was done in https://github.com/marshmallow-code/marshmallow/pull/826, available since 3.0.0b12.
Should we also check only/exclude conflicts (proposed in https://github.com/marshmallow-code/marshmallow/pull/731)?