marshmallow
marshmallow copied to clipboard
Let data_key and attribute default to field name
Closes #1864.
Trying to address #1864, I get typing issues, as foreseen in https://github.com/marshmallow-code/marshmallow/issues/1864#issuecomment-909225360. I wouldn't mind a bit of help, here.
This change spares users the hassle of checking if data_key
is None
, as can be seen in the changes in schema.py. This would be used in apispec, for instance.
Notes:
- In Pluck, we don't check for
None
but only for truthyness, which may be wrong for empty strings. I didn't look into it any further but this PR would fix it. - I also intend to add
data_key
to the repr. The printed name will be the actual value, be it the parameter or the field name (default). I don't think it is an issue. - I also intend to do the same with attribute, symmetrically.
Notes:
-
I renamed a few local variables in
Schema
methods to be more explicit:data_key
instead offield_name
. We might want to renamefield_name
attribute of_call_and_store
because it not necessarily the field name. That can be done later. -
In
Field.get_value
, I had to keep theif self.attribute is None
check because the field can be used while not bound to a schema.
I performed a quick test on apispec codebase to see how things could be simplified there and the result is a bit disappointing. apispec operates on schema instances or classes, and when operating on a class, fields are not bound to the schema so we can't rely on data_key
or attribute
being set.
This feature would be more useful if it occurred on schema class creation, not instantiation. Technically, that could mean adding a _set_name
method to Field
that would be called from Schema._get_fields
. This is what I do in the last commit. Although setting name at schema creation seems more logical to me, the downside of this is that custom fields, especially container fields, may now have to override both _bind_to_schema
and _set_name
. (Part of the trouble there is related to inferred or Meta.include
fields, which may be dropped in marshmallow 4 (at least inferred ones: #1356).)
With this last commit, the changes in apispec work.
Notes:
- The change in apispec is minimal (2 lines changed), so the benefit of this is rather limited.)
- If I understand @kasium correctly in #1864, they are using
_declared_fields
so they are working onSchema
classes, not instances, therefore, they fall in the same case as apispec and the change would only be beneficial if done atSchema
creation.
@lafrech yes, that's right. I use the declared_fields
attribute. But I guess using a schema instance would not add too much trouble if somehow cached (not your worry). However, having it on class level would still be nice