Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

typing.ClassVar

Mark an attribute as belonging to the class for static analysis.

Version: Python 3.14; repository image, production runtime not attested

Syntax

class_count: ClassVar[int] = 0

Mark an attribute as belonging to the class for static analysis.

A checker rejects assignment through an instance even though ordinary Python attribute lookup can still create an instance shadow. Dataclasses also exclude ClassVar annotations from their generated fields.

Changing the class attribute in the example affects only the instance without a shadow.

Examples

from dataclasses import dataclass, fields
from typing import ClassVar

@dataclass
class Device:
    label: str
    zone: ClassVar[str] = "west"

a, b = Device("A"), Device("B")
a.zone = "local"
Device.zone = "east"
print([f.name for f in fields(Device)])
print(a.zone, b.zone, Device.zone)

Result

['label']
local east east

Changing the class attribute in the example affects only the instance without a shadow.

Sources