mirror of
https://github.com/astral-sh/ruff.git
synced 2026-12-02 18:46:11 +08:00
[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.
This commit is contained in:
@@ -1298,11 +1298,528 @@ class InitializedDerived(DeclaringBase, metaclass=DerivedInitializingMeta): ...
|
||||
reveal_type(InitializedDerived.inherited_attr) # revealed: int
|
||||
```
|
||||
|
||||
An assignment through `cls` in an arbitrary metaclass method also writes to the constructed class
|
||||
object if that method is called. Class-object lookup currently treats such an inferred write as
|
||||
definitely present and drops an inherited value.
|
||||
|
||||
```py
|
||||
class InstallingClassAttributeMeta(type):
|
||||
def install(cls) -> None:
|
||||
cls.installed: int = 1
|
||||
|
||||
class InstalledClassAttributeBase:
|
||||
installed = "inherited"
|
||||
|
||||
class OptionallyInstalledClassAttribute(InstalledClassAttributeBase, metaclass=InstallingClassAttributeMeta): ...
|
||||
|
||||
# TODO: Without tracking calls to `install`, lookup should conservatively reveal `int | str`.
|
||||
reveal_type(OptionallyInstalledClassAttribute.installed) # revealed: int
|
||||
```
|
||||
|
||||
## Attributes stored on classes by metaclasses
|
||||
|
||||
An attribute declared in a metaclass with an annotation but no value describes an attribute of every
|
||||
class created with that metaclass. The attribute is therefore available through instances of those
|
||||
classes:
|
||||
|
||||
```py
|
||||
from typing import TypeVar
|
||||
|
||||
class StoringMeta(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 GeneratedClass(metaclass=StoringMeta):
|
||||
def method(self) -> None:
|
||||
reveal_type(self.generated) # revealed: int
|
||||
|
||||
reveal_type(GeneratedClass().generated) # revealed: int
|
||||
|
||||
TGenerated = TypeVar("TGenerated", bound=GeneratedClass)
|
||||
|
||||
def read_generated(value: TGenerated) -> None:
|
||||
reveal_type(value.generated) # revealed: int
|
||||
```
|
||||
|
||||
This also lets a generic metaclass method rely on a protocol describing the classes it accepts:
|
||||
|
||||
```py
|
||||
from typing import Iterator, Protocol, TypeVar
|
||||
|
||||
class EnumProtocol(Protocol):
|
||||
_member_map_: dict[str, int]
|
||||
|
||||
def __init__(self, value: int) -> None: ...
|
||||
|
||||
T = TypeVar("T", bound=EnumProtocol)
|
||||
|
||||
class EnumMeta(type, EnumProtocol):
|
||||
_member_map_: dict[str, int]
|
||||
|
||||
def __new__(mcls, name: str, bases: tuple[type, ...], namespace: dict[str, object]):
|
||||
namespace["_member_map_"] = {"one": 1}
|
||||
return super().__new__(mcls, name, bases, namespace)
|
||||
|
||||
def __iter__(cls: type[T]) -> Iterator[T]:
|
||||
return iter(cls(value) for value in cls._member_map_.values())
|
||||
|
||||
class EnumValue(int, metaclass=EnumMeta):
|
||||
def __init__(self, value: int) -> None: ...
|
||||
|
||||
reveal_type(EnumValue(1)._member_map_) # revealed: dict[str, int]
|
||||
|
||||
for member in EnumValue:
|
||||
reveal_type(member) # revealed: EnumValue
|
||||
```
|
||||
|
||||
Because the metaclass stores the declared attribute directly on the new class, it takes precedence
|
||||
over an attribute inherited from a base class:
|
||||
|
||||
```py
|
||||
class GeneratedBase:
|
||||
generated = "base"
|
||||
|
||||
class StoresGenerated(GeneratedBase, metaclass=StoringMeta): ...
|
||||
|
||||
reveal_type(StoresGenerated().generated) # revealed: int
|
||||
```
|
||||
|
||||
As with ordinary instance lookup, an instance assignment does not completely shadow a regular class
|
||||
attribute because the assignment may not have run. This applies whether the assignment is defined
|
||||
directly or inherited from a base class:
|
||||
|
||||
```py
|
||||
class InitializesGenerated(metaclass=StoringMeta):
|
||||
def __init__(self) -> None:
|
||||
self.generated: str = "instance"
|
||||
|
||||
reveal_type(InitializesGenerated().generated) # revealed: int | str
|
||||
|
||||
class InitializesInheritedGenerated:
|
||||
def __init__(self) -> None:
|
||||
self.generated: str = "instance"
|
||||
|
||||
class InheritsGenerated(InitializesInheritedGenerated, metaclass=StoringMeta): ...
|
||||
|
||||
reveal_type(InheritsGenerated().generated) # revealed: int | str
|
||||
```
|
||||
|
||||
A function is a descriptor when stored on a class, but not when stored directly on an instance. The
|
||||
instance attribute is therefore returned without descriptor binding:
|
||||
|
||||
```py
|
||||
from typing import Callable
|
||||
|
||||
class CallableStoringMeta(type):
|
||||
generated_callable: Callable[[int], str]
|
||||
|
||||
def __new__(mcls, name: str, bases: tuple[type, ...], namespace: dict[str, object]):
|
||||
namespace["generated_callable"] = lambda value: str(value)
|
||||
return super().__new__(mcls, name, bases, namespace)
|
||||
|
||||
class StoresInstanceCallable(metaclass=CallableStoringMeta):
|
||||
def __init__(self) -> None:
|
||||
self.generated_callable = lambda value: str(value)
|
||||
|
||||
reveal_type(StoresInstanceCallable().generated_callable(1)) # revealed: str
|
||||
```
|
||||
|
||||
A dynamic base may provide an instance attribute of any type, so a regular attribute stored by the
|
||||
metaclass does not remove that uncertainty. This remains true when an earlier static base provides a
|
||||
class attribute with the same name:
|
||||
|
||||
```py
|
||||
from typing import Any
|
||||
|
||||
DynamicGeneratedBase: Any = object
|
||||
|
||||
class InheritsDynamicGenerated(DynamicGeneratedBase, metaclass=StoringMeta): ...
|
||||
|
||||
reveal_type(InheritsDynamicGenerated().generated) # revealed: Any
|
||||
|
||||
class StaticGeneratedBase:
|
||||
generated = "static"
|
||||
|
||||
class InheritsStaticThenDynamicGenerated(StaticGeneratedBase, DynamicGeneratedBase, metaclass=StoringMeta): ...
|
||||
|
||||
reveal_type(InheritsStaticThenDynamicGenerated().generated) # revealed: Any
|
||||
```
|
||||
|
||||
Implicit special method lookup ignores attributes stored on an instance. It therefore uses the
|
||||
method supplied by a metaclass declaration even if the initializer assigns the same name:
|
||||
|
||||
```py
|
||||
class IteratingMeta(type):
|
||||
__iter__: Callable[[], Iterator[int]]
|
||||
|
||||
def __new__(mcls, name: str, bases: tuple[type, ...], namespace: dict[str, object]):
|
||||
def generated(self: object) -> Iterator[int]:
|
||||
return iter((1,))
|
||||
|
||||
namespace["__iter__"] = generated
|
||||
return super().__new__(mcls, name, bases, namespace)
|
||||
|
||||
class StoresInstanceIter(metaclass=IteratingMeta):
|
||||
def __init__(self) -> None:
|
||||
self.__iter__: Callable[[], Iterator[str]] = lambda: iter(("instance",))
|
||||
|
||||
reveal_type(iter(StoresInstanceIter())) # revealed: Iterator[int]
|
||||
```
|
||||
|
||||
Splitting the class MRO around a generated attribute preserves the usual treatment of dunder
|
||||
`Callable` attributes as bound-method descriptors:
|
||||
|
||||
```py
|
||||
def pow_impl(value: object, exponent: int) -> object:
|
||||
raise NotImplementedError
|
||||
|
||||
class PowMeta(type):
|
||||
__pow__: Callable[[object, int], object]
|
||||
|
||||
class Tensor(metaclass=PowMeta):
|
||||
__pow__: Callable[[object, int], object] = pow_impl
|
||||
|
||||
reveal_type(Tensor() ** 2) # revealed: object
|
||||
```
|
||||
|
||||
An annotation-only `ClassVar` on the constructed class is a class-namespace contract and takes
|
||||
precedence over the metaclass-generated attribute. An inherited `ClassVar` does not describe an
|
||||
instance attribute on the constructed class, but an inherited dataclass field adds an instance
|
||||
fallback:
|
||||
|
||||
```py
|
||||
from dataclasses import dataclass
|
||||
from typing import ClassVar
|
||||
|
||||
class DeclaresClassVarGenerated(metaclass=StoringMeta):
|
||||
generated: ClassVar[str]
|
||||
|
||||
reveal_type(DeclaresClassVarGenerated.generated) # revealed: str
|
||||
reveal_type(DeclaresClassVarGenerated().generated) # revealed: str
|
||||
|
||||
class ClassVarGeneratedBase:
|
||||
generated: ClassVar[str]
|
||||
|
||||
class InheritsClassVarGenerated(ClassVarGeneratedBase, metaclass=StoringMeta): ...
|
||||
|
||||
reveal_type(InheritsClassVarGenerated().generated) # revealed: int
|
||||
|
||||
@dataclass
|
||||
class DataclassGeneratedBase:
|
||||
generated: str = "instance"
|
||||
|
||||
class InheritsDataclassGenerated(DataclassGeneratedBase, metaclass=StoringMeta): ...
|
||||
|
||||
reveal_type(InheritsDataclassGenerated().generated) # revealed: int | str
|
||||
```
|
||||
|
||||
The attribute stored by the metaclass also shadows a descriptor inherited from a base class. Both
|
||||
that non-data class attribute and an instance assignment remain possible:
|
||||
|
||||
```py
|
||||
from typing import Literal
|
||||
|
||||
class InheritedGeneratedProperty:
|
||||
@property
|
||||
def generated(self) -> Literal["property"]:
|
||||
return "property"
|
||||
|
||||
class StringStoringMeta(type):
|
||||
generated: str
|
||||
|
||||
def __new__(mcls, name: str, bases: tuple[type, ...], namespace: dict[str, object]):
|
||||
namespace["generated"] = "class"
|
||||
return super().__new__(mcls, name, bases, namespace)
|
||||
|
||||
class InitializesShadowedGenerated:
|
||||
def __init__(self) -> None:
|
||||
self.generated: bytes = b"instance"
|
||||
|
||||
class ShadowsInheritedGeneratedProperty(
|
||||
InitializesShadowedGenerated, InheritedGeneratedProperty, metaclass=StringStoringMeta
|
||||
): ...
|
||||
|
||||
reveal_type(ShadowsInheritedGeneratedProperty().generated) # revealed: str | bytes
|
||||
```
|
||||
|
||||
If the metaclass instead stores a data descriptor on the new class, the descriptor takes precedence
|
||||
over an instance assignment:
|
||||
|
||||
```py
|
||||
class GeneratedDescriptor:
|
||||
def __get__(self, instance: object, owner: type | None = None) -> Literal["descriptor"]:
|
||||
return "descriptor"
|
||||
|
||||
def __set__(self, instance: object, value: int) -> None: ...
|
||||
|
||||
class DescriptorMeta(type):
|
||||
generated_descriptor: GeneratedDescriptor
|
||||
|
||||
def __new__(mcls, name: str, bases: tuple[type, ...], namespace: dict[str, object]):
|
||||
namespace["generated_descriptor"] = GeneratedDescriptor()
|
||||
return super().__new__(mcls, name, bases, namespace)
|
||||
|
||||
class UsesGeneratedDescriptor(metaclass=DescriptorMeta):
|
||||
def __init__(self) -> None:
|
||||
self.generated_descriptor = 1
|
||||
|
||||
reveal_type(UsesGeneratedDescriptor().generated_descriptor) # revealed: Literal["descriptor"]
|
||||
```
|
||||
|
||||
When a metaclass declaration uses a union, only the data descriptors in that union take precedence
|
||||
over an instance attribute. A non-descriptor member and the instance attribute both remain possible:
|
||||
|
||||
```py
|
||||
class MaybeDescriptorMeta(type):
|
||||
generated_descriptor: GeneratedDescriptor | int
|
||||
|
||||
def __new__(mcls, name: str, bases: tuple[type, ...], namespace: dict[str, object]):
|
||||
namespace["generated_descriptor"] = GeneratedDescriptor()
|
||||
return super().__new__(mcls, name, bases, namespace)
|
||||
|
||||
class UsesMaybeGeneratedDescriptorWithBytes(metaclass=MaybeDescriptorMeta):
|
||||
def __init__(self) -> None:
|
||||
self.generated_descriptor = b"instance"
|
||||
|
||||
reveal_type(UsesMaybeGeneratedDescriptorWithBytes().generated_descriptor) # revealed: Literal["descriptor"] | int | bytes
|
||||
```
|
||||
|
||||
A dynamic base likewise supplies the fallback for the non-descriptor members of a union:
|
||||
|
||||
```py
|
||||
class UsesMaybeGeneratedDescriptorWithDynamicBase(DynamicGeneratedBase, metaclass=MaybeDescriptorMeta): ...
|
||||
|
||||
reveal_type(UsesMaybeGeneratedDescriptorWithDynamicBase().generated_descriptor) # revealed: Literal["descriptor"] | Any
|
||||
```
|
||||
|
||||
Dynamic bases are ignored when descriptor detection requires a concrete `__get__` method:
|
||||
|
||||
```py
|
||||
class GeneratedGetMeta(type):
|
||||
__get__: Callable[[object, object | None, type], str]
|
||||
|
||||
def __new__(mcls, name: str, bases: tuple[type, ...], namespace: dict[str, object]):
|
||||
def generated_get(descriptor: object, instance: object | None, owner: type) -> str:
|
||||
return "generated"
|
||||
|
||||
namespace["__get__"] = generated_get
|
||||
return super().__new__(mcls, name, bases, namespace)
|
||||
|
||||
class GeneratedGetDescriptor(DynamicGeneratedBase, metaclass=GeneratedGetMeta): ...
|
||||
|
||||
class UsesGeneratedGetDescriptor:
|
||||
generated = GeneratedGetDescriptor()
|
||||
|
||||
reveal_type(UsesGeneratedGetDescriptor().generated) # revealed: str
|
||||
```
|
||||
|
||||
If the declaration can also be `Any`, the class attribute is not known to always be a data
|
||||
descriptor. The `Any` result subsumes the instance attribute type:
|
||||
|
||||
```py
|
||||
class MaybeDynamicDescriptorMeta(type):
|
||||
generated_descriptor: GeneratedDescriptor | Any
|
||||
|
||||
def __new__(mcls, name: str, bases: tuple[type, ...], namespace: dict[str, object]):
|
||||
namespace["generated_descriptor"] = GeneratedDescriptor()
|
||||
return super().__new__(mcls, name, bases, namespace)
|
||||
|
||||
class DynamicDescriptorInstanceBase:
|
||||
def __init__(self) -> None:
|
||||
self.generated_descriptor: bytes = b"instance"
|
||||
|
||||
class UsesMaybeDynamicDescriptor(DynamicDescriptorInstanceBase, metaclass=MaybeDynamicDescriptorMeta): ...
|
||||
|
||||
reveal_type(UsesMaybeDynamicDescriptor().generated_descriptor) # revealed: Literal["descriptor"] | Any
|
||||
```
|
||||
|
||||
An instance attribute annotation without a value does not store anything in the class namespace, so
|
||||
it cannot shadow a data descriptor. The annotation and non-descriptor members of the metaclass
|
||||
declaration all remain possible:
|
||||
|
||||
```py
|
||||
class DeclaresGeneratedDescriptor(metaclass=DescriptorMeta):
|
||||
generated_descriptor: int
|
||||
|
||||
reveal_type(DeclaresGeneratedDescriptor().generated_descriptor) # revealed: Literal["descriptor"]
|
||||
|
||||
class DeclaresMaybeGeneratedDescriptor(metaclass=MaybeDescriptorMeta):
|
||||
generated_descriptor: bytes
|
||||
|
||||
reveal_type(DeclaresMaybeGeneratedDescriptor().generated_descriptor) # revealed: Literal["descriptor"] | int | bytes
|
||||
```
|
||||
|
||||
Assigning an attribute through the first parameter of a static method does not describe an instance
|
||||
of the class:
|
||||
|
||||
```py
|
||||
class StaticMethodAssignment(metaclass=StoringMeta):
|
||||
@staticmethod
|
||||
def assign(obj: Any) -> None:
|
||||
obj.generated = "instance"
|
||||
|
||||
reveal_type(StaticMethodAssignment().generated) # revealed: int
|
||||
```
|
||||
|
||||
An own class-body binding takes precedence when it exists, while the metaclass member supplies the
|
||||
attribute before inherited class members on other paths. An unreachable binding does not suppress
|
||||
that fallback. An assignment inside a conditionally defined method is only a possible instance
|
||||
member, so the metaclass declaration remains as a fallback:
|
||||
|
||||
```py
|
||||
def returns_bool() -> bool:
|
||||
raise NotImplementedError
|
||||
|
||||
flag = returns_bool()
|
||||
|
||||
class PrecedenceMeta(type):
|
||||
generated: int | bytes
|
||||
|
||||
class InheritedPrecedenceGenerated:
|
||||
generated = "inherited"
|
||||
|
||||
class UnreachablePrecedenceGenerated(InheritedPrecedenceGenerated, metaclass=PrecedenceMeta):
|
||||
if False:
|
||||
generated = b"unreachable"
|
||||
|
||||
reveal_type(UnreachablePrecedenceGenerated().generated) # revealed: int | bytes
|
||||
|
||||
class DeclaredUnreachablePrecedenceGenerated(metaclass=PrecedenceMeta):
|
||||
generated: bytes
|
||||
if False:
|
||||
generated = b"unreachable"
|
||||
|
||||
reveal_type(DeclaredUnreachablePrecedenceGenerated().generated) # revealed: int | bytes
|
||||
|
||||
class ConditionalPrecedenceGenerated(InheritedPrecedenceGenerated, metaclass=PrecedenceMeta):
|
||||
if flag:
|
||||
generated = b"conditional"
|
||||
|
||||
reveal_type(ConditionalPrecedenceGenerated().generated) # revealed: bytes | int
|
||||
|
||||
class ConditionalGenerated(metaclass=StoringMeta):
|
||||
if flag:
|
||||
generated: int = 1
|
||||
|
||||
reveal_type(ConditionalGenerated().generated) # revealed: int
|
||||
|
||||
class ConditionalMethodAssignment(metaclass=StoringMeta):
|
||||
if flag:
|
||||
def assign(self) -> None:
|
||||
self.generated = "instance"
|
||||
|
||||
reveal_type(ConditionalMethodAssignment().generated) # revealed: int | str
|
||||
```
|
||||
|
||||
An attribute assigned in the metaclass body is available on classes that use the metaclass, but not
|
||||
on their instances:
|
||||
|
||||
```py
|
||||
class MetaclassAttributeOnly(type):
|
||||
metaclass_only: int = 1
|
||||
|
||||
class DoesNotInheritMetaclassAttribute(metaclass=MetaclassAttributeOnly): ...
|
||||
|
||||
reveal_type(DoesNotInheritMetaclassAttribute.metaclass_only) # revealed: int
|
||||
|
||||
# error: [unresolved-attribute]
|
||||
reveal_type(DoesNotInheritMetaclassAttribute().metaclass_only) # revealed: Unknown
|
||||
```
|
||||
|
||||
By contrast, an assignment through `cls` in a metaclass instance method writes to the constructed
|
||||
class namespace and is available through its instances. These inferred attributes are also inherited
|
||||
from base metaclasses:
|
||||
|
||||
```py
|
||||
class AssignmentOnlyMeta(type):
|
||||
def __init__(cls, name: str, bases: tuple[type, ...], namespace: dict[str, object]) -> None:
|
||||
cls.assignment_only: int = 1
|
||||
|
||||
class InfersAssignment(metaclass=AssignmentOnlyMeta):
|
||||
def method(self) -> None:
|
||||
reveal_type(self.assignment_only) # revealed: int
|
||||
|
||||
reveal_type(InfersAssignment.assignment_only) # revealed: int
|
||||
reveal_type(InfersAssignment().assignment_only) # revealed: int
|
||||
|
||||
class AssignmentBaseMeta(type):
|
||||
def __init__(cls, name: str, bases: tuple[type, ...], namespace: dict[str, object]) -> None:
|
||||
cls.inherited_assignment: str = "inherited"
|
||||
|
||||
class InheritedAssignmentMeta(AssignmentBaseMeta): ...
|
||||
class InfersInheritedAssignment(metaclass=InheritedAssignmentMeta): ...
|
||||
|
||||
reveal_type(InfersInheritedAssignment.inherited_assignment) # revealed: str
|
||||
reveal_type(InfersInheritedAssignment().inherited_assignment) # revealed: str
|
||||
```
|
||||
|
||||
When the constructed class inherits an attribute with the same name, lookup through an instance uses
|
||||
the same conservative behavior as ordinary instance lookup: an attribute inferred from a method does
|
||||
not completely eliminate the inherited value. This currently applies even to an unconditional
|
||||
assignment in the metaclass `__init__`.
|
||||
|
||||
```py
|
||||
class InitializingInheritedMeta(type):
|
||||
def __init__(cls, name: str, bases: tuple[type, ...], namespace: dict[str, object]) -> None:
|
||||
cls.initialized: int = 1
|
||||
|
||||
class InitializedBase:
|
||||
initialized = "inherited"
|
||||
|
||||
class Initialized(InitializedBase, metaclass=InitializingInheritedMeta): ...
|
||||
|
||||
reveal_type(Initialized.initialized) # revealed: int
|
||||
# TODO: Once we track definite initialization, this should narrow to `int`.
|
||||
reveal_type(Initialized().initialized) # revealed: int | str
|
||||
```
|
||||
|
||||
A conditional assignment in the metaclass `__init__` necessarily retains the inherited alternative:
|
||||
|
||||
```py
|
||||
def metaclass_condition() -> bool:
|
||||
raise NotImplementedError
|
||||
|
||||
class ConditionallyInitializingMeta(type):
|
||||
def __init__(cls, name: str, bases: tuple[type, ...], namespace: dict[str, object]) -> None:
|
||||
if metaclass_condition():
|
||||
cls.initialized: int = 1
|
||||
|
||||
class ConditionalBase:
|
||||
initialized = "inherited"
|
||||
|
||||
class ConditionallyInitialized(ConditionalBase, metaclass=ConditionallyInitializingMeta): ...
|
||||
|
||||
reveal_type(ConditionallyInitialized().initialized) # revealed: int | str
|
||||
```
|
||||
|
||||
An assignment in an arbitrary metaclass method likewise retains the inherited alternative because
|
||||
the method may not have run:
|
||||
|
||||
```py
|
||||
class InstallingMeta(type):
|
||||
def install(cls) -> None:
|
||||
cls.installed: int = 1
|
||||
|
||||
class InstalledBase:
|
||||
installed = "inherited"
|
||||
|
||||
class OptionallyInstalled(InstalledBase, metaclass=InstallingMeta): ...
|
||||
|
||||
reveal_type(OptionallyInstalled().installed) # revealed: int | str
|
||||
```
|
||||
|
||||
## Precedence between class and metaclass attributes
|
||||
|
||||
However, the metaclass attribute only takes precedence over a class-level attribute if it is a data
|
||||
descriptor. If it is a non-data descriptor or a normal attribute, the class-level attribute is used
|
||||
instead (see the [descriptor protocol tests] for data/non-data descriptor attributes):
|
||||
|
||||
```py
|
||||
from typing import Literal
|
||||
|
||||
class Meta2:
|
||||
attr: str = "metaclass value"
|
||||
|
||||
|
||||
@@ -1779,8 +1779,9 @@ static_assert(is_disjoint_from(FinalFoo, Proto))
|
||||
|
||||
A type does not have to be an `Instance` type in order to be a subtype of a protocol. Other
|
||||
protocols can be a subtype of a protocol, as can `ModuleLiteral` types, `ClassLiteral` types, and
|
||||
others. Another protocol can be a subtype of `HasX` either through "explicit" (nominal) inheritance
|
||||
from `HasX`, or by specifying a superset of `HasX`'s interface:
|
||||
others. A class object can satisfy the protocol through a declaration on its metaclass. Another
|
||||
protocol can be a subtype of `HasX` either through "explicit" (nominal) inheritance from `HasX`, or
|
||||
by specifying a superset of `HasX`'s interface:
|
||||
|
||||
`module.py`:
|
||||
|
||||
@@ -1820,9 +1821,8 @@ class Meta(type):
|
||||
|
||||
class UsesMeta(metaclass=Meta): ...
|
||||
|
||||
# TODO: these should pass
|
||||
static_assert(is_subtype_of(UsesMeta, HasX)) # error: [static-assert-error]
|
||||
static_assert(is_assignable_to(UsesMeta, HasX)) # error: [static-assert-error]
|
||||
static_assert(is_subtype_of(UsesMeta, HasX))
|
||||
static_assert(is_assignable_to(UsesMeta, HasX))
|
||||
```
|
||||
|
||||
## `ClassVar` attribute members
|
||||
|
||||
@@ -56,7 +56,7 @@ pub(crate) use self::type_expansion::expand_type;
|
||||
pub use crate::diagnostic::add_inferred_python_version_hint_to_diagnostic;
|
||||
use crate::place::{
|
||||
DefinedPlace, Definedness, Place, PlaceAndQualifiers, Provenance, TypeOrigin,
|
||||
builtins_module_scope, imported_symbol, known_module_symbol,
|
||||
builtins_module_scope, imported_symbol, known_module_symbol, place_from_bindings,
|
||||
};
|
||||
use crate::suppression::check_suppressions;
|
||||
use crate::types::bound_super::BoundSuperType;
|
||||
@@ -114,7 +114,7 @@ pub(crate) use special_form::TypedDictModule;
|
||||
use ty_python_core::definition::Definition;
|
||||
use ty_python_core::place::ScopedPlaceId;
|
||||
use ty_python_core::scope::ScopeId;
|
||||
use ty_python_core::{Truthiness, place_table, semantic_index};
|
||||
use ty_python_core::{Truthiness, place_table, semantic_index, use_def_map};
|
||||
|
||||
mod attribute_write;
|
||||
mod bool;
|
||||
@@ -2795,6 +2795,13 @@ impl<'db> Type<'db> {
|
||||
}
|
||||
}
|
||||
|
||||
Type::NominalInstance(instance) => self.to_meta_type(db).class_namespace_member(
|
||||
db,
|
||||
instance.class(db),
|
||||
name.as_str(),
|
||||
policy,
|
||||
),
|
||||
|
||||
Type::ClassLiteral(_) | Type::GenericAlias(_) | Type::SubclassOf(_) => self
|
||||
.to_meta_type(db)
|
||||
.class_object_member(db, name.as_str(), policy),
|
||||
@@ -2808,6 +2815,27 @@ impl<'db> Type<'db> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Look up the class member that participates in descriptor access through an instance.
|
||||
///
|
||||
/// The meta-type of a type variable preserves method binding to that type variable, but it does
|
||||
/// not carry attributes stored in a nominal upper-bound class's namespace by its metaclass.
|
||||
/// Add those attributes using the same lookup as a concrete nominal instance.
|
||||
fn instance_lookup_class_member_with_policy(
|
||||
self,
|
||||
db: &'db dyn Db,
|
||||
name: Name,
|
||||
policy: MemberLookupPolicy,
|
||||
) -> PlaceAndQualifiers<'db> {
|
||||
if let Type::TypeVar(_) = self
|
||||
&& let Some(class) = self.nominal_class(db)
|
||||
{
|
||||
self.to_meta_type(db)
|
||||
.class_namespace_member(db, class, name.as_str(), policy)
|
||||
} else {
|
||||
self.class_member_with_policy(db, name, policy)
|
||||
}
|
||||
}
|
||||
|
||||
/// Look up attributes stored in the namespace of a class object.
|
||||
///
|
||||
/// Besides attributes present in the class MRO, this includes attributes assigned to
|
||||
@@ -2863,6 +2891,167 @@ impl<'db> Type<'db> {
|
||||
}
|
||||
}
|
||||
|
||||
fn with_definedness(
|
||||
member: PlaceAndQualifiers<'db>,
|
||||
definedness: Definedness,
|
||||
) -> PlaceAndQualifiers<'db> {
|
||||
match member {
|
||||
PlaceAndQualifiers {
|
||||
place: Place::Defined(member),
|
||||
qualifiers,
|
||||
} => Place::Defined(member.with_definedness(definedness)).with_qualifiers(qualifiers),
|
||||
member => member,
|
||||
}
|
||||
}
|
||||
|
||||
/// Look up metaclass instance members in a constructed class's namespace.
|
||||
///
|
||||
/// A class object is an instance of its metaclass, and its instance storage is also the class
|
||||
/// namespace consulted when looking up attributes through instances of that class.
|
||||
///
|
||||
/// ```python
|
||||
/// class Meta(type):
|
||||
/// generated: int
|
||||
///
|
||||
/// class C(metaclass=Meta): ...
|
||||
///
|
||||
/// reveal_type(C().generated) # int
|
||||
/// ```
|
||||
///
|
||||
/// An own class binding or `ClassVar` contract shadows a normal generated attribute. During
|
||||
/// instance lookup, the result participates in the existing descriptor and instance-fallback
|
||||
/// logic.
|
||||
///
|
||||
/// Metaclass instance members participate, including inherited declarations and attributes
|
||||
/// inferred from instance methods. Class-body-only bindings remain attributes of the
|
||||
/// metaclass itself and are excluded.
|
||||
fn class_namespace_member(
|
||||
self,
|
||||
db: &'db dyn Db,
|
||||
class: ClassType<'db>,
|
||||
name: &str,
|
||||
policy: MemberLookupPolicy,
|
||||
) -> PlaceAndQualifiers<'db> {
|
||||
let class_attr = self
|
||||
.find_name_in_mro_with_policy(db, name, policy)
|
||||
.expect("The meta-type of an instance-like type should always have an MRO");
|
||||
let Some(metaclass) = class
|
||||
.metaclass(db)
|
||||
.to_instance(db)
|
||||
.and_then(|metaclass| metaclass.nominal_class(db))
|
||||
else {
|
||||
return class_attr;
|
||||
};
|
||||
let metaclass_member = metaclass.instance_member(db, name);
|
||||
if metaclass_member.is_undefined() {
|
||||
return class_attr;
|
||||
}
|
||||
let metaclass_member_is_implicit = metaclass_member
|
||||
.qualifiers
|
||||
.contains(TypeQualifiers::IMPLICIT_INSTANCE_ATTRIBUTE);
|
||||
|
||||
let own_class_member = class.class_literal(db).class_member_from_mro(
|
||||
db,
|
||||
name,
|
||||
policy,
|
||||
class.iter_mro(db).take(1),
|
||||
);
|
||||
// A non-ClassVar declaration-only member describes instance storage but does not add a
|
||||
// value to the class namespace.
|
||||
let own_class_member = if !own_class_member.is_class_var()
|
||||
&& class.static_class_literal(db).is_some_and(|(class, _)| {
|
||||
let scope = class.body_scope(db);
|
||||
place_table(db, scope)
|
||||
.symbol_id(name)
|
||||
.is_some_and(|symbol| {
|
||||
place_from_bindings(
|
||||
db,
|
||||
use_def_map(db, scope).end_of_scope_symbol_bindings(symbol),
|
||||
)
|
||||
.place
|
||||
.is_undefined()
|
||||
})
|
||||
}) {
|
||||
PlaceAndQualifiers::default()
|
||||
} else {
|
||||
own_class_member
|
||||
};
|
||||
let inherited_class_member = class.class_literal(db).class_member_from_mro(
|
||||
db,
|
||||
name,
|
||||
policy,
|
||||
class.iter_mro(db).skip(1),
|
||||
);
|
||||
|
||||
let metaclass_member = if metaclass_member_is_implicit {
|
||||
Self::with_definedness(metaclass_member, Definedness::PossiblyUndefined)
|
||||
} else {
|
||||
metaclass_member
|
||||
};
|
||||
let class_member = own_class_member
|
||||
.or_fall_back_to(db, || metaclass_member)
|
||||
.or_fall_back_to(db, || inherited_class_member);
|
||||
let class_member = if metaclass_member_is_implicit {
|
||||
// Preserve the existing convention that an inferred instance member is assumed to be
|
||||
// available even when no lower-precedence fallback exists.
|
||||
Self::with_definedness(class_member, Definedness::AlwaysDefined)
|
||||
} else {
|
||||
class_member
|
||||
};
|
||||
if policy.no_instance_fallback() || policy.require_concrete() {
|
||||
return class_member;
|
||||
}
|
||||
let Some(dynamic_instance_type) = class.iter_mro(db).find_map(|base| match base {
|
||||
ClassBase::Any | ClassBase::Dynamic(_) | ClassBase::Divergent(_) => {
|
||||
Some(Type::from(base))
|
||||
}
|
||||
_ => None,
|
||||
}) else {
|
||||
return class_member;
|
||||
};
|
||||
let dynamic_instance_fallback = Place::bound(dynamic_instance_type).into();
|
||||
|
||||
// A dynamic base can provide arbitrary instance storage that shadows non-data class
|
||||
// attributes. Preserve only the data-descriptor alternatives before falling back to the
|
||||
// actual dynamic type.
|
||||
let Some(class_member_ty) = class_member.ignore_possibly_undefined() else {
|
||||
return dynamic_instance_fallback;
|
||||
};
|
||||
if !class_member_ty.may_be_data_descriptor(db) {
|
||||
return dynamic_instance_fallback;
|
||||
}
|
||||
let PlaceAndQualifiers {
|
||||
place: Place::Defined(declaration),
|
||||
qualifiers,
|
||||
} = class_member
|
||||
else {
|
||||
return dynamic_instance_fallback;
|
||||
};
|
||||
let all_arms_are_possible_data_descriptors = declaration
|
||||
.ty
|
||||
.resolve_type_alias(db)
|
||||
.as_union()
|
||||
.is_none_or(|union| {
|
||||
union
|
||||
.elements(db)
|
||||
.iter()
|
||||
.all(|ty| ty.may_be_data_descriptor(db))
|
||||
});
|
||||
Place::Defined(DefinedPlace {
|
||||
ty: declaration
|
||||
.ty
|
||||
.filter_union(db, |ty| ty.may_be_data_descriptor(db)),
|
||||
definedness: if all_arms_are_possible_data_descriptors {
|
||||
declaration.definedness
|
||||
} else {
|
||||
Definedness::PossiblyUndefined
|
||||
},
|
||||
..declaration
|
||||
})
|
||||
.with_qualifiers(qualifiers)
|
||||
.or_fall_back_to(db, || dynamic_instance_fallback)
|
||||
}
|
||||
|
||||
/// This function roughly corresponds to looking up an attribute in the `__dict__` of an object.
|
||||
/// For instance-like types, this goes through the classes MRO and discovers attribute assignments
|
||||
/// in methods, as well as class-body declarations that we consider to be evidence for the presence
|
||||
@@ -3094,11 +3283,19 @@ impl<'db> Type<'db> {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Descriptor special-method lookup checks the descriptor's type, so instance storage
|
||||
// cannot shadow `__get__`. Dynamic MRO entries still participate in the lookup.
|
||||
let Place::Defined(DefinedPlace {
|
||||
ty: descr_get,
|
||||
definedness: descr_get_boundness,
|
||||
..
|
||||
}) = ty.class_member(db, "__get__".into()).place
|
||||
}) = ty
|
||||
.class_member_with_policy(
|
||||
db,
|
||||
"__get__".into(),
|
||||
MemberLookupPolicy::NO_INSTANCE_FALLBACK,
|
||||
)
|
||||
.place
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
@@ -3389,7 +3586,7 @@ impl<'db> Type<'db> {
|
||||
meta_attr_kind,
|
||||
) = Self::try_call_dunder_get_on_attribute(
|
||||
db,
|
||||
self.class_member_with_policy(db, name.into(), member_policy),
|
||||
self.instance_lookup_class_member_with_policy(db, name.into(), member_policy),
|
||||
Some(receiver),
|
||||
self.to_meta_type(db),
|
||||
);
|
||||
|
||||
@@ -1095,32 +1095,7 @@ impl<'db> StaticClassLiteral<'db> {
|
||||
name: &str,
|
||||
policy: MemberLookupPolicy,
|
||||
) -> PlaceAndQualifiers<'db> {
|
||||
fn into_function_like_callable<'d>(db: &'d dyn Db, ty: Type<'d>) -> Type<'d> {
|
||||
match ty {
|
||||
Type::Callable(callable_ty) => Type::Callable(CallableType::new(
|
||||
db,
|
||||
callable_ty.signatures(db),
|
||||
CallableTypeKind::FunctionLike,
|
||||
callable_ty.provenance(db),
|
||||
)),
|
||||
Type::Union(union) => {
|
||||
union.map(db, |element| into_function_like_callable(db, *element))
|
||||
}
|
||||
Type::Intersection(intersection) => intersection
|
||||
.map_positive(db, |element| into_function_like_callable(db, *element)),
|
||||
_ => ty,
|
||||
}
|
||||
}
|
||||
|
||||
let mut member = self.class_member_inner(db, None, name, policy);
|
||||
|
||||
// We generally treat dunder attributes with `Callable` types as function-like callables.
|
||||
// See `callables_as_descriptors.md` for more details.
|
||||
if name.starts_with("__") && name.ends_with("__") {
|
||||
member = member.map_type(|ty| into_function_like_callable(db, ty));
|
||||
}
|
||||
|
||||
member
|
||||
self.class_member_inner(db, None, name, policy)
|
||||
}
|
||||
|
||||
pub(super) fn class_member_inner(
|
||||
@@ -1140,6 +1115,23 @@ impl<'db> StaticClassLiteral<'db> {
|
||||
policy: MemberLookupPolicy,
|
||||
mro_iter: impl Iterator<Item = ClassBase<'db>>,
|
||||
) -> PlaceAndQualifiers<'db> {
|
||||
fn into_function_like_callable<'d>(db: &'d dyn Db, ty: Type<'d>) -> Type<'d> {
|
||||
match ty {
|
||||
Type::Callable(callable_ty) => Type::Callable(CallableType::new(
|
||||
db,
|
||||
callable_ty.signatures(db),
|
||||
CallableTypeKind::FunctionLike,
|
||||
callable_ty.provenance(db),
|
||||
)),
|
||||
Type::Union(union) => {
|
||||
union.map(db, |element| into_function_like_callable(db, *element))
|
||||
}
|
||||
Type::Intersection(intersection) => intersection
|
||||
.map_positive(db, |element| into_function_like_callable(db, *element)),
|
||||
_ => ty,
|
||||
}
|
||||
}
|
||||
|
||||
let result = MroLookup::new(db, mro_iter).class_member(
|
||||
name,
|
||||
policy,
|
||||
@@ -1147,12 +1139,20 @@ impl<'db> StaticClassLiteral<'db> {
|
||||
self.is_known(db, KnownClass::Object),
|
||||
);
|
||||
|
||||
match result {
|
||||
let mut member = match result {
|
||||
ClassMemberResult::Done(result) => result.finalize(db),
|
||||
ClassMemberResult::TypedDict(module) => {
|
||||
typed_dict_class_member(db, self.identity_specialization(db), module, policy, name)
|
||||
}
|
||||
};
|
||||
|
||||
// We generally treat dunder attributes with `Callable` types as function-like callables.
|
||||
// See `callables_as_descriptors.md` for more details.
|
||||
if name.starts_with("__") && name.ends_with("__") {
|
||||
member = member.map_type(|ty| into_function_like_callable(db, ty));
|
||||
}
|
||||
|
||||
member
|
||||
}
|
||||
|
||||
/// Returns the inferred type of the class member named `name`. Only bound members
|
||||
|
||||
@@ -1052,7 +1052,9 @@ fn protocol_member_read_type<'db>(
|
||||
member.name,
|
||||
Place::Undefined.into(),
|
||||
InstanceFallbackShadowsNonDataDescriptor::No,
|
||||
MemberLookupPolicy::default(),
|
||||
// The undefined fallback excludes instance members. Keep the class
|
||||
// member lookup from reintroducing dynamic instance fallbacks.
|
||||
MemberLookupPolicy::NO_INSTANCE_FALLBACK,
|
||||
)
|
||||
.place
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user