Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why using ClassVar's attributes in a dataclass has no effect?

Considering this example :

from dataclasses import dataclass
from typing import ClassVar

@dataclass
class Circle:
    radius: float
    pi: ClassVar[float] = 3.14159


circle1 = Circle(5.0)
circle2 = Circle(10.0)

circle1.pi = 3.14

print(circle1) # gives Circle(radius=5.0)
print(circle1.pi) # gives 3.14

I’m very confused because I can’t see the difference between using pi: ClassVar[float] = 3.14159 and pi: float = 3.14159.

Sorry but can someone explain why and where ClassVar can be useful ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

From ClassVar

it is excluded from consideration as a field and is ignored by the dataclass mechanism

That means that you won’t see it in the string representation of a a dataclass instances

Also modifying it as Class.attribute will result in modification for every object of the class (if you try Circle.radius = 3.14 is has no effect)

circle1 = Circle(5.0)
circle2 = Circle(10.0)
print(circle1.radius, circle1.pi) # 5.0  3.14159
print(circle2.radius, circle2.pi) # 10.0 3.14159


Circle.pi = 3.14

print(circle1.radius, circle1.pi) # 5.0  3.14
print(circle2.radius, circle2.pi) # 10.0 3.14
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading