Python Glossary Русский

Python 3.5+Annotations & typingterm

ClassVar

attributes

Marks a variable as belonging to the class rather than to the instance. It must not be assigned through self.

Syntax

from typing import ClassVar
class MyClass:
    attr: ClassVar[type] = value

The annotation enforces nothing by itself — assigning through self still creates an instance attribute that shadows the class one, and only a type checker will complain. Where ClassVar really bites is dataclasses: such a field is excluded from the generated __init__ and from fields(), staying a plain class-level constant. Also mind the usual class-attribute trap — a mutable list or dict is shared by every instance, so mutating it in place is visible everywhere.

Examples

from typing import ClassVar
class Counter:
    count: ClassVar[int] = 0
    def __init__(self): Counter.count += 1
c1 = Counter()
c2 = Counter()
print(Counter.count)  # → 2
from typing import ClassVar
class Config:
    debug: ClassVar[bool] = False
    host: str = 'localhost'
print(Config.debug)  # → False
print(Config.host)  # → localhost
Config.debug = True
print(Config.debug)  # → True

See also

Open in the full glossarydocs.python.orgReport an inaccuracy