Documentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
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 asmypy, pyright, or pyre), ClassVar enforces strict assignment rules:
- Instance Assignment Prohibition: A type checker will emit an error if code attempts to assign a value to a
ClassVarthrough an instance (self.node_count = 5). It must be assigned via the class (Node.node_count = 5). - No Type Variables:
ClassVarcannot contain generic type variables (TypeVar). For example,ClassVar[T]is invalid. - No Nesting:
ClassVarcannot be nested within itself or other generic types.ClassVar[ClassVar[int]]andList[ClassVar[int]]are syntactically invalid. - Initialization: While not strictly required by all type checkers, it is standard practice to initialize a
ClassVarat 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.
Master Python with Deep Grasping Methodology!Learn More





