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

Allow omit_defaults to exclude fields when encoded value is {} (empty dict) #645

Open
wikiped opened this issue Feb 20, 2024 · 0 comments
Open

Comments

@wikiped
Copy link

wikiped commented Feb 20, 2024

Description

The following code:

import msgspec as ms


class Sub(ms.Struct, omit_defaults=True):
    f1: str = ""
    f2: int = 0


class Struct(ms.Struct, omit_defaults=True, tag=True):
    f1: int = 1
    sub: Sub = ms.field(default_factory=Sub)


print(ms.yaml.encode(Struct()).decode())
print(ms.json.encode(Struct()).decode())

y = """
type: Struct

"""
j = '{"type":"Struct"}'

print()
print(ms.yaml.decode(y, type=Struct))
print(ms.json.decode(j, type=Struct))

Will output:

type: Struct
sub: {}

{"type":"Struct","sub":{}}

Struct(f1=1, sub=Sub(f1='', f2=0))
Struct(f1=1, sub=Sub(f1='', f2=0))

Although it is clear why the empty dict is being encoded, it is still desirable to avoid that, given that decoding absent fields does not cause any errors when the empty constructor (i.e. empty dict) is producing the expected default.

It would seem that recursive check with matches_default on subclasses of msgspec.Struct might do the job, but this would probably mean some hit on perfomance (?).

Perhaps there is a way to check the resulting '{}' value and omit it instead?

Thank you for considering this.

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

1 participant