Dataclasses and property decorator

It sure does work: from dataclasses import dataclass @dataclass class Test: _name: str=”schbell” @property def name(self) -> str: return self._name @name.setter def name(self, v: str) -> None: self._name = v t = Test() print(t.name) # schbell t.name = “flirp” print(t.name) # flirp print(t) # Test(_name=”flirp”) In fact, why should it not? In the end, what … Read more

How can I get Python 3.7 new dataclass field types?

Inspecting __annotations__ gives you the raw annotations, but those don’t necessarily correspond to a dataclass’s field types. Things like ClassVar and InitVar show up in __annotations__, even though they’re not fields, and inherited fields don’t show up. Instead, call dataclasses.fields on the dataclass, and inspect the field objects: field_types = {field.name: field.type for field in … Read more

Make the Python json encoder support Python’s new dataclasses

Much like you can add support to the JSON encoder for datetime objects or Decimals, you can also provide a custom encoder subclass to serialize dataclasses: import dataclasses, json class EnhancedJSONEncoder(json.JSONEncoder): def default(self, o): if dataclasses.is_dataclass(o): return dataclasses.asdict(o) return super().default(o) json.dumps(foo, cls=EnhancedJSONEncoder)

Validating detailed types in python dataclasses

Instead of checking for type equality, you should use isinstance. But you cannot use a parametrized generic type (typing.List[int]) to do so, you must use the “generic” version (typing.List). So you will be able to check for the container type but not the contained types. Parametrized generic types define an __origin__ attribute that you can … Read more