## Custom `__call__` on metaclass When a metaclass defines a custom `__call__` method, it controls what happens when the class is called. If the metaclass `__call__` returns an "instance type" (subtype of the class being constructed), then the class' `__new__` and `__init__` are checked as usual (see `class/constructor.md`). But if the metaclass `__call__` returns a non-instance type, then `__new__` and `__init__` are skipped and the return type of `__call__` is used directly. ### Metaclass `__call__` returning non-instance type ```py class Meta(type): def __call__(cls, x: int, y: str) -> str: return y class Foo(metaclass=Meta): ... reveal_type(Foo(1, "hello")) # revealed: str a: str = Foo(1, "hello") # OK ``` ### Metaclass `__call__` takes precedence over `__init__` and `__new__` ```py class Meta(type): def __call__(cls) -> str: return "hello" class Foo(metaclass=Meta): def __new__(cls, x: int) -> "Foo": return object.__new__(cls) def __init__(self, x: int, y: int) -> None: pass # The metaclass __call__ takes precedence, so no arguments are needed # and the return type is str, not Foo. reveal_type(Foo()) # revealed: str ``` ### Metaclass `__call__` with wrong arguments ```py class Meta(type): def __call__(cls, x: int) -> int: return x class Foo(metaclass=Meta): ... # error: [invalid-argument-type] reveal_type(Foo("wrong")) # revealed: int # error: [missing-argument] reveal_type(Foo()) # revealed: int # error: [too-many-positional-arguments] reveal_type(Foo(1, 2)) # revealed: int ``` ### Metaclass `__call__` with TypeVar return type When the metaclass `__call__` returns a TypeVar bound to the class type, it's essentially a pass-through to the normal constructor machinery. In this case, we should still check the `__new__` and `__init__` signatures. ```py from typing import TypeVar T = TypeVar("T") class Meta(type): def __call__(cls: type[T], *args, **kwargs) -> T: return object.__new__(cls) class Foo(metaclass=Meta): def __init__(self, x: int) -> None: pass # The metaclass __call__ returns T (bound to Foo), so we check __init__ parameters. Foo() # error: [missing-argument] reveal_type(Foo(1)) # revealed: Foo ``` ### Metaclass `__call__` with no return type annotation When the metaclass `__call__` has no return type annotation (returns `Unknown`), we should still check the `__new__` and `__init__` signatures, and infer the instance return type. ```py class Meta(type): def __call__(cls, *args, **kwargs): return object.__new__(cls) class Foo(metaclass=Meta): def __init__(self, x: int) -> None: pass # No return type annotation means we fall through to check __init__ parameters. Foo() # error: [missing-argument] reveal_type(Foo(1)) # revealed: Foo ``` ### Metaclass `__call__` with specific parameters When the metaclass `__call__` has specific parameters (not just `*args, **kwargs`), we validate them even when the return type is an instance type. Here both `__new__` and `__init__` accept anything, so the errors must come from the metaclass `__call__`. ```py from typing import Any, TypeVar T = TypeVar("T") class Meta(type): def __call__(cls: type[T], x: int) -> T: return object.__new__(cls) class Foo(metaclass=Meta): def __new__(cls, *args: Any, **kwargs: Any) -> "Foo": return object.__new__(cls) def __init__(self, *args: Any, **kwargs: Any) -> None: pass # The metaclass `__call__` requires exactly one `int` argument. # error: [invalid-argument-type] reveal_type(Foo("wrong")) # revealed: Foo # error: [missing-argument] reveal_type(Foo()) # revealed: Foo # error: [too-many-positional-arguments] reveal_type(Foo(1, 2)) # revealed: Foo reveal_type(Foo(1)) # revealed: Foo ``` ### Metaclass `__call__` returning the class instance type When the metaclass `__call__` returns the constructed class type (or a subclass), it's not overriding normal construction. Per the spec, `__new__`/`__init__` should still be evaluated. ```py class Meta(type): def __call__(cls, *args, **kwargs) -> "Foo": return super().__call__(*args, **kwargs) class Foo(metaclass=Meta): def __init__(self, x: int) -> None: pass # The metaclass __call__ returns Foo, so we fall through to check __init__. Foo() # error: [missing-argument] Foo("wrong") # error: [invalid-argument-type] reveal_type(Foo(1)) # revealed: Foo ``` ### Metaclass `__call__` returning a specific class affects subclasses When a metaclass `__call__` returns a specific class (e.g., `-> Foo`), this is an instance type for `Foo` itself, so `__init__` is checked. But for a subclass `Bar(Foo)`, the return type `Foo` is NOT an instance of `Bar`, so the metaclass `__call__` is used directly and `Bar.__init__` is skipped. ```py from typing import Any class Meta(type): def __call__(cls, *args: Any, **kwargs: Any) -> "Foo": return super().__call__(*args, **kwargs) class Foo(metaclass=Meta): def __init__(self, x: int) -> None: pass class Bar(Foo): def __init__(self, y: str) -> None: pass # For Foo: return type `Foo` IS an instance of `Foo`, so `__init__` is checked. Foo() # error: [missing-argument] reveal_type(Foo(1)) # revealed: Foo # For Bar: return type `Foo` is NOT an instance of `Bar`, so `__init__` is # skipped and the metaclass `__call__` (which accepts `*args, **kwargs`) is # used directly. reveal_type(Bar()) # revealed: Foo reveal_type(Bar("hello")) # revealed: Foo ``` ### Metaclass `__call__` returning `Any` When a metaclass `__call__` returns `Any`, the spec says to assume that the return type is not an instance of the class being constructed, so we use the metaclass `__call__` signature directly and skip `__new__`/`__init__` validation. It's a bit odd to have different behavior for `-> Any` than for no annotation, but that's what the spec says, and for now we follow it. ```py from typing import Any class Meta(type): def __call__(cls, *args: Any, **kwargs: Any) -> Any: return super().__call__(*args, **kwargs) class Foo(metaclass=Meta): def __init__(self, x: int) -> None: pass # The metaclass `__call__` accepts `(*args, **kwargs)` and returns `Any`, # so we use that directly, skipping `__init__` validation. reveal_type(Foo()) # revealed: Any reveal_type(Foo("wrong")) # revealed: Any ``` ### Metaclass `__call__` returning `Never` When metaclass `__call__` returns `Never`, construction is terminal. We use metaclass `__call__` directly and skip `__new__` and `__init__`. ```py from typing_extensions import Never class Meta(type): def __call__(cls) -> Never: raise NotImplementedError class C(metaclass=Meta): def __new__(cls, x: int) -> "C": return object.__new__(cls) def __init__(self, x: int) -> None: pass # `__new__` and `__init__` are skipped because metaclass `__call__` never returns. reveal_type(C()) # revealed: Never ``` ### Overloaded metaclass `__call__` with mixed return types When a metaclass `__call__` is overloaded and some overloads return the class instance type while others return a different type, non-instance-returning overloads use the metaclass `__call__` directly, while instance-returning overloads are replaced by `__init__` validation. ```py from typing import Any, overload from typing_extensions import Literal class Meta(type): @overload def __call__(cls, x: int) -> int: ... @overload def __call__(cls, x: str) -> "Foo": ... def __call__(cls, x: int | str) -> Any: return super().__call__(x) class Foo(metaclass=Meta): def __init__(self) -> None: pass # The `int` overload from the metaclass `__call__` is selected; its return type # is not an instance of `Foo`, so it is used directly. reveal_type(Foo(1)) # revealed: int # The `str -> Foo` metaclass overload matches and returns an instance, so `__init__` # is also validated. # error: [too-many-positional-arguments] reveal_type(Foo("hello")) # revealed: Foo # No overload matches. # error: [no-matching-overload] reveal_type(Foo()) # revealed: Unknown def _(a: Any): # error: [too-many-positional-arguments] reveal_type(Foo(a)) # revealed: Unknown ``` ### Mixed metaclass `__call__` overloads should not become declaration-order dependent Reversing the declaration order of the same mixed overload set should not change the result when overload resolution falls back to `Unknown`. ```py from typing import Any, TypeVar, overload from missing import Unknown # type: ignore T = TypeVar("T") class ReverseMeta(type): @overload def __call__(cls: type[T], x: str) -> str: ... @overload def __call__(cls: type[T], x: int) -> T: ... def __call__(cls, x: int | str) -> object: return super().__call__() class ReverseMetaTarget(metaclass=ReverseMeta): def __init__(self) -> None: ... def _(a: Any, u: Unknown): # error: [too-many-positional-arguments] reveal_type(ReverseMetaTarget(a)) # revealed: Unknown # error: [too-many-positional-arguments] reveal_type(ReverseMetaTarget(u)) # revealed: Unknown ``` ### Overloaded metaclass `__call__` preserving strict-subclass return ```py from typing import Any, overload class Meta(type): @overload def __call__(cls, x: int) -> int: ... @overload def __call__(cls, x: str) -> "Child": ... def __call__(cls, x: int | str) -> Any: return super().__call__(x) class Parent(metaclass=Meta): def __init__(self, x: str) -> None: pass class Child(Parent): ... reveal_type(Parent(1)) # revealed: int reveal_type(Parent("hello")) # revealed: Child ``` ### Overloaded metaclass `__call__` returning only non-instance types When all overloads of a metaclass `__call__` return non-instance types, the metaclass fully overrides `type.__call__` and `__init__` is not checked. ```py from typing import Any, overload class Meta(type): @overload def __call__(cls, x: int) -> int: ... @overload def __call__(cls, x: str) -> str: ... def __call__(cls, x: int | str) -> Any: return x class Bar(metaclass=Meta): def __init__(self, x: int, y: int) -> None: pass # `__init__` is not checked: it requires two `int` args, but we only pass one. # No error is raised because the metaclass `__call__` controls construction. reveal_type(Bar(1)) # revealed: int reveal_type(Bar("hello")) # revealed: str ``` ### Invalid overloaded non-instance metaclass `__call__` should not invent an instance return If no overload matches, we should still report `Unknown` rather than falling back to the class instance type. ```py from typing import overload class OnlyNonInstanceMeta(type): @overload def __call__(cls, x: int) -> int: ... @overload def __call__(cls, x: str) -> str: ... def __call__(cls, x: int | str) -> object: raise NotImplementedError class OnlyNonInstanceMetaTarget(metaclass=OnlyNonInstanceMeta): pass # error: [no-matching-overload] reveal_type(OnlyNonInstanceMetaTarget(1.2)) # revealed: Unknown ``` ### Overloaded metaclass `__call__` with non-class return forms When all overloads return non-instance types that aren't simple class instances (e.g., `Callable`), `__init__` should still be skipped. ```py from typing import Any, Callable, overload class Meta(type): @overload def __call__(cls, x: int) -> Callable[[], int]: ... @overload def __call__(cls, x: str) -> Callable[[], str]: ... def __call__(cls, x: int | str) -> Any: return lambda: x class Baz(metaclass=Meta): def __init__(self, x: int, y: int) -> None: pass # `__init__` is not checked: it requires two `int` args, but we only pass one. # No error is raised because the metaclass `__call__` controls construction. reveal_type(Baz(1)) # revealed: () -> int reveal_type(Baz("hello")) # revealed: () -> str ``` ### If metaclass `__call__` fails, `__new__` is irrelevant ```py class Meta(type): def __call__(cls, x: str) -> "C": raise NotImplementedError class C(metaclass=Meta): def __new__(cls, x: bytes) -> int: return 1 # error: [invalid-argument-type] reveal_type(C(b"hello")) # revealed: C ``` ### Metaclass `__call__` is not a simple method ```py class MetaCall: def __call__(self) -> int: return 1 class Meta(type): __call__: MetaCall = MetaCall() class C(metaclass=Meta): ... reveal_type(C()) # revealed: int ``` ### Metaclass classmethods wrapping callable objects A metaclass can wrap a callable instance in `classmethod`. Passing the class as a callback binds the metaclass argument and preserves the wrapped callable's remaining parameters and return type. ```py from typing import Callable class MetaCall: def __call__(self, cls: type, value: int) -> str: return str(value) class Meta(type): __call__ = classmethod(MetaCall()) class C(metaclass=Meta): ... def call_factory(factory: Callable[[int], str]) -> str: return factory(1) reveal_type(C(1)) # revealed: str reveal_type(call_factory(C)) # revealed: str ``` A callback expecting a no-argument constructor returning `C` is incompatible with this metaclass. ```py wrong_factory: Callable[[], C] = C # error: [invalid-assignment] ``` ### Invalid overloaded downstream `__new__` If metaclass `__call__` forwards to normal construction by returning the constructed instance type, and the downstream overloaded `__new__` doesn't match, we error, but still assume the class instance type. ```py from typing import TypeVar, overload T = TypeVar("T") class Meta(type): def __call__(cls: type[T], x: object) -> T: raise NotImplementedError class D(metaclass=Meta): @overload def __new__(cls, x: int) -> int: ... @overload def __new__(cls, x: str) -> str: ... def __new__(cls, x: object) -> object: raise NotImplementedError # error: [no-matching-overload] reveal_type(D(1.2)) # revealed: D ``` ### Mixed `__new__` and mixed metaclass `__call__` If both metaclass `__call__` and `__new__` are mixed (some overloads instance-returning and some non-instance), the fallback chain works as expected: `__new__` is only considered if metaclass `__call__` is instance-returning, and `__init__` is only considered if both `__call__` and `__new__` are instance-returning. ```py from __future__ import annotations from typing import Any, Literal, overload class A: ... class B: ... class C: ... class D: ... class Meta(type): @overload def __call__(cls, x: A) -> A: ... @overload def __call__(cls, x: B) -> Test: ... @overload def __call__(cls, x: C) -> Test: ... @overload def __call__(cls, x: str) -> Test: ... def __call__(cls, x: A | B | C | str) -> A | Test: raise NotImplementedError() class Test(metaclass=Meta): @overload def __new__(cls, x: B) -> B: ... @overload def __new__(cls, x: D) -> D: ... @overload def __new__(cls, x: str) -> Test: ... def __new__(cls, x: B | D | str) -> B | D | Test: raise NotImplementedError() def __init__(self, x: Literal["ok"]) -> None: pass # `A` matches the first metaclass overload, which returns `A`, bypassing `__new__` and `__init__` # since `A` is not a subtype of `Test`. reveal_type(Test(A())) # revealed: A # `B` returns `Test` from metaclass `__call__` and returns `B` from `__new__`, bypassing `__init__` # since `B` is not a subtype of `Test`. reveal_type(Test(B())) # revealed: B # `C` returns `Test` from metaclass `__call__` and fails the call to `__new__`. # error: [no-matching-overload] reveal_type(Test(C())) # revealed: Test # `D` fails metaclass `__call__`, so never reaches `__new__` or `__init__`, and we infer `Unknown` # since not all overloads are instance-returning. # error: [no-matching-overload] reveal_type(Test(D())) # revealed: Unknown # `str` returns `Test` from both `__call__` and `__new__`, but `__init__` rejects `Literal["bad"]`. # error: [invalid-argument-type] reveal_type(Test("bad")) # revealed: Test # `Literal["ok"]` returns `Test` from both `__call__` and `__new__`, and is accepted by `__init__`. reveal_type(Test("ok")) # revealed: Test ``` ## Default ```py class M(type): ... reveal_type(M.__class__) # revealed: ``` ## `object` ```py reveal_type(object.__class__) # revealed: ``` ## `type` ```py reveal_type(type.__class__) # revealed: ``` ## Basic ```py class M(type): ... class B(metaclass=M): ... reveal_type(B.__class__) # revealed: ``` ## Invalid metaclass A class which doesn't inherit `type` (and/or doesn't implement a custom `__new__` accepting the same arguments as `type.__new__`) isn't a valid metaclass. ```py class M: ... class A(metaclass=M): ... # TODO: emit a diagnostic for the invalid metaclass reveal_type(A.__class__) # revealed: ``` ## Linear inheritance If a class is a subclass of a class with a custom metaclass, then the subclass will also have that metaclass. ```py class M(type): ... class A(metaclass=M): ... class B(A): ... reveal_type(B.__class__) # revealed: ``` ## Linear inheritance with PEP 695 generic class The same is true if the base with the metaclass is a generic class. ```toml [environment] python-version = "3.13" ``` ```py from typing import Any class M(type): ... class A[T](metaclass=M): ... class B(A[Any]): ... class C(A[int]): ... reveal_type(B.__class__) # revealed: reveal_type(C.__class__) # revealed: ``` ## Inheritance from an intersection type Narrowing can cause a class object to have an intersection type. A class that inherits from this intersection should still inherit the class object's metaclass. ```py from typing import Any class Meta(type): meta_attr: int = 1 class Base(metaclass=Meta): base_attr: str = "" def f(other: Any): if Base is other: reveal_type(Base) # revealed: & Any class Child(Base): ... reveal_type(Child.base_attr) # revealed: str reveal_type(Child.__class__) # revealed: reveal_type(Child.meta_attr) # revealed: int ``` ## Conflict (1) The metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases. ("Strict subclass" is a synonym for "proper subclass"; a non-strict subclass can be a subclass or the class itself.) We report the conflict and infer an unknown metaclass. Attributes supplied by either conflicting metaclass are also unknown, regardless of the order of the bases. ```py class M1(type): value: int class M2(type): value: str class A(metaclass=M1): ... class B(metaclass=M2): ... # error: [conflicting-metaclass] "The metaclass of a derived class (`C`) must be a subclass of the metaclasses of all its bases, but `M1` (metaclass of base class `A`) and `M2` (metaclass of base class `B`) have no subclass relationship" class C(A, B): ... class Reversed(B, A): ... # error: [conflicting-metaclass] reveal_type(C.__class__) # revealed: type[Unknown] reveal_type(type(C)) # revealed: type[Unknown] reveal_type(C.value) # revealed: Unknown reveal_type(Reversed.value) # revealed: Unknown ``` The metaclass and its attributes are also unknown on subclasses of `C`: ```py def check_subclass(cls: type[C]): reveal_type(cls.__class__) # revealed: type[Unknown] reveal_type(type(cls)) # revealed: type[Unknown] reveal_type(cls.value) # revealed: Unknown ``` Even with an unknown metaclass, `C` is a class object. It can be assigned to a metaclass instance type, but not to `None`. Overload resolution preserves this distinction: ```py from typing import overload @overload def select(cls: None) -> None: ... @overload def select(cls: type) -> int: ... def select(cls: type | None) -> int | None: ... meta: M1 = C none: None = C # error: [invalid-assignment] reveal_type(select(C)) # revealed: int def check_assignability(cls: type[C]): meta: M1 = cls none: None = cls # error: [invalid-assignment] reveal_type(select(cls)) # revealed: int ``` The same applies to classes created with `type()`: ```py Dynamic = type("Dynamic", (A, B), {}) # error: [conflicting-metaclass] reveal_type(select(Dynamic)) # revealed: int ``` ## Conflict (2) The metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases. ("Strict subclass" is a synonym for "proper subclass"; a non-strict subclass can be a subclass or the class itself.) An explicit metaclass that conflicts with a base's metaclass is retained for error recovery. This preserves the types of attributes declared on the class and its explicit metaclass. ```py class M1(type): ... class M2(type): value: str class A(metaclass=M1): ... # error: [conflicting-metaclass] "The metaclass of a derived class (`B`) must be a subclass of the metaclasses of all its bases, but `M2` (metaclass of `B`) and `M1` (metaclass of base class `A`) have no subclass relationship" class B(A, metaclass=M2): declared: int reveal_type(B.__class__) # revealed: reveal_type(type(B)) # revealed: reveal_type(B.value) # revealed: str reveal_type(B.declared) # revealed: int ``` Descendants also inherit the recovered metaclass: ```py class Child(B): ... reveal_type(Child.__class__) # revealed: def check_subclass(cls: type[B]): reveal_type(cls.__class__) # revealed: type[M2] reveal_type(type(cls)) # revealed: type[M2] reveal_type(cls.value) # revealed: str reveal_type(cls.declared) # revealed: int ``` ## Explicit metaclass recovery after selecting a more derived candidate A base can supply a more derived metaclass before another base introduces a conflict. Error recovery still uses the original explicit metaclass, regardless of the order of the bases. ```py class Meta(type): ... class DerivedMeta(Meta): ... class OtherMeta(type): ... class Derived(metaclass=DerivedMeta): ... class Other(metaclass=OtherMeta): ... class Forward(Derived, Other, metaclass=Meta): ... # error: [conflicting-metaclass] class Reverse(Other, Derived, metaclass=Meta): ... # error: [conflicting-metaclass] reveal_type(Forward.__class__) # revealed: reveal_type(Reverse.__class__) # revealed: ``` ## Common metaclass A class has two explicit bases, both of which have the same metaclass. ```py class M(type): ... class A(metaclass=M): ... class B(metaclass=M): ... class C(A, B): ... reveal_type(C.__class__) # revealed: ``` ## Conflicting metaclasses through unions and intersections A union retains the known metaclass of its valid alternative and the unknown metaclass of its invalid alternative. Type aliases and attribute lookup preserve this uncertainty. ```py from typing import Any, TypeAlias class Meta(type): value: int class OtherMeta(type): ... class Valid(metaclass=Meta): ... class Base(metaclass=Meta): ... class Other(metaclass=OtherMeta): ... class Invalid(Other, Base): ... # error: [conflicting-metaclass] Classes: TypeAlias = type[Invalid] | type[Valid] def check_union(cls: Classes): reveal_type(cls.__class__) # revealed: type[Unknown | Meta] reveal_type(type(cls)) # revealed: type[Unknown | Meta] reveal_type(cls.value) # revealed: Unknown | int ``` Narrowing the invalid class to an intersection does not make its metaclass known: ```py def check_intersection(other: Any): if Invalid is other: reveal_type(Invalid) # revealed: & Any reveal_type(Invalid.__class__) # revealed: type[Unknown] reveal_type(type(Invalid)) # revealed: type[Unknown] reveal_type(Invalid.value) # revealed: Unknown ``` ## Protocol metaclass inheritance A protocol declared in Python source uses `typing._ProtocolMeta`, which derives from `ABCMeta`. Explicitly specifying `ABCMeta` selects the more derived `_ProtocolMeta`. A compatible custom metaclass is preserved, including when its base is obtained by calling `type`. ```py from abc import ABC, ABCMeta from typing import Protocol class P(Protocol): ... class Base(ABC): ... class Combined(Base, P): ... class ExplicitABC(Protocol, metaclass=ABCMeta): ... reveal_type(type(Combined)) # revealed: reveal_type(type(ExplicitABC)) # revealed: class Meta(type(Protocol)): ... class Derived(Base, P, metaclass=Meta): ... reveal_type(type(Derived)) # revealed: ``` An unrelated metaclass conflicts with this constraint, both when declaring a protocol and when subclassing an existing one. ```py class Unrelated(type): ... # error: [conflicting-metaclass] "`_ProtocolMeta` (metaclass of base class `typing.Protocol`)" class InvalidDirect(Protocol, metaclass=Unrelated): ... class InvalidSubclass(P, metaclass=Unrelated): ... # error: [conflicting-metaclass] ``` Deriving an otherwise unrelated metaclass from `ABCMeta` does not make it compatible with `_ProtocolMeta`. ```py class UnrelatedABC(ABCMeta): ... class InvalidABC(P, metaclass=UnrelatedABC): ... # error: [conflicting-metaclass] ``` ## Protocol metaclass fallback in typeshed Typeshed can list `Protocol` as a base even when the runtime class does not inherit from `typing.Protocol`. For example, `collections.abc.Iterable` is an ordinary abstract base class at runtime. Its typeshed definition therefore does not establish that the class has `_ProtocolMeta` as its metaclass. When no custom metaclass is selected, ty uses `ABCMeta` instead of `type` for class attribute lookup. This fallback makes ABC methods such as `register` available: ```py from collections.abc import Iterable class Registered: ... reveal_type(type(Iterable)) # revealed: reveal_type(Iterable.register(Registered)) # revealed: type[Registered] ``` The inferred `ABCMeta` is not a claim about the exact runtime metaclass. It does not constrain subclasses, so a subclass can choose a metaclass unrelated to `ABCMeta` without a conflict. ```py class Meta(type): ... class Direct(Iterable[object], metaclass=Meta): ... reveal_type(type(Direct)) # revealed: ``` ## Protocol metaclass fallback in a custom typeshed The same fallback applies to a configured typeshed. These minimal standard-library stubs provide the types used below. ```toml [environment] typeshed = "/typeshed" ``` `/typeshed/stdlib/builtins.pyi`: ```pyi class object: ... class type: ... class tuple: ... ``` `/typeshed/stdlib/abc.pyi`: ```pyi class ABCMeta(type): ... ``` `/typeshed/stdlib/typing.pyi`: ```pyi from abc import ABCMeta class _SpecialForm: ... Protocol: _SpecialForm class _ProtocolMeta(ABCMeta): ... def reveal_type(obj, /): ... ``` `/typeshed/stdlib/interface.pyi`: ```pyi from typing import Protocol class Interface(Protocol): ... ``` The typeshed protocol gets the lookup fallback, but an unrelated explicit metaclass wins. `main.py`: ```py from interface import Interface from typing import reveal_type class Meta(type): ... class Derived(Interface, metaclass=Meta): ... reveal_type(Interface.__class__) # revealed: reveal_type(Derived.__class__) # revealed: ``` ## Inheritance of a typeshed protocol metaclass fallback A source-defined subclass inherits the same non-constraining fallback from a typeshed protocol. An indirect or dynamically created subclass can choose an unrelated metaclass. `Child` can also share a subclass with `Other`, despite `Other`'s final metaclass, and `type[Child]` is not a subtype of `ABCMeta`. ```py from abc import ABCMeta from collections.abc import Iterable from typing import final from ty_extensions import static_assert from ty_extensions._internal import is_disjoint_from, is_subtype_of class Child(Iterable[object]): ... @final class Meta(type): ... class Other(metaclass=Meta): ... class Left(Child, Other): ... class Right(Other, Child): ... Dynamic = type("Dynamic", (Iterable,), {}) Combined = type("Combined", (Child, Other), {}) class ViaDynamic(Dynamic, metaclass=Meta): ... reveal_type(type(Child)) # revealed: reveal_type(type(Left)) # revealed: reveal_type(type(Right)) # revealed: reveal_type(type(Combined)) # revealed: reveal_type(type(ViaDynamic)) # revealed: static_assert(not is_disjoint_from(Child, Other)) static_assert(not is_subtype_of(type[Child], ABCMeta)) ``` Explicitly listing `Protocol` in source declares a new protocol with a `_ProtocolMeta` constraint, even when another base contributes only the typeshed fallback. ```py from typing import Protocol class SourceProtocol(Iterable[object], Protocol): ... class Invalid(SourceProtocol, metaclass=Meta): ... # error: [conflicting-metaclass] ``` ## Explicit typeshed protocol metaclasses Explicitly choosing the inferred `ABCMeta` makes it a real constraint on later subclasses. ```py from collections.abc import Iterable class Meta(type): ... class Pinned(Iterable[object], metaclass=type(Iterable)): ... class Invalid(Pinned, metaclass=Meta): ... # error: [conflicting-metaclass] reveal_type(type(Pinned)) # revealed: ``` ## Typeshed protocol metaclass attributes in the class namespace The `ABCMeta` fallback inferred from typeshed bases does not guarantee that the runtime metaclass creates attributes in the class namespace. It therefore does not make attributes such as `__abstractmethods__` available on instances. For example, typeshed declares `weakref.WeakSet` as a `MutableSet` subclass, but at runtime it inherits directly from `object` and has metaclass `type`. ```py from weakref import WeakSet class Child(WeakSet[object]): ... reveal_type(type(Child)) # revealed: def f(child: Child): child.__abstractmethods__ # error: [missing-attribute] ``` The fallback also does not constrain the types of attributes defined in the class namespace. For example, a `WeakSet` subclass can define its own `__abstractmethods__` without matching `ABCMeta`'s declaration. ```py class OwnAttribute(WeakSet[object]): __abstractmethods__ = 1 ``` ## Built-in collection metaclasses Typeshed includes collection ABCs in some built-in classes' bases to describe their interfaces. Those stub-only bases do not change the built-ins' runtime metaclasses or introduce conflicts when they are subclassed. ```py from collections import deque from types import GeneratorType reveal_type(type(str)) # revealed: reveal_type(type(tuple)) # revealed: reveal_type(type(list)) # revealed: reveal_type(type(dict)) # revealed: reveal_type(type(deque)) # revealed: reveal_type(type(GeneratorType)) # revealed: class Meta(type): ... class CustomList(list[int], metaclass=Meta): ... class OrdinaryList(list[int]): ... reveal_type(type(CustomList)) # revealed: reveal_type(type(OrdinaryList)) # revealed: ``` ## Metaclass metaclass A class has an explicit base with a custom metaclass. That metaclass itself has a custom metaclass. ```py class M1(type): ... class M2(type, metaclass=M1): ... class M3(M2): ... class A(metaclass=M3): ... class B(A): ... reveal_type(A.__class__) # revealed: ``` ## Diamond inheritance ```py class M(type): ... class M1(M): ... class M2(M): ... class M12(M1, M2): ... class A(metaclass=M1): ... class B(metaclass=M2): ... class C(metaclass=M12): ... # error: [conflicting-metaclass] "The metaclass of a derived class (`D`) must be a subclass of the metaclasses of all its bases, but `M1` (metaclass of base class `A`) and `M2` (metaclass of base class `B`) have no subclass relationship" class D(A, B, C): ... reveal_type(D.__class__) # revealed: type[Unknown] ``` ## Metaclasses with gradual bases A metaclass with an `Any` base can inherit from `type`. We accept it as an explicit metaclass and when reconciling the metaclasses of base classes, regardless of their order. Regression test for [ty#4510](https://github.com/astral-sh/ty/issues/4510). ```py from typing import Any def _(base: Any): class Meta(base): ... class Base(object, metaclass=Meta): ... class Child(Base, object): ... class Plain: ... class Reversed(Plain, Base): ... reveal_type(Base.__class__) # revealed: reveal_type(Child.__class__) # revealed: reveal_type(Reversed.__class__) # revealed: # A known subclass takes precedence over its base, even when the base's Any # superclass could make the two metaclasses assignable in both directions. class DerivedMeta(Meta): ... class Other(metaclass=DerivedMeta): ... class Combined(Base, Other): ... reveal_type(Combined.__class__) # revealed: ``` ## Metaclasses with unknown bases An unresolved superclass can also provide the required inheritance relationship. This remains true when the unknown base is inherited indirectly. ```py from missing import UnknownBase # error: [import-not-found] class RootMeta(UnknownBase): ... class Meta(RootMeta): ... class Base(object, metaclass=Meta): ... class Child(Base, object): ... class Plain: ... class Reversed(Plain, Base): ... reveal_type(Base.__class__) # revealed: reveal_type(Child.__class__) # revealed: reveal_type(Reversed.__class__) # revealed: ``` ## Sibling metaclasses with an unknown ancestor An unknown ancestor of a shared base cannot make its subclasses inherit from one another without an inheritance cycle. We report the conflict and infer an unknown metaclass. ```py from typing import Any def _(base: Any): class RootMeta(base): ... class LeftMeta(RootMeta): ... class RightMeta(RootMeta): ... class Left(metaclass=LeftMeta): ... class Right(metaclass=RightMeta): ... class Combined(Left, Right): ... # error: [conflicting-metaclass] class Reversed(Right, Left): ... # error: [conflicting-metaclass] class Explicit(Left, metaclass=RightMeta): ... # error: [conflicting-metaclass] reveal_type(Combined.__class__) # revealed: type[Unknown] reveal_type(type(Reversed)) # revealed: type[Unknown] ``` ## Metaclasses with a separate unknown base An unknown base outside the shared ancestry can establish a subclass relationship. Only `LeftMeta` can inherit from `RightMeta` here, so it is selected regardless of the order of the bases. ```py from typing import Any def _(extra: Any): class RootMeta(type): ... class RightMeta(RootMeta): ... class LeftMeta(extra, RootMeta): ... class Left(metaclass=LeftMeta): ... class Right(metaclass=RightMeta): ... class Forward(Left, Right): ... class Reverse(Right, Left): ... reveal_type(Forward.__class__) # revealed: reveal_type(type(Reverse)) # revealed: # The separate unknown base can also supply this relationship for a known # subclass of LeftMeta. class DerivedMeta(LeftMeta): ... class Derived(metaclass=DerivedMeta): ... class Inherited(Derived, Right): ... reveal_type(Inherited.__class__) # revealed: ``` ## Ambiguous metaclasses When the relationship between two metaclasses is hidden by `Any`, either could be the more derived one. Neither base order determines a unique metaclass, and subclasses preserve this uncertainty. ```py from typing import Any def _(base1: Any, base2: Any, other_base: Any): class Meta1(base1): ... class Meta2(base2): ... class A(metaclass=Meta1): ... class B(metaclass=Meta2): ... class Forward(A, B): ... class Reverse(B, A): ... class Explicit(A, metaclass=Meta2): ... class Child(Forward): ... class Plain: ... class Inherited(Plain, Reverse): ... reveal_type(Forward.__class__) # revealed: type[Unknown] reveal_type(type(Forward)) # revealed: type[Unknown] reveal_type(Reverse.__class__) # revealed: type[Unknown] reveal_type(Explicit.__class__) # revealed: type[Unknown] reveal_type(Child.__class__) # revealed: type[Unknown] reveal_type(Inherited.__class__) # revealed: type[Unknown] # The hidden bases can also conceal a runtime conflict. If base1 and # other_base are both type, the metaclasses are unrelated, but the Any # annotations prevent us from proving that conflict. class OtherMeta(other_base): ... class Other(metaclass=OtherMeta): ... class PossiblyInvalid(A, Other): ... reveal_type(PossiblyInvalid.__class__) # revealed: type[Unknown] # Once the metaclass is unknown, we do not retain the possible candidates. # A later base therefore does not resolve the ambiguity, even when its # metaclass inherits from both original candidates. class CommonMeta(Meta2, Meta1): ... class Common(metaclass=CommonMeta): ... class WithCommonBase(A, B, Common): ... class InheritedWithCommonBase(Forward, Common): ... reveal_type(WithCommonBase.__class__) # revealed: type[Unknown] reveal_type(InheritedWithCommonBase.__class__) # revealed: type[Unknown] ``` ## Unknown ```py from nonexistent_module import UnknownClass # error: [import-not-found] class C(UnknownClass): ... # TODO: should be `type[type] & Unknown` reveal_type(C.__class__) # revealed: class M(type): ... class A(metaclass=M): ... class B(A, UnknownClass): ... # TODO: should be `type[M] & Unknown` reveal_type(B.__class__) # revealed: ``` ## Duplicate ```py class M(type): ... class A(metaclass=M): ... class B(A, A): ... # error: [duplicate-base] "Duplicate base class `A`" reveal_type(B.__class__) # revealed: ``` ## Non-class When a class has an explicit `metaclass` that is not a class, but is a callable that accepts `type.__new__` arguments, we should return the meta-type of its return type. ```py def f(*args, **kwargs) -> int: return 1 class A(metaclass=f): ... # TODO: Should be `int` reveal_type(A) # revealed: reveal_type(A.__class__) # revealed: type[int] def _(n: int): # error: [invalid-metaclass] class B(metaclass=n): ... # TODO: Should be `Unknown` reveal_type(B) # revealed: reveal_type(B.__class__) # revealed: type[Unknown] def _(flag: bool): m = f if flag else 42 # error: [invalid-metaclass] class C(metaclass=m): ... # TODO: Should be `int | Unknown` reveal_type(C) # revealed: reveal_type(C.__class__) # revealed: type[Unknown] class SignatureMismatch: ... # TODO: Emit a diagnostic class D(metaclass=SignatureMismatch): ... # TODO: Should be `Unknown` reveal_type(D) # revealed: # TODO: Should be `type[Unknown]` reveal_type(D.__class__) # revealed: ``` ## Metaclass bounds With a metaclass annotated as `type[Meta]`, the resulting class and its subclasses are instances of `Meta`, and therefore of `type`. Matching a `type[C]` value against `type()` is exhaustive, but returning it as `int` is invalid. ```py from typing_extensions import assert_never class Meta(type): ... def _(meta: type[Meta]): class C(metaclass=meta): ... def check(cls: type[C]) -> None: reveal_type(cls.__class__) # revealed: type[Meta] match cls: case type(): pass case _: assert_never(cls) def as_int(cls: type[C]) -> int: return cls # error: [invalid-explicit-return] ``` ## Diagnostic range ```py def _(n: int): # snapshot: invalid-metaclass class B(metaclass=n): x = 1 y = 2 ``` ```snapshot error[invalid-metaclass]: Metaclass type `int` is not callable --> src/mdtest_snippet.py:3:13 | 3 | class B(metaclass=n): | ^^^^^^^^^^^ ``` ## Cyclic Retrieving the metaclass of a cyclically defined class should not cause an infinite loop. ```pyi class A(B): ... # error: [cyclic-class-definition] class B(C): ... # error: [cyclic-class-definition] class C(A): ... # error: [cyclic-class-definition] reveal_type(A.__class__) # revealed: type[Unknown] ``` ## Metaclass conflicts during recursive attribute inference A stub can refer to an inherited type alias through a nested class with a custom metaclass. When an attribute named `type` also depends on that alias, inferring the metaclass's bases can depend on the metaclass being selected. Gradual metaclass selection accepts the unresolved ancestry during inference, allowing type checking to converge. Regression test for [ty#4492](https://github.com/astral-sh/ty/issues/4492). ```toml [environment] python-version = "3.12" ``` ```py from mod import Outer # TODO: This should be `int`. reveal_type(Outer.value) # revealed: Unknown ``` `mod.pyi`: ```pyi class Wrapper[T](type): ... class Outer: class Aliases: Value = int class Meta(Wrapper[int], type): ... class Inner(Aliases, metaclass=Meta): ... value: Outer.Inner.Value type: Outer.Inner.Value ``` ## Persistent metaclass conflict during recursive attribute inference Recursive attribute inference does not suppress a provable metaclass conflict. `OtherMeta` is final, so an unknown base inferred for `Meta` cannot make it a subclass of `OtherMeta`. We retain the explicit metaclass and still report the conflict when checking the stub. ```toml [environment] python-version = "3.12" ``` ```py from mod import Outer reveal_type(Outer.value) # revealed: Unknown reveal_type(Outer.Inner.__class__) # revealed: ``` `mod.pyi`: ```pyi from typing import final class Wrapper[T](type): ... @final class OtherMeta(type): ... class Outer: class Aliases(metaclass=OtherMeta): Value = int class Meta(Wrapper[int], type): ... class Inner(Aliases, metaclass=Meta): ... # error: [conflicting-metaclass] value: Outer.Inner.Value type: Outer.Inner.Value ``` ## Metaclass reflection during recursive attribute inference This stress test checks that cyclic attribute inference converges. Inferring `Outer.type` requires resolving `Inner.Value.__class__`, while inferring `Inner`'s metaclass uses `Outer.type` as a base. Both `__class__` and `type()` resolve to `Meta`. ```toml [environment] python-version = "3.12" ``` ```py from mod import Outer reveal_type(Outer.Inner.__class__) # revealed: reveal_type(type(Outer.Inner)) # revealed: ``` `mod.pyi`: ```pyi class Wrapper[T](type): ... class Outer: class Aliases: Value = int class Meta(Wrapper[int], type): ... class Inner(Aliases, metaclass=Meta): ... type = Inner.Value.__class__ ``` ## Metaclass reflection in a metaclass base This stress test creates an inheritance cycle through metaclass reflection. In the stub, `Meta` inherits from `Outer.type`, which refers back to `Meta` through `Inner.__class__`. Inference terminates and reports the cycle. `mod.pyi`: ```pyi class Outer: class Meta(type): ... # error: [cyclic-class-definition] class Inner(object, metaclass=Meta): ... type = Inner.__class__ reveal_type(Outer.Inner.__class__) # revealed: type[Unknown] ``` ## PEP 695 generic ```toml [environment] python-version = "3.12" ``` ```py class M(type): ... class A[T: str](metaclass=M): ... reveal_type(A.__class__) # revealed: ``` ## Generic metaclass ### Fully specialized A generic metaclass fully specialized with concrete types is fine: ```toml [environment] python-version = "3.13" ``` ```py class Foo[T](type): x: T class Bar(metaclass=Foo[int]): ... reveal_type(Bar.__class__) # revealed: ``` ### Parameterized by type variables (legacy) A generic metaclass parameterized by type variables is not supported: ```py from typing import TypeVar, Generic T = TypeVar("T") class GenericMeta(type, Generic[T]): ... # error: [invalid-metaclass] "Generic metaclasses are not supported" class GenericMetaInstance(metaclass=GenericMeta[T]): ... ``` ### Parameterized by type variables (PEP 695) The same applies using PEP 695 syntax: ```toml [environment] python-version = "3.13" ``` ```py class Foo[T](type): x: T # error: [invalid-metaclass] class Bar[T](metaclass=Foo[T]): ... ``` ## Metaclasses of metaclasses ```py class Foo(type): ... class Bar(type, metaclass=Foo): ... class Baz(type, metaclass=Bar): ... class Spam(metaclass=Baz): ... reveal_type(Spam.__class__) # revealed: reveal_type(Spam.__class__.__class__) # revealed: reveal_type(Spam.__class__.__class__.__class__) # revealed: def test(x: Spam): reveal_type(x.__class__) # revealed: type[Spam] reveal_type(x.__class__.__class__) # revealed: type[Baz] reveal_type(x.__class__.__class__.__class__) # revealed: type[Bar] reveal_type(x.__class__.__class__.__class__.__class__) # revealed: type[Foo] reveal_type(x.__class__.__class__.__class__.__class__.__class__) # revealed: type[type] # revealed: type[type] reveal_type(x.__class__.__class__.__class__.__class__.__class__.__class__.__class__.__class__) ```