Files
ruff/crates/ty_python_semantic/resources/lint_docs/invalid-attribute-access.md
Charlie Marsh 917c626954 [ty] Reject class access to generic instance attributes (#28123)
## Summary

Previously, we allowed generic instance attributes to be read or written
through the generic class itself, including through a specialized
generic alias. We now report `invalid-attribute-access` for these
accesses: specializing a class does not give it separate attribute
storage for each set of type arguments.

```python
class Node[T]:
    label: T

    def __init__(self, label: T) -> None:
        self.label = label

# Before: no errors. After: invalid-attribute-access on each line.
Node[int].label = 1
Node[int].label
Node.label = 1
Node.label

node = Node(1)
node.label = 2  # Before and after: OK.
```

We check the generic declaration before applying the class's type
arguments, using the existing variance analysis to detect dependencies
through type aliases without expanding recursive specializations.
Instance access, class variables, and attributes independent of the
class's type parameters remain valid. Access to methods and descriptors
retains its existing behavior, and invalid accesses retain their
inferred types for error recovery.

Importantly, we continue to allow access through `cls`,
`type(instance)`, and parameters annotated with `type[...]`. These
receivers can refer to concrete subclasses with their own class
attributes. The typing specification [makes the analogous
`type(instance).attribute` diagnostic
optional](https://github.com/python/typing/commit/b41e5096bc9b1333355911614648616f7cfbf943)
for that reason.

This moves
[`generics_type_erasure`](https://github.com/python/typing/blob/b41e5096bc9b1333355911614648616f7cfbf943/conformance/tests/generics_type_erasure.py)
from Partial to Pass.

<details>
<summary>Case analysis</summary>

Mypy 2.1.0, pyright 1.1.410, and pyrefly 1.3.0-dev.1 all reject the four
class accesses above. The Pyrefly comparisons use its `default` preset.
Pyright and pyrefly pass the full conformance file. Mypy still fails two
separate assertions because it infers `Never` rather than `Any` for an
unspecialized constructor call.

In `__init_subclass__`, `cls` refers to the subclass being initialized.
MkDocs reads its configuration metadata through this receiver, while
steam.py assigns the converter's target type. We allow both patterns, as
do mypy, pyright, and pyrefly:

```python
from typing import Generic, TypeVar

T = TypeVar("T")

class BasePlugin(Generic[T]):
    config_class: T

    def __init_subclass__(cls):
        cls.config_class  # All four: OK.

class Converter(Generic[T]):
    converter_for: T

    def __init_subclass__(cls, converter_for):
        cls.converter_for = converter_for  # All four: OK.
```

We also allow reads through `cls` in `__new__` and classmethods.
Prefect's worker configuration, Static-frame's store configuration, and
SymPy's Gaussian domains use this pattern, with concrete subclasses
supplying the attributes. All four checkers accept these examples:

```python
from typing import Generic, TypeVar

T = TypeVar("T")

class GaussianElement(Generic[T]):
    base: T
    _parent: T

    def __new__(cls):
        cls.base  # All four: OK.
        return super().__new__(cls)

    @classmethod
    def _get_xy(cls):
        cls._parent  # All four: OK.
```

For class objects passed as parameters, we agree with mypy: the receiver
may be a concrete subclass, even when the annotation names a generic
base. Pyright and Pyrefly's `default` preset reject both examples below.
Pyrefly's `basic` preset accepts them because it disables the relevant
check. The same distinction applies whether the class parameter retains
a type variable, as in pytest, or fixes its type argument, as in
Static-frame:

```python
from typing import Generic, TypeVar

T = TypeVar("T")

class CaptureBase(Generic[T]):
    EMPTY_BUFFER: T

def capture(captureclass: type[CaptureBase[T]]):
    # ty, mypy: OK; pyright, pyrefly (default): error.
    captureclass.EMPTY_BUFFER

class Store(Generic[T]):
    _STORE_CONFIG_CLASS: T

def read(cls: type[Store[object]]):
    # ty, mypy: OK; pyright, pyrefly (default): error.
    cls._STORE_CONFIG_CLASS
```

</details>
2026-08-29 12:44:34 +00:00

1.7 KiB

What it does

Checks for assignments to class variables from instances and assignments to instance-only attributes from their class. Also checks for reads and writes of generic instance attributes through a generic class or a specialized generic alias.

An "instance-only" variable is one which is only ever assigned to or declared when accessed via self in an instance method.

A generic instance attribute has a type that depends on the class's type parameters. Specializing a generic class does not create separate class attribute storage, so these attributes cannot be accessed through the generic class or a specialized alias. Access through a type[...] receiver is allowed because it can refer to a concrete subclass with its own class attributes.

Why is this bad?

Incorrect assignments break the rules of the type system and weaken a type checker's ability to accurately reason about your code.

Examples

from typing import ClassVar


class C:
    instance_var: int
    class_var: ClassVar[int] = 1

    def __init__(self):
        # instance variable declared in the class body
        self.instance_var = 42

        # instance-only variable not declared in the class body
        self.instance_only_var: int = 42


C.class_var = 3  # okay

C.instance_var = 56  # okay
C().instance_var = 72  # okay

C().instance_only_var = 100  # okay

# Cannot assign to class variable from instance
C().class_var = 3  # error

# Cannot assign to instance-only variable from class
C.instance_only_var = 56  # error
from typing import Generic, TypeVar

T = TypeVar("T")


class Box(Generic[T]):
    value: T


Box[int].value = 1  # error
Box.value  # error

box = Box[int]()
box.value = 1  # okay