jcrist / msgspec

A fast serialization and validation library, with builtin support for JSON, MessagePack, YAML, and TOML

Home Page:https://jcristharif.com/msgspec/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How can I do data normalization on a frozen instance in `__post_init__`?

onecrayon opened this issue · comments

Question

I am trying to normalize a piece of data in a frozen=True Struct class. I figured the most sensible place to do this was in __post_init__ but received this error:

AttributeError: immutable type: 'SomeFrozenStruct'

A bit of searching pulled up this StackOverflow answer: https://stackoverflow.com/a/54119384/38666 so I modified my code to look something like:

def __post_init__(self):
    object.__setattr__(self, "target_prop", normalize_value(self.target_prop))

But that raised a new error:

TypeError: can't apply this __setattr__ to SomeFrozenStruct object

Is there an officially-recommended way to go about this? The other good suggestion in that StackOverflow thread was to use a cached property, but this isn't appropriate for my use case because I'm normalizing data rather than generating a new property value (the source and the end name are the same).

Literally seconds after posting this I stumbled across #588 after trying slightly different keywords; the existing msgspec.structs.force_setattr perfectly addresses my needs. Apologies for the noise in your inbox!