Skip to content

add skip_none argument #587

@JakeSummers

Description

@JakeSummers

Question / Feature Request

Suppose that I have a class like this:

class Jake(BaseModel):
    foo: Optional[str]

When I serialize it, I only want to serialize optional values when they are not null. The skip_defaults flag does something similar to what I am looking for but has this weird case:

>>> j = Jake()
>>> 
>>> # This is the behavior I expect: 
... j.dict(skip_defaults=True)
{}
>>> 
>>> # Set the foo property: 
>>> j.foo = "baz"
>>> 
>>> # This is also the behaviour I expect: 
... j.dict(skip_defaults=True)
{'foo': 'baz'}
>>> 
>>> 
>>> # Unfortunately, this is not the behavior that I expect:
... j.foo = None
>>> j.dict(skip_defaults=True)
{'foo': None}

Right now after I serialize to dict, I walk the dict and remove all of the None values recursively, but I would rather not have to do this. Is this built into Pydantic? Is the behavior that I am seeing a bug?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions