Skip to main content

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.
from typing import ClassVar

class Node:
    # Declared as a class variable
    node_count: ClassVar[int] = 0
    
    # Declared as an instance variable
    value: int

    def __init__(self, value: int):
        self.value = value
        Node.node_count += 1

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.
from typing import ClassVar

class Configuration:
    debug_mode: ClassVar[bool] = False

config = Configuration()


# Type Checker: OK
Configuration.debug_mode = True 


# Type Checker: ERROR (Cannot assign to class variable via instance)
config.debug_mode = True 

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.
from dataclasses import dataclass
from typing import ClassVar

@dataclass
class Worker:
    worker_id: int
    max_workers: ClassVar[int] = 10


# max_workers is excluded from the constructor
w = Worker(worker_id=1) 
Master Python with Deep Grasping Methodology!Learn More