Proper way to create class variable in Data Class

To create a class variable, annotate the field as a typing.ClassVar or not at all.

from typing import ClassVar
from dataclasses import dataclass

@dataclass
class Foo:
    ivar: float = 0.5
    cvar: ClassVar[float] = 0.5
    nvar = 0.5

foo = Foo()
Foo.ivar, Foo.cvar, Foo.nvar = 1, 1, 1
print(Foo().ivar, Foo().cvar, Foo().nvar)   # 0.5 1 1
print(foo.ivar, foo.cvar, foo.nvar)         # 0.5 1 1
print(Foo(), Foo(12))                       # Foo(ivar=0.5) Foo(ivar=12)

There is a subtle difference in that the unannotated field is completely ignored by @dataclass, whereas the ClassVar field is stored but not converted to an attribute.


dataclasses — Data Classes

The member variables […] are defined using PEP 526 type annotations.

Class variables

One of two places where dataclass() actually inspects the type of a
field is to determine if a field is a class variable as defined in PEP
526. It does this by checking if the type of the field is typing.ClassVar. If a field is a ClassVar, it is excluded from
consideration as a field and is ignored by the dataclass mechanisms.

Such ClassVar pseudo-fields are not returned by the module-level
fields() function.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)