Files
Carl Meyer c08d12bfc9 [ty] Infer implicit aliases from their definition as type expressions (#29200)
https://github.com/astral-sh/ruff/pull/28425 added a new way to infer
implicit and PEP 613 type aliases, which I'd previously described in
https://github.com/astral-sh/ty/issues/1711. Rather than using the value
type of the alias and converting it back to its type-annotation meaning,
this system goes back to the original definition and infers it directly
as a type expression. This gives us more robust validation that implicit
type aliases are valid type expressions, and allows us to emit accurate
diagnostics both for invalid-as-type-expression and for
invalid-at-runtime.

https://github.com/astral-sh/ruff/pull/28425 used this new approach only
for recursive type aliases; this PR expands it to all implicit and PEP
613 type aliases, so that we consistently get its benefits. This also
significantly improves our conformance results for implicit type
aliases; we now pass two more conformance files.

This is an example of the sort of thing that we previously accepted as a
type alias, and now reject (as the conformance suite says we should):

```py
BadAlias = (lambda: int)()

def f(value: BadAlias):  # Main: int, Now: invalid-type-form
    ...
```

This also makes us more consistent (with ourselves, other type checkers
,and the conformance suite) when a generic type is used "bare" in an
alias. The core rule we use is that the RHS of an implicit or PEP 613
type alias is a type expression, therefore a use of a bare generic alias
in that type expression should be implicitly default-specialized.

```py
from typing import TypeVar

T = TypeVar("T", default=str)

GenAlias = list[T]
AnotherAlias = GenAlias | int

# this is now an error: AnotherAlias is not generic
def _(x: AnotherAlias[bytes]): ...

# The bare reference to GenAlias inside AnotherAlias is default-specialized:
def _(x: AnotherAlias):
    reveal_type(x)  # list[str] | int
```

We do make one carve-out from this rule: we consider a plain assignment
like `A = B` or `A = module.B` to be a direct "rename" or "forward" that
doesn't really treat the RHS as a type expression, and thus doesn't
default-specialize anything; instead `A` just becomes a new name for
`B`. This feels more intuitive, and matches pyrefly and pyright. This
carve-out does not apply to PEP 613 type aliases: `A: TypeAlias = B` is
explicitly a type alias, not a rename, so it does default-specialize
`B`.

Reject computed values used as types, including values that evaluate to
classes or `Any`, and preserve that validation when `invalid-type-form`
is disabled. Definition lookup stays behind a tracked query so unrelated
edits in an imported module do not invalidate consumers.

Fixes https://github.com/astral-sh/ty/issues/1711.
Fixes https://github.com/astral-sh/ty/issues/1846.
Prepares https://github.com/astral-sh/ty/issues/4683. Runtime `|`
behavior is not changed here.

Source-location diagnostic explanations for invalid aliases are added in
the follow-up #29654.

## Ecosystem

[Full ecosystem
analysis](https://github.com/astral-sh/ruff/pull/29200#issuecomment-6353595871)
for `b175c73` covers all 150 diagnostic changes across 21 projects: 61
additions, 58 removals, and 31 message changes. New diagnostics
primarily validate computed values used as types and default-specialized
explicit aliases. Improved alias inference removes cascading errors and
preserves forward references and generic parameters.

The nine new discord.py false positives match the known
[ty#4016](https://github.com/astral-sh/ty/issues/4016) callback-context
limitation and are accepted for this PR. No other new false positives
were identified.

Conformance gains six expected diagnostics (five in
`aliases_implicit.py`, one in `aliases_explicit.py`) and two fully
passing files, with no new conformance false positives.
2026-10-23 16:32:27 -07:00

7.7 KiB

Annotated

Annotated attaches arbitrary metadata to a given type.

Usages

Annotated[T, ...] is equivalent to T: All metadata arguments are simply ignored.

from typing_extensions import Annotated

def _(x: Annotated[int, "foo"]):
    reveal_type(x)  # revealed: int

def _(x: Annotated[int, lambda: 0 + 1 * 2 // 3, _(4)]):
    reveal_type(x)  # revealed: int

def _(x: Annotated[int, "arbitrary", "metadata", "elements", "are", "fine"]):
    reveal_type(x)  # revealed: int

def _(x: Annotated[tuple[str, int], bytes]):
    reveal_type(x)  # revealed: tuple[str, int]

String annotations

Metadata in a string annotation can include calls with unpacked dictionaries. The metadata does not affect the annotated type, regardless of where the annotation appears.

from typing_extensions import Annotated

value: "Annotated[int, dict(**{})]"

def convert(value: "Annotated[str, dict(**{'name': 'value'})]") -> "Annotated[int, dict(**{})]":
    reveal_type(value)  # revealed: str
    return 1

Conditional expressions are also valid metadata and do not affect the annotated type.

def flag() -> bool:
    return True

conditional_value: "Annotated[int, 1 if flag() else 2]" = 1

Inside type[...]

Annotated can wrap a class or specialized generic class inside type[...] without changing the resulting class object type.

from typing_extensions import Annotated

def _(
    simple: type[Annotated[int, "metadata"]],
    generic: type[Annotated[list[str], "metadata"]],
):
    reveal_type(simple)  # revealed: type[int]
    reveal_type(generic)  # revealed: type[list[str]]

This also works for unions of classes and nested Annotated forms.

def _(
    union: type[Annotated[int | str, "metadata"]],
    nested: type[Annotated[Annotated[int, "inner"], "outer"]],
):
    reveal_type(union)  # revealed: type[int | str]
    reveal_type(nested)  # revealed: type[int]

Wrapping a non-class type in Annotated does not make it a valid argument to type[...].

from typing import Callable

def _(
    # error: [invalid-type-form] "The argument to `type[]` must be a class object type"
    invalid: type[Annotated[Callable[[], int], "metadata"]],
):
    reveal_type(invalid)  # revealed: type[Unknown]

Parameterization

It is invalid to parameterize Annotated with less than two arguments.

from typing_extensions import Annotated

# error: [invalid-type-form] "`typing.Annotated` requires at least two arguments when used in a parameter annotation"
def _(x: Annotated):
    reveal_type(x)  # revealed: Unknown

def _(flag: bool):
    if flag:
        X = Annotated
    else:
        X = bool

    # error: [invalid-type-form] "`typing.Annotated` requires at least two arguments when used in a parameter annotation"
    def f(y: X):
        reveal_type(y)  # revealed: Unknown | bool

# error: [invalid-type-form] "`typing.Annotated` requires at least two arguments when used in a parameter annotation"
def _(x: Annotated | bool):
    reveal_type(x)  # revealed: Unknown | bool

# error: [invalid-type-form] "Special form `typing.Annotated` expected at least 2 arguments (one type and at least one metadata element)"
# error: [invalid-type-form] "Special form `typing.Annotated` expected at least 2 arguments (one type and at least one metadata element)"
def _(x: Annotated[()], y: list[Annotated[()]]):
    reveal_type(x)  # revealed: Unknown
    reveal_type(y)  # revealed: list[Unknown]

# error: [invalid-type-form]
def _(x: Annotated[int]):
    # `Annotated[T]` is invalid and will raise an error at runtime,
    # but we treat it the same as `T` to provide better diagnostics later on.
    # The subscription itself is still reported, regardless.
    # Same for the `(int,)` form below.
    reveal_type(x)  # revealed: int

# error: [invalid-type-form]
def _(x: Annotated[(int,)]):
    reveal_type(x)  # revealed: int

Runtime inference preserves an Annotated object when a type argument is present, even if that type is Unknown. With no type argument, the entire expression recovers as Unknown:

from ty_extensions._internal import Unknown

Missing = Annotated[()]  # error: [invalid-type-form]
Wrapped = Annotated[Unknown]  # error: [invalid-type-form]

reveal_type(Missing)  # revealed: Unknown
reveal_type(Wrapped)  # revealed: <special-form 'typing.Annotated[Unknown, <metadata>]'>

Inheritance

Correctly parameterized

Inheriting from Annotated[T, ...] is equivalent to inheriting from T itself.

from typing_extensions import Annotated, Any
from ty_extensions._internal import reveal_mro

class C(Annotated[int, "foo"]): ...

# revealed: (<class 'C'>, <class 'int'>, <class 'object'>)
reveal_mro(C)

class D(Annotated[list[str], "foo"]): ...

# revealed: (<class 'D'>, <class 'list[str]'>, <class 'MutableSequence[str]'>, <class 'Sequence[str]'>, <class 'Reversible[str]'>, <class 'Collection[str]'>, <class 'Iterable[str]'>, <class 'Container[Any]'>, typing.Protocol, typing.Generic, <class 'object'>)
reveal_mro(D)

class E(Annotated[list["E"], "metadata"]): ...

# error: [revealed-type] "Revealed MRO: (<class 'E'>, <class 'list[E]'>, <class 'MutableSequence[E]'>, <class 'Sequence[E]'>, <class 'Reversible[E]'>, <class 'Collection[E]'>, <class 'Iterable[E]'>, <class 'Container[Any]'>, typing.Protocol, typing.Generic, <class 'object'>)"
reveal_mro(E)

class F(Annotated[Any, "metadata"]): ...

# revealed: (<class 'F'>, Any, <class 'object'>)
reveal_mro(F)

Not parameterized

from typing_extensions import Annotated
from ty_extensions._internal import reveal_mro

# At runtime, this is an error.
# error: [invalid-base]
class C(Annotated): ...

reveal_mro(C)  # revealed: (<class 'C'>, Unknown, <class 'object'>)

Recursive runtime values

TypeOf can make an Annotated value refer to the type of another runtime Annotated object. Inference preserves the outer object and collapses the recursive wrapped type. The resulting approximation can overlap with a concrete Annotated object, so identity comparisons remain ambiguous.

from typing import Annotated
from ty_extensions._internal import TypeOf

value = int
while True:
    value = Annotated[TypeOf[value], "metadata"]
    reveal_type(value)  # revealed: <special-form 'typing.Annotated[Divergent, <metadata>]'>
    reveal_type(value is Annotated[TypeOf[int], "metadata"])  # revealed: bool
    reveal_type(Annotated[TypeOf[int], "metadata"] is value)  # revealed: bool
    reveal_type(value is not Annotated[TypeOf[int], "metadata"])  # revealed: bool

Recursive inferred attributes

An inferred attribute can store successive runtime Annotated objects. The recursive approximation accepts the next assignment, both with and without a separate initializer.

from typing import Annotated
from ty_extensions._internal import TypeOf

class Initialized:
    def __init__(self):
        self.value = int

    def update(self):
        self.value = Annotated[TypeOf[self.value], "metadata"]

class Uninitialized:
    def update(self):
        self.value = Annotated[TypeOf[self.value], "metadata"]

Distinct runtime values

An Annotated object wrapping int is distinct from one wrapping object, even though int is a subtype of object.

from typing import Annotated
from ty_extensions._internal import TypeOf

integer = Annotated[int, "metadata"]
object_ = Annotated[object, "metadata"]

reveal_type(integer is object_)  # revealed: Literal[False]
reveal_type(integer is not object_)  # revealed: Literal[True]

def accepts_integer(value: TypeOf[integer]): ...
def accepts_object(value: TypeOf[object_]): ...

accepts_integer(integer)
accepts_object(object_)
accepts_integer(object_)  # error: [invalid-argument-type]
accepts_object(integer)  # error: [invalid-argument-type]