Root reference is broken for nested/container fields when using schema inheritance
See original GitHub issueI use schema inheritance a lot to reuse shared parts of schemas. Additionally I have some custom fields with validation methods which use references to the field’s root schema. When these custom fields are used in nested schemas or inside lists, then the same field instance is used in different schema classes and thus the root reference is “broken”:
>>> import marshmallow
>>> marshmallow.__version__
'3.0.0b13'
>>> from marshmallow import fields
>>> from marshmallow.schema import Schema
>>> class A(Schema):
... f1 = fields.List(fields.Integer())
...
>>> class B(A):
... pass
...
>>> a = A()
>>> b = B()
>>> a_f1 = a.declared_fields['f1']
>>> b_f1 = b.declared_fields['f1']
>>> a_f1.root == a
True
>>> b_f1.root == b
True
>>> a_f1.container.root == a
False
>>> a_f1.container.root == b
True
So the problem is that the container root of field f1
of schema instance a
is schema instance b
. In fact a_f1.container
and b_f1.container
point to the same object.
Is this a problem of how I use marshmallow or is this a bug?
I find the possibility to reference a field’s root schema very valuable and the root property looks like it can be used like that. However, I think the problem here is that nested (or container) fields are not unique instances when used in multiple classes.
Issue Analytics
- State:
- Created 5 years ago
- Comments:5 (2 by maintainers)
Top GitHub Comments
self.container = cls_or_instance
->self.container = copy.deepcopy(cls_or_instance)
should do the trick.If you are interested in submitting a PR it would be greatly appreciated. Otherwise I will try to work on a fix when I find time.
Thanks for the fix!