-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Closed
Labels
Description
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?