classes_classvar error

ClassVar used in an invalid context

PEP 526 and the typing spec restrict ClassVarT to:

- Annotations of class body attributes (class variables)

Using ClassVar outside a class body (in function parameters, return types, local variable annotations, or module-level variable annotations) is an error. Additionally, nesting ClassVar inside another type constructor (e.g. FinalClassVar[int] or listClassVar[int]) is forbidden.

Note: AnnotatedClassVar[T, ...] is a valid exception.

This rule also validates ClassVar argument correctness: - ClassVar accepts at most one argument - The argument must be a valid type (not a literal or runtime variable) - The argument must not contain TypeVar, ParamSpec, or TypeVarTuple

Additionally, ClassVar attributes cannot be assigned via instances.

class MyClass:
    bad9: Final[ClassVar[int]] = 3     # E0036 — ClassVar cannot be nested
    bad10: list[ClassVar[int]] = []    # E0036 — ClassVar cannot be nested

    def method1(self, a: ClassVar[int]):   # E0036 — ClassVar not allowed here
        x: ClassVar[str] = ""              # E0036 — ClassVar not allowed here
        self.xx: ClassVar[str] = ""        # E0036 — ClassVar not allowed here

    def method2(self) -> ClassVar[int]:    # E0036 — ClassVar not allowed here
        ...

bad11: ClassVar[int] = 3              # E0036 — ClassVar not allowed at module level
bad12: TypeAlias = ClassVar[str]      # E0036 — ClassVar not allowed here

How to handle it

Every rule is on by default — strict is the default, not a cage. You can dial classes_classvar down per-file or per-path from your editor or pyproject.toml, or fix the code so it type-checks. See the Type System rules and the complete diagnostic reference.

Canonical URL: https://www.basilisk-python.dev/errors/classes_classvar