Checking an eager annotation such as `A | B | C` can involve looking up the same name twice. Ty needs both the type that the annotation denotes and the runtime value on which Python calls `|`. In longer annotations, it can also evaluate an inner union again while checking its parent. This change reuses the runtime values of bare names, `None`, and nested unions within the same eager annotation. A nested union computes its runtime value only when the enclosing `|` can use it under the same inference flags. Each expression still records its annotation type. For example, `bool | int` denotes `int` but evaluates to a union object, which matters for a subsequent `| None`. This addresses the eager-annotation case from #29312 on top of #29727. ## Test plan Measured CPU time for fresh, single-core `ty check` processes over 12 interleaved rounds. The comparison uses main at `18c5d27c41` and the eager operand changes from #29312 rebased onto the same commit. Times are medians in milliseconds for each whole input file. | Input | Main | Rebased #29312 | This change | | --- | ---: | ---: | ---: | | Three ordinary classes, 1,500 signatures | 58.5 | 59.3 | 56.6 | | Twelve ordinary classes, 450 signatures | 86.7 | 72.5 | 69.4 | | Twelve specialized generics, 350 signatures | 144.5 | 100.3 | 100.0 | | Direct `TypeForm` arguments | 113.9 | 98.3 | 91.7 | The source-only checks of NumPy’s `_typing` package and Pydantic showed no clear difference. Against rebased #29312, the stored 256-member `TypeForm` case used 1.0% more CPU time, and the `gradual_literal_union_equality` Criterion benchmark took 0.9% longer. Compared the inferred types of all 14 AST nodes in a pair of left- and right-nested annotations. Both alternatives and main yielded the same type at every node.
6.4 KiB
Union
Annotation
typing.Union can be used to construct union types in the same way as the | operator.
from typing import Union
a: Union[int, str]
a1: Union[int, bool]
a2: Union[int, Union[bytes, str]]
a3: Union[int, None]
a4: Union[Union[bytes, str]]
a5: Union[int]
a6: Union[()]
def f():
# revealed: int | str
reveal_type(a)
# Since bool is a subtype of int we simplify to int here. But we do allow assigning boolean values (see below).
# revealed: int
reveal_type(a1)
# revealed: int | bytes | str
reveal_type(a2)
# revealed: int | None
reveal_type(a3)
# revealed: bytes | str
reveal_type(a4)
# revealed: int
reveal_type(a5)
# revealed: Never
reveal_type(a6)
Assignment
from typing import Union
a: Union[int, str]
a = 1
a = ""
a1: Union[int, bool]
a1 = 1
a1 = True
# error: [invalid-assignment] "Object of type `Literal[b""]` is not assignable to `int | str`"
a = b""
Typing Extensions
from typing_extensions import Union
a: Union[int, str]
def f():
# revealed: int | str
reveal_type(a)
Invalid
from typing import Union
# error: [invalid-type-form] "`typing.Union` requires at least one argument when used in a parameter annotation"
def f(x: Union) -> None:
reveal_type(x) # revealed: Unknown
Implicit type aliases using new-style unions
[environment]
python-version = "3.10"
X = int | str
def f(y: X):
reveal_type(y) # revealed: int | str
Runtime union operands
None can be combined with classes and type forms in either order:
from typing import Annotated, Callable, Literal, NewType, TypeVar
from typing_extensions import TypeAliasType
T = TypeVar("T")
UserId = NewType("UserId", int)
Alias = TypeAliasType("Alias", int)
reveal_type(int | None) # revealed: <types.UnionType special-form 'int | None'>
reveal_type(None | list[int]) # revealed: <types.UnionType special-form 'None | list[int]'>
reveal_type(Literal[1] | None) # revealed: <types.UnionType special-form 'Literal[1] | None'>
reveal_type(None | Annotated[int, "tag"]) # revealed: <types.UnionType special-form 'None | int'>
reveal_type(Callable[[], int] | None) # revealed: <types.UnionType special-form '(() -> int) | None'>
reveal_type(None | T) # revealed: <types.UnionType special-form 'None | TypeVar'>
reveal_type(UserId | None) # revealed: <types.UnionType special-form 'UserId | None'>
reveal_type(None | Alias) # revealed: <types.UnionType special-form 'None | int'>
Ordinary values do not become type union operands merely because their type is known to ty:
from functools import partial
def f(x: int) -> int:
return x
p = partial(f)
p | None # error: [unsupported-operator]
None | p # error: [unsupported-operator]
staticmethod(f) | None # error: [unsupported-operator]
range(5) | None # error: [unsupported-operator]
Runtime operands and the type they denote
bool | int is a union object even though it denotes just int. Adding Literal[True] preserves
the denoted type, but isinstance rejects the literal among the runtime operands.
from typing import Literal
Ints = bool | int
WithLiteral = Literal[True] | Ints
reveal_type(Ints) # revealed: <types.UnionType special-form 'int'>
def check(value: WithLiteral):
reveal_type(value) # revealed: int
isinstance(value, WithLiteral) # error: [invalid-argument-type]
Runtime operators in eager annotations
[environment]
python-version = "3.12"
Nested union objects
bool | int denotes int, but evaluates to a union object that accepts None on either side.
def f(left: bool | int | None | bytes, right: bytes | (None | (bool | int))):
reveal_type(left) # revealed: int | None | bytes
reveal_type(right) # revealed: bytes | None | int
Custom metaclass operators
A metaclass can give | a different result. Here C | "int" evaluates to a string, so applying
| None to that result fails.
class Meta(type):
def __or__(self, other: str) -> str:
return other
class C(metaclass=Meta): ...
# error: 29 [unsupported-operator] "Operator `|` is unsupported between objects of type `str` and `None`"
def invalid(value: bytes | (C | "int" | None)):
reveal_type(value) # revealed: bytes | C | int | None
Dictionary merges
Even in an invalid annotation, merging a dictionary literal with a TypedDict instance produces
that TypedDict. The next | reports its runtime type.
from typing import TypedDict
class Row(TypedDict):
key: int
row: Row = {"key": 1}
# error: [invalid-type-form] "Dict literals"
# error: [invalid-type-form] "Variable of type `Row`"
# error: [unsupported-operator] "Operator `|` is unsupported between objects of type `Row` and `None`"
def invalid(value: {} | row | None | bytes): ...
Recursive assignments to invalid union operands
An invalid operation still produces a diagnostic when its operand is inferred recursively:
from functools import partial
def f(x: int) -> int:
return x
def loop(flag: bool) -> None:
value = partial(f)
while flag:
value = value | None # error: [unsupported-operator]
reveal_type(value) # revealed: partial[(x: int) -> int] | Unknown
def reverse_loop(flag: bool) -> None:
value = staticmethod(f)
while flag:
value = None | value # error: [unsupported-operator]
reveal_type(value) # revealed: staticmethod[def f(x: int) -> int] | Unknown
class X:
def __init__(self):
self.value = partial(f)
def update(self):
self.value = self.value | None # error: [unsupported-operator]
reveal_type(X().value) # revealed: partial[(x: int) -> int] | Unknown
Runtime class
Python 3.13 and earlier
typing.Union is an instance of typing._SpecialForm, so it is not a class.
[environment]
python-version = "3.13"
from typing import Union
reveal_type(type(Union)) # revealed: <class '_SpecialForm'>
def takes_type(cls: type) -> None: ...
takes_type(Union) # error: [invalid-argument-type]
Python 3.14 and later
typing.Union is a class, as is its re-export from typing_extensions.
[environment]
python-version = "3.14"
from typing import Union
from typing_extensions import Union as ExtensionsUnion
reveal_type(type(Union)) # revealed: <class 'type'>
reveal_type(type(ExtensionsUnion)) # revealed: <class 'type'>
def takes_type(cls: type) -> None: ...
takes_type(Union)
takes_type(ExtensionsUnion)