I have a python dataclass
that looks something like:
@dataclass
class MyDataClass:
field0: int = 0
field1: int = 0
# --- Some other attribute that shouldn't be considered as _fields_ of the class
attr0: int = 0
attr1: int = 0
I'd like to write the class in such a way that, when calling dataclasses.fields(my_data:=MyDataClass())
, only field0
and field1
are reported.
As a workaround, I've splitted the class in two inheriting classes, as:
@dataclass
class MyData:
field0: int = 0
field1: int = 0
class MyDataClass(MyData):
# --- Some other attribute that shouldn't be considered as _fields_ of the class
attr0: int = 0
attr1: int = 0
It works, but I don't know if it's the right way (some drawback I'm not considering?) or if there is a more straightforward way to do it
Not the most elegant solution, but you may declare the non-field attributes as InitVar[int]
and set them in a __post_init__()
method.
@dataclass
class MyDataClass:
field0: int = 0
field1: int = 0
# --- Some other attribute that shouldn't be considered as _fields_ of the class
attr0: InitVar[int] = 0
attr1: InitVar[int] = 0
def __post_init__(self, attr0, attr1):
self.attr0 = attr0
self.attr1 = attr1