Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
frogcjn opened this issue Jan 31, 2016 · 3 comments
Closed

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

frogcjn opened this issue Jan 31, 2016 · 3 comments

Comments

@frogcjn
Copy link

frogcjn commented Jan 31, 2016

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
@frogcjn frogcjn changed the title load None to special value, e.g. None -> [] load None value into special value, e.g. None -> [] Jan 31, 2016
@sloria
Copy link
Member

sloria commented Oct 5, 2016

Could you use a post_load method in a base class that your Schemas inherit from?

@sloria
Copy link
Member

sloria commented Jan 8, 2017

We do not plan to support this feature at this time. Closing for now.

@lafrech
Copy link
Member

lafrech commented Nov 29, 2023

#1381 would allow a Field to interpret None as missing.

Combined with load_default, it would solve OP's case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants