According to the typing spec:
The
typing.ClassVar
type qualifier is used to annotate class variables that should not be set on class instances.
However, what about modifying the ClassVar
with __setitem__
or __setattr__
on an instance? It feels like this should also not be allowed. Two examples:
__setitem__
example: pyright playground, mypy playground, ty playground
from typing import ClassVar
class Foo:
d: ClassVar[dict[str, object]] = {}
def set_value(self, key: str, value: object) -> None:
self.d[key] = value # <-- Use Foo.d[key] = value instead?!
__setattr__
example: pyright playground, mypy playground, ty playground
from typing import ClassVar
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
class Bar:
p: ClassVar[Point] = Point(0.0, 0.0)
def set_x(self, value: float) -> None:
self.p.x = value # <-- Use Bar.p.x = value instead?!
Enforcing that setting attributes/items should only be done on the class and not the instance level would be a good reminder that such modification does indeed apply to all instances.