Skip to content

load None value into special value, e.g. None -> [] #388

@frogcjn

Description

@frogcjn

I have many schemas which have some list fields, and I want all my list fields in my schemas have a feature, that is load a None into [] automatically. So when I operate with advanced class object, I don't need to worry about it is a None or a list.

This feature cannot be simply implemented by override _deserialize, because _deserialize will not be called if input value is None. (but _serialize will be called if attribute value is None, which is different behavior as _deserialize)

One way to implement this feature, is to add @post_load to each Schama, which needs lot of repeat code.

Another way to solve the problem, is to override deserialize in fields.List, which is not the recommended way to subclass Field

### Optional List & Set

# None, [] --load()-> []
# None, [] --dump()-> []

class SafeList(List):
    def _serialize(self, value, attr, obj):
        result = super(SafeList, self)._serialize(value, attr, obj)
        return [] if result is None else result

    def deserialize(self, value, attr=None, data=None): # or override _validate_missing, None -load-> []
        result = super(SafeList, self).deserialize(value, attr, data)
        return [] if result is None else result

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions