ruff
4059807d - [ty] Infer metaclass-declared attributes on class instances (#26512)

Commit
4 days ago
[ty] Infer metaclass-declared attributes on class instances (#26512) ## Summary Metaclasses can declare instance variables that their construction hooks populate in every class they create. We already exposed these attributes on the class object, but instance lookup only searched the constructed class's ordinary MRO. As a result, custom enum classes could fail protocol checks even though their metaclass populated the required attributes at runtime. Treat an annotation-only instance declaration directly on the concrete metaclass as a contract for an attribute stored in each constructed class namespace: ```python class Meta(type): generated: int def __new__(mcls, name: str, bases: tuple[type, ...], namespace: dict[str, object]): namespace["generated"] = 1 return super().__new__(mcls, name, bases, namespace) class C(metaclass=Meta): ... reveal_type(C().generated) # int ``` The new lookup preserves normal class and instance precedence, including data descriptors, dynamic bases, and implicit special-method lookup. Bound metaclass attributes and inferred method writes remain excluded from this contract. The mdtests cover the motivating protocol case along with the relevant class, instance, and descriptor interactions. Closes https://github.com/astral-sh/ty/issues/3535.
Author
Parents
Loading