1

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?

2
  • There are init only varaibles, which don't seem to be what you want. Dataclasses aren't really designed to have non-transient variables that aren't fields. How would you be using the status? Commented Feb 24, 2020 at 19:03
  • @PatrickHaugh, I've edited the question (replaced status by parent) so it is closer to the use I have. As you can see, I am using this variable as a reference. I will need to set it only once, but it needs to be after initialisation. Commented Feb 24, 2020 at 19:09

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.