Skip to main content
typing.ClassVar is a type hint construct used to indicate that a given attribute is intended to be a class variable rather than an instance variable. It signals to static type checkers that the attribute is bound to the class object itself, shared across all instances, and should not be dynamically assigned or overridden on a per-instance basis.

Syntax

ClassVar requires a type parameter specifying the type of the class variable. It is imported from the standard typing module.

Static Type Checking Rules

When analyzed by a static type checker (such as mypy, pyright, or pyre), ClassVar enforces strict assignment rules:
  1. Instance Assignment Prohibition: A type checker will emit an error if code attempts to assign a value to a ClassVar through an instance (self.node_count = 5). It must be assigned via the class (Node.node_count = 5).
  2. No Type Variables: ClassVar cannot contain generic type variables (TypeVar). For example, ClassVar[T] is invalid.
  3. No Nesting: ClassVar cannot be nested within itself or other generic types. ClassVar[ClassVar[int]] and List[ClassVar[int]] are syntactically invalid.
  4. Initialization: While not strictly required by all type checkers, it is standard practice to initialize a ClassVar at the class level.

Runtime Behavior

At runtime, ClassVar does not alter standard Python attribute resolution. Python’s interpreter does not enforce the immutability of the class variable on instances; the enforcement is purely lexical via static analysis. However, ClassVar is actively consumed at runtime by specific metaprogramming tools, most notably the dataclasses module.

Interaction with Dataclasses

When the @dataclass decorator processes a class, it inspects the type annotations to generate boilerplate methods (__init__, __repr__, __eq__). If a field is annotated with ClassVar, the dataclass generator explicitly ignores it. The variable will not be included in the generated __init__ signature, nor will it be treated as a dataclass field.
Tired of Poor Python Skills? Fix That With Deep Grasping!Learn More