Python dataclass, what’s a pythonic way to validate initialization arguments?

Define a __post_init__ method on the class; the generated __init__ will call it if defined: from dataclasses import dataclass @dataclass class MyClass: is_good: bool = False is_bad: bool = False def __post_init__(self): if self.is_good: assert not self.is_bad This will even work when the replace function is used to make a new instance.

How to use enum value in asdict function from dataclasses module

Actually you can do it. asdict has keyword argument dict_factory which allows you to handle your data there: from dataclasses import dataclass, asdict from enum import Enum @dataclass class Foobar: name: str template: “FoobarEnum” class FoobarEnum(Enum): FIRST = “foobar” SECOND = “baz” def custom_asdict_factory(data): def convert_value(obj): if isinstance(obj, Enum): return obj.value return obj return dict((k, … Read more

How to convert Python dataclass to dictionary of string literal?

You can use dataclasses.asdict: from dataclasses import dataclass, asdict class MessageHeader(BaseModel): message_id: uuid.UUID def dict(self): return {k: str(v) for k, v in asdict(self).items()} If you’re sure that your class only has string values, you can skip the dictionary comprehension entirely: class MessageHeader(BaseModel): message_id: uuid.UUID dict = asdict

How to add a dataclass field without annotating the type?

The dataclass decorator examines the class to find fields, by looking for names in __annotations__. It is the presence of annotation which makes the field, so, you do need an annotation. You can, however, use a generic one: @dataclass class Favs: fav_number: int = 80085 fav_duck: ‘typing.Any’ = object() fav_word: str=”potato”

Dynamically add fields to dataclass objects

You could use make_dataclass to create X on the fly: X = make_dataclass(‘X’, [(‘i’, int), (‘s’, str)]) x = X(i=42, s=”text”) asdict(x) # {‘i’: 42, ‘s’: ‘text’} Or as a derived class: @dataclass class X: i: int x = X(i=42) x.__class__ = make_dataclass(‘Y’, fields=[(‘s’, str)], bases=(X,)) x.s=”text” asdict(x) # {‘i’: 42, ‘s’: ‘text’}

Replace attributes in Data Class objects

The dataclasses module has a helper function for field replacement on instances (docs) from dataclasses import replace Usage differs from collections.namedtuple, where the functionality was provided by a method on the generated type (Side note: namedtuple._replace is documented/public API, using an underscore on the name was called a “regret” by the author, see link at … Read more

How to create an optional field in a dataclass that is inherited? [duplicate]

The underlying problem that you have seems to be the same one that is described here. The short version of that post is that in a function signature (including the dataclass-generated __init__ method), obligatory arguments (like NamedEvent’s name) can not follow after arguments with default values (which are necessary to define the behavior of Event’s … Read more