Jundiaius
Jundiaius

Reputation: 7620

How to create a non-field instance-level variable on a dataclass?

If I understand well, ClassVar is a way of creating a class-variable on a dataclass, a variable which won't be considered as a field. So, for example:

@dataclass
class MyData:
    name: str
    age: int
    parent: ClassVar[Optional["MyData"]] = None

jake_data = MyData(name="Jake", age=34)

dataclasses.fields(jake_data) # This will output only two fields, as status is a ClassVar

But if I want to modify parent at the instance level after the instance's initialisation, it should not be a ClassVar, as PEP 526 makes it clear that the ClassVar annotation should only be used for variables which are not replaced at instance level. And I don't want to declare parent as a field with a default value because then it would be... a dataclass field!

For the context: I use libraries that rely on the output of dataclasses.fields, that's why I want it to be a non-field variable.

Is there a pythonic and readable way to do that?

Upvotes: 1

Views: 1984

Answers (1)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95948

Just don't annotate it, and define it in the __post_init__, so something like:

@dataclass
class MyData:
    name: str
    age: int

    def __post_init__(self):
        self.parent = None
        # whatever else

Upvotes: 5

Related Questions