The ClassVar section of the typing spec says:
The
typing.ClassVartype qualifier is used to annotate class variables that should not be set on class instances.
The same section says an annotation in a class body without ClassVar, such as captain: str = 'Picard', declares an “instance variable with default”.
A metaclass’s instances are classes, and a class can declare a name that its metaclass declares as a ClassVar:
from typing import ClassVar
class Meta(type):
a: ClassVar[int] = 0
class C(metaclass=Meta):
a: str = ""
C is an instance of Meta, so by the ClassVar rule a should not be set on C. But C’s body declares a as an instance variable of C with a default, which puts a in C.__dict__. At runtime, C.__dict__["a"] takes precedence over a non-descriptor attribute on the metaclass, so C.a is "". The spec doesn’t say whether Meta’s ClassVar applies to C’s declaration, or which of the two declarations gives the type of C.a.
No type checker reports the declaration, but they disagree on the type of C.a:
C.a |
|
|---|---|
| pyright 1.1.414 | str |
| ty 0.0.112 | str |
| pyrefly 1.5.0 | str |
| mypy 2.4.1 | int |
I’d like feedback on whether an instance variable with a default, declared in the body of a class, is subject to a ClassVar of the same name on its metaclass. If it is, should declaring it be an error, or should the metaclass’s declaration still give the type of C.a?