Files
Charlie Marsh d67aa96e6a [ty] Skip overload prefix checks for literal parameters (#31043)
## Summary

When the service name is `Any`, we check whether some prefix of the
overloads accepts every possible value. A prefix that only accepts
literal service names can never cover `object()`. We already use that
observation to skip prefix checks for some parameter types. We now
recognize literal types here too, including unions where every member
excludes `object()`.

Checking `boto3auth` with `boto3-stubs` was 7.7% faster on a single
worker (112 ms to 104 ms, faster in 17 of 18 paired runs). In
`boto3-stubs` 1.44.3, all 435 overloads of `Session.client` take a
literal service name.
2026-11-29 07:50:16 -05:00

74 KiB
Raw Permalink Blame History

Overloads

When ty evaluates the call of an overloaded function, it attempts to "match" the supplied arguments with one or more overloads. This document describes the algorithm that it uses for overload matching, which is the same as the one mentioned in the spec.

Note that all of the examples that involve positional parameters are tested multiple times: once with the parameters matched with individual positional arguments, and once with the parameters matched with a single positional argument that is splatted into the argument list. Overload resolution is performed after splatted arguments have been expanded, and so both approaches (TODO: should) produce the same results.

Arity check

The first step is to perform arity check. The non-overloaded cases are described in the function document.

overloaded.pyi:

from typing import overload

@overload
def f() -> None: ...
@overload
def f(x: int) -> int: ...
from overloaded import f

# These match a single overload
reveal_type(f())  # revealed: None
reveal_type(f(*()))  # revealed: None

reveal_type(f(1))  # revealed: int
reveal_type(f(*(1,)))  # revealed: int

# error: [no-matching-overload] "No overload of function `f` matches arguments"
reveal_type(f("a", "b"))  # revealed: Unknown
# error: [no-matching-overload] "No overload of function `f` matches arguments"
reveal_type(f(*("a", "b")))  # revealed: Unknown

Type checking

The second step checks argument types against the overloads that passed the arity check. If a literal argument rules out an overload, ty can check the other candidates first. If any of them matches, ty skips type checking the deferred overloads. If none matches, ty checks them too so it can use their errors to choose the closest overload for diagnostics.

Single match

overloaded.pyi:

from typing import overload

@overload
def f(x: int) -> int: ...
@overload
def f(x: str) -> str: ...
@overload
def f(x: bytes) -> bytes: ...

Here, all of the calls below pass the arity check for all overloads, so we proceed to type checking which filters out all but the matching overload:

from overloaded import f

reveal_type(f(1))  # revealed: int
reveal_type(f(*(1,)))  # revealed: int

reveal_type(f("a"))  # revealed: str
reveal_type(f(*("a",)))  # revealed: str

reveal_type(f(b"b"))  # revealed: bytes
reveal_type(f(*(b"b",)))  # revealed: bytes

Single match error

overloaded.pyi:

from typing import overload

@overload
def f() -> None: ...
@overload
def f(x: int) -> int: ...
@overload
def f(x: int, y: int) -> int: ...

If the arity check only matches a single overload, it should be evaluated as a regular (non-overloaded) function call. This means that any diagnostics resulted during type checking that call should be reported directly and not as a no-matching-overload error.

from overloaded import f

reveal_type(f())  # revealed: None
reveal_type(f(*()))  # revealed: None

# error: [invalid-argument-type] "Argument to function `f` is incorrect: Expected `int`, found `Literal["a"]`"
reveal_type(f("a"))  # revealed: Unknown
# error: [invalid-argument-type] "Argument to function `f` is incorrect: Expected `int`, found `Literal["a"]`"
reveal_type(f(*("a",)))  # revealed: Unknown

More examples of this diagnostic can be found in the single_matching_overload.md document.

Overloads distinguished by a string literal

A literal-valued variable can select an overload by keyword.

from functools import partial
from typing import Literal, overload

@overload
def select(key: Literal["number"], value: int) -> int: ...
@overload
def select(key: Literal["text"], value: str) -> str: ...
def select(key: str, value: int | str) -> int | str:
    return value

def use(key: Literal["text"]):
    reveal_type(select(key=key, value="hello"))  # revealed: str

Binding the literal with functools.partial selects the same overload for later calls.

select_text = partial(select, "text")
reveal_type(select_text)  # revealed: partial[(value: str) -> str]
select_text(1)  # error: [invalid-argument-type]

Literal promotion in a matching overload

The literal bound in the matching overload keeps "blue" from widening to str when the call result becomes a list element.

from typing import Literal, TypeVar, overload

T = TypeVar("T", bound=Literal["blue"])

@overload
def color(value: Literal["red"]) -> str: ...
@overload
def color(value: Literal["green"]) -> str: ...
@overload
def color(value: T) -> T: ...
def color(value: str) -> str:
    return value

reveal_type([color("blue")])  # revealed: list[Literal["blue"]]

Type context when no overload matches

Both overloads reject the value, but only the first also rejects the key. The second overload therefore supplies the type of the lambda parameter.

from typing import Callable, Literal, overload

@overload
def visit(value: int, callback: Callable[[int], object], *, key: Literal["number"]) -> None: ...
@overload
def visit(value: str, callback: Callable[[str], object], *, key: Literal["text"]) -> None: ...
def visit(value, callback, *, key): ...

# error: [no-matching-overload]
visit(b"bad", lambda x: reveal_type(x), key="text")  # revealed: str

Multiple matches

overloaded.pyi:

from typing import overload

class A: ...
class B(A): ...

@overload
def f(x: A) -> A: ...
@overload
def f(x: B, y: int = 0) -> B: ...
from overloaded import A, B, f

# These calls pass the arity check, and type checking matches both overloads:
reveal_type(f(A()))  # revealed: A
reveal_type(f(*(A(),)))  # revealed: A

reveal_type(f(B()))  # revealed: A
reveal_type(f(*(B(),)))  # revealed: A

# But, in this case, the arity check filters out the first overload, so we only have one match:
reveal_type(f(B(), 1))  # revealed: B
reveal_type(f(*(B(), 1)))  # revealed: B

Argument type expansion

This step is performed only if the previous steps resulted in no matches.

In this case, the algorithm would perform argument type expansion and loops over from the type checking step, evaluating the argument lists.

Expanding the only argument

overloaded.pyi:

from typing import overload

class A: ...
class B: ...
class C: ...

@overload
def f(x: A) -> A: ...
@overload
def f(x: B) -> B: ...
@overload
def f(x: C) -> C: ...
from overloaded import A, B, C, f

def _(ab: A | B, ac: A | C, bc: B | C):
    reveal_type(f(ab))  # revealed: A | B
    reveal_type(f(*(ab,)))  # revealed: A | B

    reveal_type(f(bc))  # revealed: B | C
    reveal_type(f(*(bc,)))  # revealed: B | C

    reveal_type(f(ac))  # revealed: A | C
    reveal_type(f(*(ac,)))  # revealed: A | C

Expanding immediate list and dictionary arguments

Unpacking an immediate list or dictionary preserves each element's union type for overload expansion.

from typing import overload

@overload
def choose(x: int) -> int: ...
@overload
def choose(x: str) -> str: ...
def choose(x: int | str) -> int | str:
    return x

def _(value: int | str) -> None:
    reveal_type(choose(*[value]))  # revealed: int | str
    reveal_type(choose(**{"x": value}))  # revealed: int | str

Expanding first argument

If the set of argument lists created by expanding the first argument evaluates successfully, the algorithm shouldn't expand the second argument.

overloaded.pyi:

from typing import Literal, overload

class A: ...
class B: ...
class C: ...
class D: ...

@overload
def f(x: A, y: C) -> A: ...
@overload
def f(x: A, y: D) -> B: ...
@overload
def f(x: B, y: C) -> C: ...
@overload
def f(x: B, y: D) -> D: ...
from overloaded import A, B, C, D, f

def _(a_b: A | B):
    reveal_type(f(a_b, C()))  # revealed: A | C
    reveal_type(f(*(a_b, C())))  # revealed: A | C

    reveal_type(f(a_b, D()))  # revealed: B | D
    reveal_type(f(*(a_b, D())))  # revealed: B | D

# But, if it doesn't, it should expand the second argument and try again:
def _(a_b: A | B, c_d: C | D):
    reveal_type(f(a_b, c_d))  # revealed: A | B | C | D
    reveal_type(f(*(a_b, c_d)))  # revealed: A | B | C | D

Expanding second argument

If the first argument cannot be expanded, the algorithm should move on to the second argument, keeping the first argument as is.

overloaded.pyi:

from typing import overload

class A: ...
class B: ...
class C: ...
class D: ...

@overload
def f(x: A, y: B) -> B: ...
@overload
def f(x: A, y: C) -> C: ...
@overload
def f(x: B, y: D) -> D: ...
from overloaded import A, B, C, D, f

def _(a: A, bc: B | C, cd: C | D):
    # This also tests that partial matching works correctly as the argument type expansion results
    # in matching the first and second overloads, but not the third one.
    reveal_type(f(a, bc))  # revealed: B | C
    reveal_type(f(*(a, bc)))  # revealed: B | C

    # error: [no-matching-overload] "No overload of function `f` matches arguments"
    reveal_type(f(a, cd))  # revealed: Unknown
    # error: [no-matching-overload] "No overload of function `f` matches arguments"
    reveal_type(f(*(a, cd)))  # revealed: Unknown

Expanding a keyword argument after unpacking into a variadic parameter

Valid unpacked positional arguments must not prevent expansion of an unrelated union-typed keyword argument. The positional arguments may come from an empty tuple, a fixed-length tuple, a variable-length tuple, or a list.

overloaded.pyi:

from typing import overload

@overload
def f(*values: str, kind: int) -> int: ...
@overload
def f(*values: str, kind: None) -> str: ...

Expanding kind matches one overload when its value is an int and the other when its value is None, independently of how the positional arguments are provided. An incompatible positional argument must still fail to match either overload.

from overloaded import f

def _(one: tuple[str], many: tuple[str, ...], items: list[str], kind: int | None) -> None:
    reveal_type(f("a", kind=kind))  # revealed: int | str
    reveal_type(f(*(), kind=kind))  # revealed: int | str
    reveal_type(f(*one, kind=kind))  # revealed: int | str
    reveal_type(f(*many, kind=kind))  # revealed: int | str
    reveal_type(f(*items, kind=kind))  # revealed: int | str

def _(invalid: tuple[int], kind: int | None) -> None:
    # error: [no-matching-overload]
    reveal_type(f(*invalid, kind=kind))  # revealed: Unknown

Expanding a keyword argument with an unpacked variadic annotation

An unpacked variadic annotation can specify a different expected type for each positional argument. Unpacked arguments must be checked against their corresponding element types while an unrelated union-typed keyword argument is expanded.

[environment]
python-version = "3.13"

overloaded.pyi:

from typing import overload

@overload
def f(*values: *tuple[str, int], kind: int) -> int: ...
@overload
def f(*values: *tuple[str, int], kind: None) -> str: ...
@overload
def suffix[T: str, *Parts](*values: *tuple[*Parts, T], kind: int) -> int: ...
@overload
def suffix[T: str, *Parts](*values: *tuple[*Parts, T], kind: None) -> str: ...

Both directly supplied arguments and an unpacked tuple satisfy the heterogeneous annotation. A generic variadic prefix also permits expansion when the fixed suffix has a compatible type.

from overloaded import f, suffix

def _(values: tuple[str, int], kind: int | None) -> None:
    reveal_type(f("a", 1, kind=kind))  # revealed: int | str
    reveal_type(f(*values, kind=kind))  # revealed: int | str

def _(pair: tuple[int, str], kind: int | None) -> None:
    reveal_type(suffix(*pair, kind=kind))  # revealed: int | str

Expanding a keyword argument after unpacking into positional parameters

Expanding a union-typed keyword argument must also work when a fixed-length tuple supplies ordinary positional parameters with different types instead of a variadic parameter.

overloaded.pyi:

from typing import overload

@overload
def f(value: str, count: int, *, kind: int) -> int: ...
@overload
def f(value: str, count: int, *, kind: None) -> str: ...

Both the direct positional arguments and the unpacked tuple select the same overloads after kind is expanded.

from overloaded import f

def _(values: tuple[str, int], kind: int | None) -> None:
    reveal_type(f("a", 1, kind=kind))  # revealed: int | str
    reveal_type(f(*values, kind=kind))  # revealed: int | str

Generics (legacy)

overloaded.pyi:

from typing import TypeVar, overload

_T = TypeVar("_T")

class A: ...
class B: ...

@overload
def f(x: A) -> A: ...
@overload
def f(x: _T) -> _T: ...
from overloaded import A, f

def _(x: int, y: A | int):
    reveal_type(f(x))  # revealed: int
    reveal_type(f(*(x,)))  # revealed: int

    reveal_type(f(y))  # revealed: A | int
    reveal_type(f(*(y,)))  # revealed: A | int

Generics (PEP 695)

[environment]
python-version = "3.12"

overloaded.pyi:

from typing import overload

class A: ...
class B: ...

@overload
def f(x: B) -> B: ...
@overload
def f[T](x: T) -> T: ...
from overloaded import B, f

def _(x: int, y: B | int):
    reveal_type(f(x))  # revealed: int
    reveal_type(f(*(x,)))  # revealed: int

    reveal_type(f(y))  # revealed: B | int
    reveal_type(f(*(y,)))  # revealed: B | int

Expanding bool

overloaded.pyi:

from typing import Literal, overload

class T: ...
class F: ...

@overload
def f(x: Literal[True]) -> T: ...
@overload
def f(x: Literal[False]) -> F: ...
from overloaded import f

def _(flag: bool):
    reveal_type(f(True))  # revealed: T
    reveal_type(f(*(True,)))  # revealed: T

    reveal_type(f(False))  # revealed: F
    reveal_type(f(*(False,)))  # revealed: F

    reveal_type(f(flag))  # revealed: T | F
    reveal_type(f(*(flag,)))  # revealed: T | F

Expanding tuple

overloaded.pyi:

from typing import Literal, overload

class A: ...
class B: ...
class C: ...
class D: ...

@overload
def f(x: tuple[A, int], y: tuple[int, Literal[True]]) -> A: ...
@overload
def f(x: tuple[A, int], y: tuple[int, Literal[False]]) -> B: ...
@overload
def f(x: tuple[B, int], y: tuple[int, Literal[True]]) -> C: ...
@overload
def f(x: tuple[B, int], y: tuple[int, Literal[False]]) -> D: ...
from overloaded import A, B, f

def _(x: tuple[A | B, int], y: tuple[int, bool]):
    reveal_type(f(x, y))  # revealed: A | B | C | D
    reveal_type(f(*(x, y)))  # revealed: A | B | C | D

Expanding tuple subclasses

Expanding a tuple subclass preserves its class identity while specializing its element types. Overloads accepting either the subclass or its tuple base remain applicable after expansion.

overloaded.pyi:

from typing import Literal, NamedTuple, overload

class Point(NamedTuple):
    x: bool

@overload
def by_class(value: Point, flag: Literal[True]) -> int: ...
@overload
def by_class(value: Point, flag: Literal[False]) -> str: ...
@overload
def by_element(value: tuple[Literal[True]]) -> int: ...
@overload
def by_element(value: tuple[Literal[False]]) -> str: ...
from overloaded import Point, by_class, by_element

def _(value: Point, flag: bool):
    reveal_type(by_class(value, flag))  # revealed: int | str
    reveal_type(by_class(*(value, flag)))  # revealed: int | str
    reveal_type(by_element(value))  # revealed: int | str
    reveal_type(by_element(*(value,)))  # revealed: int | str

Expanding type

There's no special handling for expanding type[A | B] type because ty stores this type in it's distributed form, which is type[A] | type[B].

overloaded.pyi:

from typing import overload

class A: ...
class B: ...

@overload
def f(x: type[A]) -> A: ...
@overload
def f(x: type[B]) -> B: ...
from overloaded import A, B, f

def _(x: type[A | B]):
    reveal_type(x)  # revealed: type[A | B]
    reveal_type(f(x))  # revealed: A | B
    reveal_type(f(*(x,)))  # revealed: A | B

Expanding enums

Basic

overloaded.pyi:

from enum import Enum
from typing import Literal, overload

class SomeEnum(Enum):
    A = 1
    B = 2
    C = 3

class A: ...
class B: ...
class C: ...

@overload
def f(x: Literal[SomeEnum.A]) -> A: ...
@overload
def f(x: Literal[SomeEnum.B]) -> B: ...
@overload
def f(x: Literal[SomeEnum.C]) -> C: ...
from typing import Literal
from overloaded import SomeEnum, A, B, C, f

def _(x: SomeEnum, y: Literal[SomeEnum.A, SomeEnum.C]):
    reveal_type(f(SomeEnum.A))  # revealed: A
    reveal_type(f(*(SomeEnum.A,)))  # revealed: A

    reveal_type(f(SomeEnum.B))  # revealed: B
    reveal_type(f(*(SomeEnum.B,)))  # revealed: B

    reveal_type(f(SomeEnum.C))  # revealed: C
    reveal_type(f(*(SomeEnum.C,)))  # revealed: C

    reveal_type(f(x))  # revealed: A | B | C
    reveal_type(f(*(x,)))  # revealed: A | B | C

    reveal_type(f(y))  # revealed: A | C
    reveal_type(f(*(y,)))  # revealed: A | C

Enum with single member

This pattern appears in typeshed. Here, it is used to represent two optional, mutually exclusive keyword parameters:

overloaded.pyi:

from enum import Enum, auto
from typing import overload, Literal

class Missing(Enum):
    Value = auto()

class OnlyASpecified: ...
class OnlyBSpecified: ...
class BothMissing: ...

@overload
def f(*, a: int, b: Literal[Missing.Value] = ...) -> OnlyASpecified: ...
@overload
def f(*, a: Literal[Missing.Value] = ..., b: int) -> OnlyBSpecified: ...
@overload
def f(*, a: Literal[Missing.Value] = ..., b: Literal[Missing.Value] = ...) -> BothMissing: ...
from typing import Literal
from overloaded import f, Missing

reveal_type(f())  # revealed: BothMissing
reveal_type(f(a=0))  # revealed: OnlyASpecified
reveal_type(f(b=0))  # revealed: OnlyBSpecified

f(a=0, b=0)  # error: [no-matching-overload]

def _(missing: Literal[Missing.Value], missing_or_present: Literal[Missing.Value] | int):
    reveal_type(f(a=missing, b=missing))  # revealed: BothMissing
    reveal_type(f(a=missing))  # revealed: BothMissing
    reveal_type(f(b=missing))  # revealed: BothMissing
    reveal_type(f(a=0, b=missing))  # revealed: OnlyASpecified
    reveal_type(f(a=missing, b=0))  # revealed: OnlyBSpecified

    reveal_type(f(a=missing_or_present))  # revealed: BothMissing | OnlyASpecified
    reveal_type(f(b=missing_or_present))  # revealed: BothMissing | OnlyBSpecified

    # Here, both could be present, so this should be an error
    f(a=missing_or_present, b=missing_or_present)  # error: [no-matching-overload]

Enum subclass without members

An Enum subclass without members should not be expanded:

overloaded.pyi:

from enum import Enum
from typing import overload, Literal

class MyEnumSubclass(Enum):
    pass

class ActualEnum(MyEnumSubclass):
    A = 1
    B = 2

class OnlyA: ...
class OnlyB: ...
class Both: ...

@overload
def f(x: Literal[ActualEnum.A]) -> OnlyA: ...
@overload
def f(x: Literal[ActualEnum.B]) -> OnlyB: ...
@overload
def f(x: ActualEnum) -> Both: ...
@overload
def f(x: MyEnumSubclass) -> MyEnumSubclass: ...
from overloaded import MyEnumSubclass, ActualEnum, f

def _(actual_enum: ActualEnum, my_enum_instance: MyEnumSubclass):
    reveal_type(f(actual_enum))  # revealed: Both
    reveal_type(f(*(actual_enum,)))  # revealed: Both

    reveal_type(f(ActualEnum.A))  # revealed: OnlyA
    reveal_type(f(*(ActualEnum.A,)))  # revealed: OnlyA

    reveal_type(f(ActualEnum.B))  # revealed: OnlyB
    reveal_type(f(*(ActualEnum.B,)))  # revealed: OnlyB

    reveal_type(f(my_enum_instance))  # revealed: MyEnumSubclass
    reveal_type(f(*(my_enum_instance,)))  # revealed: MyEnumSubclass

Enum complement inside union

A narrowed enum complement inside a union should be expanded to the remaining enum literals:

overloaded.pyi:

from enum import Enum
from typing import Literal, overload

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

class Red: ...
class Green: ...
class Blue: ...
class NoColor: ...

@overload
def f(x: Literal[Color.RED]) -> Red: ...
@overload
def f(x: Literal[Color.GREEN]) -> Green: ...
@overload
def f(x: Literal[Color.BLUE]) -> Blue: ...
@overload
def f(x: None) -> NoColor: ...
from overloaded import Blue, Color, Green, NoColor, f

def _(x: Color | None):
    if x is Color.RED:
        return

    result: Green | Blue | NoColor = f(x)
    result_from_star: Green | Blue | NoColor = f(*(x,))

Enum complement as a bound overload receiver

A narrowed enum complement should also preserve literal alternatives during member lookup, so bound-method overload resolution can still discriminate on the receiver:

overloaded.pyi:

from enum import Enum
from typing import Literal, overload

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

    @overload
    def label(self: Literal[Color.GREEN]) -> int: ...
    @overload
    def label(self: Literal[Color.BLUE]) -> str: ...
from typing import Literal

from overloaded import Color

def narrowed(color: Color):
    if color is Color.RED:
        return
    reveal_type(color.label())  # revealed: int | str

def explicit(color: Literal[Color.GREEN, Color.BLUE]):
    reveal_type(color.label())  # revealed: int | str

Expanding PEP 695 type alias

[environment]
python-version = "3.12"

PEP 695 type aliases should be properly expanded during argument type expansion. This test ensures that type X = A | B is treated the same as a plain union A | B during overload resolution.

overloaded.pyi:

from typing import overload, Literal

class A: ...
class B: ...

@overload
def f(x: A) -> A: ...
@overload
def f(x: B) -> B: ...
from overloaded import A, B, f

type Alias = A | B

def _(x: Alias) -> None:
    # The type alias `Alias` should be expanded to `A | B` during overload resolution
    reveal_type(f(x))  # revealed: A | B
    reveal_type(f(*(x,)))  # revealed: A | B

Expanding recursive aliases

A recursive alias whose outermost type is a union can match several overloads. Its recursive members retain their types while each union alternative is checked.

from typing import TypeVar, overload

T = TypeVar("T")
Tree = T | tuple["Tree[T]"]

@overload
def choose(value: int) -> str: ...
@overload
def choose(value: tuple[object]) -> bytes: ...
def choose(value):
    raise NotImplementedError

def inspect(value: Tree[int]):
    reveal_type(choose(value))  # revealed: str | bytes

Expanding recursive tuple elements

The boolean element of a recursive tuple expands to its two literal alternatives. Expanding the recursive element stops at the reference to the same tuple type.

from typing import Literal, overload

Recursive = tuple["Recursive", bool]

@overload
def choose(value: tuple[object, Literal[True]]) -> str: ...
@overload
def choose(value: tuple[object, Literal[False]]) -> bytes: ...
def choose(value):
    raise NotImplementedError

def inspect(value: Recursive):
    reveal_type(choose(value))  # revealed: str | bytes

No matching overloads

If argument expansion has been applied to all arguments and one or more of the expanded argument lists cannot be evaluated successfully, generate an error and stop.

overloaded.pyi:

from typing import overload

class A: ...
class B: ...
class C: ...
class D: ...

@overload
def f(x: A) -> A: ...
@overload
def f(x: B) -> B: ...
from overloaded import A, B, C, D, f

def _(ab: A | B, ac: A | C, cd: C | D):
    reveal_type(f(ab))  # revealed: A | B
    reveal_type(f(*(ab,)))  # revealed: A | B

    # The `[A | C]` argument list is expanded to `[A], [C]` where the first list matches the first
    # overload while the second list doesn't match any of the overloads, so we generate an
    # error: [no-matching-overload] "No overload of function `f` matches arguments"
    reveal_type(f(ac))  # revealed: Unknown
    # error: [no-matching-overload] "No overload of function `f` matches arguments"
    reveal_type(f(*(ac,)))  # revealed: Unknown

    # None of the expanded argument lists (`[C], [D]`) match any of the overloads, so we generate an
    # error: [no-matching-overload] "No overload of function `f` matches arguments"
    reveal_type(f(cd))  # revealed: Unknown
    # error: [no-matching-overload] "No overload of function `f` matches arguments"
    reveal_type(f(*(cd,)))  # revealed: Unknown

Optimization: Avoid argument type expansion

Argument type expansion could lead to exponential growth of the number of argument lists that needs to be evaluated, so ty deploys some heuristics to prevent this from happening.

Heuristic: If an argument type that cannot be expanded and cannot be assigned to any of the remaining overloads before argument type expansion, then even with argument type expansion, it won't lead to a successful evaluation of the call.

overloaded.pyi:

from typing import overload

class A: ...
class B: ...
class C: ...

@overload
def f() -> None: ...
@overload
def f(**kwargs: int) -> C: ...
@overload
def f(x: A, /, **kwargs: int) -> A: ...
@overload
def f(x: B, /, **kwargs: int) -> B: ...

class Foo:
    @overload
    def f(self) -> None: ...
    @overload
    def f(self, **kwargs: int) -> C: ...
    @overload
    def f(self, x: A, /, **kwargs: int) -> A: ...
    @overload
    def f(self, x: B, /, **kwargs: int) -> B: ...
from overloaded import A, B, C, Foo, f
from typing_extensions import Any, reveal_type

def _(ab: A | B, a: int | Any, invalid: tuple[C]):
    reveal_type(f(a1=a, a2=a, a3=a))  # revealed: C
    reveal_type(f(A(), a1=a, a2=a, a3=a))  # revealed: A
    reveal_type(f(B(), a1=a, a2=a, a3=a))  # revealed: B

    # Here, the arity check filters out the first and second overload, type checking fails on the
    # remaining overloads, so ty moves on to argument type expansion. But, the first argument (`C`)
    # isn't assignable to any of the remaining overloads (3 and 4), so there's no point in expanding
    # the other 30 arguments of type `Unknown | Literal[1]` which would result in allocating a
    # vector containing 2**30 argument lists after expanding all of the arguments.
    reveal_type(
        # error: [no-matching-overload]
        # revealed: Unknown
        f(
            C(),
            a1=a,
            a2=a,
            a3=a,
            a4=a,
            a5=a,
            a6=a,
            a7=a,
            a8=a,
            a9=a,
            a10=a,
            a11=a,
            a12=a,
            a13=a,
            a14=a,
            a15=a,
            a16=a,
            a17=a,
            a18=a,
            a19=a,
            a20=a,
            a21=a,
            a22=a,
            a23=a,
            a24=a,
            a25=a,
            a26=a,
            a27=a,
            a28=a,
            a29=a,
            a30=a,
        )
    )

    # An incompatible element in a definitely nonempty splat must also prevent expansion of the
    # nine union-typed keyword arguments.
    reveal_type(
        # error: [no-matching-overload]
        # revealed: Unknown
        f(
            *invalid,
            a1=a,
            a2=a,
            a3=a,
            a4=a,
            a5=a,
            a6=a,
            a7=a,
            a8=a,
            a9=a,
        )
    )

    # Here, the heuristics won't come into play because all arguments can be expanded but expanding
    # the first argument results in a successful evaluation of the call, so there's no exponential
    # growth of the number of argument lists.
    reveal_type(
        # revealed: A | B
        f(
            ab,
            a1=a,
            a2=a,
            a3=a,
            a4=a,
            a5=a,
            a6=a,
            a7=a,
            a8=a,
            a9=a,
            a10=a,
            a11=a,
            a12=a,
            a13=a,
            a14=a,
            a15=a,
            a16=a,
            a17=a,
            a18=a,
            a19=a,
            a20=a,
            a21=a,
            a22=a,
            a23=a,
            a24=a,
            a25=a,
            a26=a,
            a27=a,
            a28=a,
            a29=a,
            a30=a,
        )
    )

def _(foo: Foo, ab: A | B, a: int | Any):
    reveal_type(foo.f(a1=a, a2=a, a3=a))  # revealed: C
    reveal_type(foo.f(A(), a1=a, a2=a, a3=a))  # revealed: A
    reveal_type(foo.f(B(), a1=a, a2=a, a3=a))  # revealed: B

    reveal_type(
        # error: [no-matching-overload]
        # revealed: Unknown
        foo.f(
            C(),
            a1=a,
            a2=a,
            a3=a,
            a4=a,
            a5=a,
            a6=a,
            a7=a,
            a8=a,
            a9=a,
            a10=a,
            a11=a,
            a12=a,
            a13=a,
            a14=a,
            a15=a,
            a16=a,
            a17=a,
            a18=a,
            a19=a,
            a20=a,
            a21=a,
            a22=a,
            a23=a,
            a24=a,
            a25=a,
            a26=a,
            a27=a,
            a28=a,
            a29=a,
            a30=a,
        )
    )

    reveal_type(
        # revealed: A | B
        foo.f(
            ab,
            a1=a,
            a2=a,
            a3=a,
            a4=a,
            a5=a,
            a6=a,
            a7=a,
            a8=a,
            a9=a,
            a10=a,
            a11=a,
            a12=a,
            a13=a,
            a14=a,
            a15=a,
            a16=a,
            a17=a,
            a18=a,
            a19=a,
            a20=a,
            a21=a,
            a22=a,
            a23=a,
            a24=a,
            a25=a,
            a26=a,
            a27=a,
            a28=a,
            a29=a,
            a30=a,
        )
    )

Optimization: Limit expansion size

To prevent combinatorial explosion, ty limits the number of argument lists created by expanding a single argument.

overloaded.pyi:

from typing import overload

class A: ...
class B: ...
class C: ...

@overload
def f() -> None: ...
@overload
def f(**kwargs: int) -> C: ...
@overload
def f(x: A, /, **kwargs: int) -> A: ...
@overload
def f(x: B, /, **kwargs: int) -> B: ...
from overloaded import A, B, f
from typing_extensions import reveal_type

def _(a: int | None):
    reveal_type(
        # snapshot: no-matching-overload
        # revealed: Unknown
        f(
            A(),
            a1=a,
            a2=a,
            a3=a,
            a4=a,
            a5=a,
            a6=a,
            a7=a,
            a8=a,
            a9=a,
            a10=a,
            a11=a,
            a12=a,
            a13=a,
            a14=a,
            a15=a,
            a16=a,
            a17=a,
            a18=a,
            a19=a,
            a20=a,
            a21=a,
            a22=a,
            a23=a,
            a24=a,
            a25=a,
            a26=a,
            a27=a,
            a28=a,
            a29=a,
            a30=a,
        )
    )
error[no-matching-overload]: No overload of function `f` matches arguments
  --> src/mdtest_snippet.py:8:9
   |
 8 | /         f(
 9 | |             A(),
10 | |             a1=a,
11 | |             a2=a,
12 | |             a3=a,
13 | |             a4=a,
14 | |             a5=a,
15 | |             a6=a,
16 | |             a7=a,
17 | |             a8=a,
18 | |             a9=a,
19 | |             a10=a,
20 | |             a11=a,
21 | |             a12=a,
22 | |             a13=a,
23 | |             a14=a,
24 | |             a15=a,
25 | |             a16=a,
26 | |             a17=a,
27 | |             a18=a,
28 | |             a19=a,
29 | |             a20=a,
30 | |             a21=a,
31 | |             a22=a,
32 | |             a23=a,
33 | |             a24=a,
34 | |             a25=a,
35 | |             a26=a,
36 | |             a27=a,
37 | |             a28=a,
38 | |             a29=a,
39 | |             a30=a,
40 | |         )
   | |_________^
info: Limit of argument type expansion reached at argument 9
info: First overload defined here
 --> src/overloaded.pyi:7:1
  |
7 | / @overload
8 | | def f() -> None: ...
  | |____________________^ First overload defined here
info: Possible overloads for function `f`:
info:   () -> None
info:   (**kwargs: int) -> C
info:   (x: A, /, **kwargs: int) -> A
info:   (x: B, /, **kwargs: int) -> B

Optimization: Limit tuple element expansion size

To prevent combinatorial explosion, ty limits the Cartesian product size when expanding tuple elements. A tuple like tuple[A | B, A | B, ..., A | B] with many union-typed elements would otherwise produce an exponential number of expanded types.

overloaded.pyi:

from typing import overload

@overload
def f(x: tuple[int, ...]) -> int: ...
@overload
def f(x: tuple[str, ...]) -> str: ...
from overloaded import f

def _(a: int | str) -> None:
    # This tuple has too many expandable elements for the Cartesian product to be computed.
    # ty skips the tuple expansion and falls through to the error case.
    # error: [no-matching-overload]
    f((a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a))

Retry from parameter matching

As per the spec, the argument type expansion should retry evaluating the expanded argument list from the type checking step. However, that creates an issue when variadic arguments are involved because if a variadic argument is a union type, it could be expanded to have different arities. So, ty retries it from the start which includes parameter matching as well.

overloaded.pyi:

from typing import overload

@overload
def f(x: int, y: int) -> None: ...
@overload
def f(x: int, y: str, z: int) -> None: ...
from overloaded import f

# Test all of the above with a number of different splatted argument types

def _(t: tuple[int, str]) -> None:
    # This correctly produces an error because the argument has a precise arity of 2, which
    # matches the first overload, but the second element of the tuple doesn't match the second
    # parameter type, yielding an `invalid-argument-type` error.
    f(*t)  # error: [invalid-argument-type]

def _(t: tuple[int, str, int]) -> None:
    # This correctly produces no error because the argument has a precise arity of 3, which
    # matches the second overload.
    f(*t)

def _(t: tuple[int, str] | tuple[int, str, int]) -> None:
    # This produces an error because the expansion produces two argument lists: `[*tuple[int, str]]`
    # and `[*tuple[int, str, int]]`. The first list produces a type checking error as described in
    # the first example, while the second list matches the second overload. And, because not all of
    # the expanded argument list evaluates successfully, we produce an error.
    f(*t)  # error: [no-matching-overload]

from typing import Literal, overload

@overload
def g(x: int, y: str) -> Literal[1]: ...
@overload
def g(x: int, y: str, z: int) -> Literal[2]: ...
def g(*args, **kwargs) -> int:
    return 1

def _(t: tuple[int, str] | tuple[int, str, int]) -> None:
    # Here both expanded argument lists evaluate successfully, so argument expansion should keep
    # both overloads and combine their return types.
    reveal_type(g(*t))  # revealed: Literal[1, 2]

@overload
def h(x: int, y: str) -> Literal[1]: ...
@overload
def h(x: object, y: object, z: object) -> Literal[2]: ...
def h(*args, **kwargs) -> int:
    return 1

def _(t: tuple[int, str] | tuple[int, str, int]) -> None:
    reveal_type(h(*t))  # revealed: Literal[1, 2]

@overload
def k(x: int, y: str) -> Literal[1]: ...
@overload
def k(x: int | str, y: object, z: object) -> Literal[2]: ...
@overload
def k(x: object, y: object, z: object) -> Literal[2]: ...
def k(*args, **kwargs) -> int:
    return 1

def _(t: tuple[int, str] | tuple[int, str, int]) -> None:
    reveal_type(k(*t))  # revealed: Literal[1, 2]

# TODO: this case should error with overlapping overloads -- but people do write overlapping
# overloads, and `Literal[1, 2]` is still a better return type here than `Literal[2]`.

@overload
def m(x: int, y: str) -> Literal[1]: ...
@overload
def m(x: int, y: str, z: int = 0) -> Literal[2]: ...
def m(*args, **kwargs) -> int:
    return 1

def _(t: tuple[int, str] | tuple[int, str, int]) -> None:
    # The defaulted third parameter lets the second overload survive provisional arity checking,
    # but argument expansion should still revive the 2-arg overload and combine both return types.
    reveal_type(m(*t))  # revealed: Literal[1, 2]

Retry from parameter matching with type context

When retrying, arguments are inferred with the correct type context:

from typing import Callable, overload

@overload
def n(callback: Callable[[int], int], value: int, /) -> int: ...
@overload
def n(callback: Callable[[str], str], first: str, second: str, /) -> str: ...
def n(*args: object) -> object: ...
def _(values: tuple[int] | tuple[str, str]):
    reveal_type(n(lambda value: value, *values))  # revealed: int | str

Filtering based on variadic arguments

This is step 4 of the overload call evaluation algorithm which specifies that:

If the argument list is compatible with two or more overloads, determine whether one or more of the overloads has a variadic parameter (either *args or **kwargs) that maps to a corresponding argument that supplies an indeterminate number of positional or keyword arguments. If so, eliminate overloads that do not have a variadic parameter.

This is only performed if the previous step resulted in more than one matching overload.

Simple *args

overloaded.pyi:

from typing import overload

@overload
def f(x1: int) -> tuple[int]: ...
@overload
def f(x1: int, x2: int) -> tuple[int, int]: ...
@overload
def f(*args: int) -> int: ...
from overloaded import f

def _(x1: int, x2: int, args: list[int]):
    reveal_type(f(x1))  # revealed: tuple[int]
    reveal_type(f(x1, x2))  # revealed: tuple[int, int]
    reveal_type(f(*(x1, x2)))  # revealed: tuple[int, int]

    # Step 4 should filter out all but the last overload.
    reveal_type(f(*args))  # revealed: int

Variable *args

[environment]
python-version = "3.11"

overloaded.pyi:

from typing import overload

@overload
def f(x1: int) -> tuple[int]: ...
@overload
def f(x1: int, x2: int) -> tuple[int, int]: ...
@overload
def f(x1: int, *args: int) -> tuple[int, ...]: ...
from overloaded import f

def _(x1: int, x2: int, args1: list[int], args2: tuple[int, *tuple[int, ...]]):
    reveal_type(f(x1, x2))  # revealed: tuple[int, int]
    reveal_type(f(*(x1, x2)))  # revealed: tuple[int, int]
    reveal_type(f(*[x1, x2]))  # revealed: tuple[int, int]

    # Step 4 should filter out all but the last overload.
    reveal_type(f(x1, *args1))  # revealed: tuple[int, ...]
    reveal_type(f(*args2))  # revealed: tuple[int, ...]

Simple **kwargs

overloaded.pyi:

from typing import overload

@overload
def f(*, x1: int) -> int: ...
@overload
def f(*, x1: int, x2: int) -> tuple[int, int]: ...
@overload
def f(**kwargs: int) -> int: ...
from overloaded import f

def _(x1: int, x2: int, kwargs: dict[str, int]):
    reveal_type(f(x1=x1))  # revealed: int
    reveal_type(f(x1=x1, x2=x2))  # revealed: tuple[int, int]

    # The literal dictionary has exactly the two keys required by the second overload.
    reveal_type(f(**{"x1": x1, "x2": x2}))  # revealed: tuple[int, int]

    # Step 4 should filter out all but the last overload for unknown dictionary contents.
    reveal_type(f(**kwargs))  # revealed: int

TypedDict

The keys in a TypedDict are static so there's no variable part to it, so step 4 shouldn't filter out any overloads.

overloaded.pyi:

from typing import TypedDict, overload

@overload
def f(*, x: int) -> int: ...
@overload
def f(*, x: int, y: int) -> tuple[int, int]: ...
@overload
def f(**kwargs: int) -> tuple[int, ...]: ...
from typing import TypedDict
from overloaded import f

class Foo(TypedDict):
    x: int
    y: int

def _(foo: Foo, kwargs: dict[str, int]):
    reveal_type(f(**foo))  # revealed: tuple[int, int]
    reveal_type(f(**kwargs))  # revealed: tuple[int, ...]

Filtering based on Any / Unknown

This is the step 5 of the overload call evaluation algorithm which specifies that:

For all arguments, determine whether all possible materializations of the argument’s type are assignable to the corresponding parameter type for each of the remaining overloads. If so, eliminate all of the subsequent remaining overloads.

This is only performed if the previous step resulted in more than one matching overload.

Protocols and an argument of type Any

The first two overloads of read cannot cover object together, so the last one still contributes to the result. The first overload of select accepts object() through Hashable.

from collections.abc import Hashable
from typing import Any, Protocol, overload

class Readable(Protocol):
    def read(self) -> str: ...

@overload
def read(value: Readable | str) -> str: ...
@overload
def read(value: bytes) -> str: ...
@overload
def read(value: object) -> int: ...
def read(value: object) -> str | int:
    raise NotImplementedError

@overload
def select(value: Hashable) -> str: ...
@overload
def select(value: bytes) -> int: ...
def select(value: object) -> str | int:
    raise NotImplementedError

def _(value: Any):
    reveal_type(read(value))  # revealed: Unknown
    reveal_type(select(value))  # revealed: str

Literal parameters and an argument of type Any

No union of service names covers every value of Any. The fallback overload still contributes to the result when the name is dynamic.

overloaded.pyi:

from typing import Literal, overload

@overload
def client(name: Literal["storage"]) -> int: ...
@overload
def client(name: Literal["logs", "metrics"]) -> int: ...
@overload
def client(name: object) -> str: ...
from typing import Any
from overloaded import client

def _(name: Any):
    reveal_type(client(name))  # revealed: Unknown

reveal_type(client("storage"))  # revealed: int
reveal_type(client("other"))  # revealed: str

Single list argument

overloaded.pyi:

from typing import Any, overload

@overload
def f(x: list[int]) -> int: ...
@overload
def f(x: list[Any]) -> int: ...
@overload
def f(x: Any) -> str: ...

For the above definition, anything other than list should match the last overload:

from typing import Any

from overloaded import f

# Anything other than `list` should match the last overload
reveal_type(f(1))  # revealed: str
reveal_type(f(*(1,)))  # revealed: str

def _(list_int: list[int], list_any: list[Any]):
    reveal_type(f(list_int))  # revealed: int
    reveal_type(f(*(list_int,)))  # revealed: int

    reveal_type(f(list_any))  # revealed: int
    reveal_type(f(*(list_any,)))  # revealed: int

Single list argument (complex generics)

Here Callable[P, R] in the first overload is an equivalent type to Callable[P, R] in the second overload, despite the fact that P and R are scoped to different overload-literals. Evaluation of the result of the call is therefore unambiguous: it must evaluate to a Callable type rather Unknown/Any:

[environment]
python-version = "3.12"

overloaded.pyi:

from typing import overload, Callable

class Foo: ...

class Decorator:
    @overload
    def __call__[**P, R](self, task_runner: None) -> Callable[[Callable[P, R]], Callable[P, R]]: ...
    @overload
    def __call__[**P, R](self, task_runner: Foo) -> Callable[[Callable[P, R]], Callable[P, R]]: ...

main.py:

from typing import Any
from overloaded import Decorator

def test(decorator: Decorator, argument: Any):
    # revealed: [**P'return, R'return]((**P'return) -> R'return, /) -> ((**P'return) -> R'return)
    reveal_type(decorator(argument))

Single list argument (ambiguous)

The overload definition is the same as above, but the return type of the second overload is changed to str to make the overload matching ambiguous if the argument is a list[Any].

overloaded.pyi:

from typing import Any, overload

@overload
def f(x: list[int]) -> int: ...
@overload
def f(x: list[Any]) -> str: ...
@overload
def f(x: Any) -> str: ...
from typing import Any

from overloaded import f

# Anything other than `list` should match the last overload
reveal_type(f(1))  # revealed: str
reveal_type(f(*(1,)))  # revealed: str

def _(list_int: list[int], list_any: list[Any]):
    # All materializations of `list[int]` are assignable to `list[int]`, so it matches the first
    # overload.
    reveal_type(f(list_int))  # revealed: int
    reveal_type(f(*(list_int,)))  # revealed: int

    # All materializations of `list[Any]` are assignable to `list[int]` and `list[Any]`, but the
    # return type of first and second overloads are not equivalent, so the overload matching
    # is ambiguous.
    reveal_type(f(list_any))  # revealed: Unknown
    reveal_type(f(*(list_any,)))  # revealed: Unknown

Shared structure in ambiguous return types

When multiple overloads remain ambiguous, their return types can still share useful structure. We preserve matching generic classes and recursively replace differing type arguments with Unknown. Overloads eliminated by argument checking do not contribute to the result.

overloaded.pyi:

from typing import overload

@overload
def nested(x: int) -> dict[str, list[int]]: ...
@overload
def nested(x: str) -> dict[str, list[str]]: ...
@overload
def nested(x: bytes) -> dict[int, list[bytes]]: ...
@overload
def different_classes(x: int) -> list[int]: ...
@overload
def different_classes(x: str) -> set[int]: ...
from typing import Any
from overloaded import nested, different_classes

def _(value: Any):
    reveal_type(nested(value))  # revealed: dict[Unknown, list[Unknown]]
    reveal_type(different_classes(value))  # revealed: Unknown

reveal_type(nested(1))  # revealed: dict[str, list[int]]

Ambiguous tuple return types

Tuples with matching shapes retain their length, fixed elements, and variable-length segment. Different tuple shapes fall back to Unknown.

overloaded.pyi:

from typing import overload

@overload
def fixed(x: int) -> tuple[int | str, list[int]]: ...
@overload
def fixed(x: str) -> tuple[str | int, list[str]]: ...
@overload
def variable(x: int) -> tuple[str, *tuple[int, ...], bytes]: ...
@overload
def variable(x: str) -> tuple[str, *tuple[float, ...], bytes]: ...
@overload
def different_lengths(x: int) -> tuple[int]: ...
@overload
def different_lengths(x: str) -> tuple[int, int]: ...
from typing import Any
from overloaded import fixed, variable, different_lengths

def _(value: Any):
    reveal_type(fixed(value))  # revealed: tuple[int | str, list[Unknown]]
    reveal_type(variable(value))  # revealed: tuple[str, *tuple[Unknown, ...], bytes]
    reveal_type(different_lengths(value))  # revealed: Unknown

Equivalent tuple shapes with a differing return type

The first two return types below describe the same nonempty tuples of integers. Nevertheless, when a third return type differs, all original tuple shapes must agree before we merge their elements. Choosing one equivalent return type first would make the result depend on overload order.

overloaded.pyi:

from typing import overload

@overload
def prefix_first(x: int) -> tuple[int, *tuple[int, ...]]: ...
@overload
def prefix_first(x: str) -> tuple[*tuple[int, ...], int]: ...
@overload
def prefix_first(x: bytes) -> tuple[str, *tuple[int, ...]]: ...
@overload
def suffix_first(x: str) -> tuple[*tuple[int, ...], int]: ...
@overload
def suffix_first(x: int) -> tuple[int, *tuple[int, ...]]: ...
@overload
def suffix_first(x: bytes) -> tuple[str, *tuple[int, ...]]: ...
from typing import Any
from overloaded import prefix_first, suffix_first

def _(value: Any):
    reveal_type(prefix_first(value))  # revealed: Unknown
    reveal_type(suffix_first(value))  # revealed: Unknown

Ambiguous class object return types

When every remaining overload returns a class object, the result retains type[...], including any shared generic structure within it. This also applies to final classes, which normalize to exact class objects.

overloaded.pyi:

from typing import final, overload

@final
class Final: ...

@overload
def classes(x: int) -> type[int]: ...
@overload
def classes(x: str) -> type[str]: ...
@overload
def generic_classes(x: int) -> type[list[int]]: ...
@overload
def generic_classes(x: str) -> type[list[str]]: ...
@overload
def final_classes(x: int) -> type[Final]: ...
@overload
def final_classes(x: str) -> type[str]: ...
from typing import Any
from overloaded import classes, generic_classes, final_classes

def _(value: Any):
    reveal_type(classes(value))  # revealed: type[Unknown]
    reveal_type(generic_classes(value))  # revealed: type[list[Unknown]]
    reveal_type(final_classes(value))  # revealed: type[Unknown]

Differing unions in ambiguous return types

Equivalent unions are preserved, but differing unions fall back to Unknown without trying to pair up their elements. Shared structure outside the union is still preserved.

overloaded.pyi:

from typing import overload

@overload
def union_arguments(x: int) -> list[int | str]: ...
@overload
def union_arguments(x: str) -> list[int | bytes]: ...
@overload
def optional(x: int) -> list[int] | None: ...
@overload
def optional(x: str) -> list[str] | None: ...
from typing import Any
from overloaded import union_arguments, optional

def _(value: Any):
    # A union-aware merge could infer list[int | Unknown], but we currently don't attempt to
    # find the common structure of two unions.
    reveal_type(union_arguments(value))  # revealed: list[Unknown]
    reveal_type(optional(value))  # revealed: Unknown

Argument expansion with shared return structure

Ambiguity is resolved separately for each expanded argument list. The final result is a union of those results, so a precise return from another expansion is preserved.

overloaded.pyi:

from typing import overload

@overload
def f(x: int, y: int) -> list[int]: ...
@overload
def f(x: int, y: str) -> list[str]: ...
@overload
def f(x: str, y: object) -> bytes: ...
from typing import Any
from overloaded import f

def _(x: int | str, y: Any):
    reveal_type(f(x, y))  # revealed: list[Unknown] | bytes

Single tuple argument

overloaded.pyi:

from typing import Any, overload

@overload
def f(x: tuple[int, str]) -> int: ...
@overload
def f(x: tuple[int, Any]) -> int: ...
@overload
def f(x: Any) -> str: ...
from typing import Any

from overloaded import f

reveal_type(f("a"))  # revealed: str
reveal_type(f(*("a",)))  # revealed: str

reveal_type(f((1, "b")))  # revealed: int
reveal_type(f(*((1, "b"),)))  # revealed: int

reveal_type(f((1, 2)))  # revealed: int
reveal_type(f(*((1, 2),)))  # revealed: int

def _(int_str: tuple[int, str], int_any: tuple[int, Any], any_any: tuple[Any, Any]):
    # All materializations are assignable to first overload, so second and third overloads are
    # eliminated
    reveal_type(f(int_str))  # revealed: int
    reveal_type(f(*(int_str,)))  # revealed: int

    # All materializations are assignable to second overload, so the third overload is eliminated;
    # the return type of first and second overload is equivalent
    reveal_type(f(int_any))  # revealed: int
    reveal_type(f(*(int_any,)))  # revealed: int

    # All materializations of `tuple[Any, Any]` are assignable to the parameters of all the
    # overloads, but the return types aren't equivalent, so the overload matching is ambiguous
    reveal_type(f(any_any))  # revealed: Unknown
    reveal_type(f(*(any_any,)))  # revealed: Unknown

Unknown passed into an overloaded function annotated with protocols

Foo.join() here has similar annotations to str.join() in typeshed:

module.pyi:

from typing_extensions import Iterable, overload, LiteralString, Protocol
from ty_extensions._internal import Unknown, is_assignable_to

class Foo:
    @overload
    def join(self, iterable: Iterable[LiteralString], /) -> LiteralString: ...
    @overload
    def join(self, iterable: Iterable[str], /) -> str: ...

main.py:

from module import Foo
from typing_extensions import LiteralString

def f(a: Foo, b: list[str], c: list[LiteralString], e):
    reveal_type(e)  # revealed: Unknown
    reveal_type(a.join(b))  # revealed: str
    reveal_type(a.join(c))  # revealed: LiteralString

    # since both overloads match and they have return types that are not equivalent,
    # step (5) of the overload evaluation algorithm says we must evaluate the result of the
    # call as `Unknown`.
    #
    # Note: although the spec does not state as such (since intersections in general are not
    # specified currently), `(str | LiteralString) & Unknown` might also be a reasonable type
    # here (the union of all overload returns, intersected with `Unknown`) -- here that would
    # simplify to `str & Unknown`.
    reveal_type(a.join(e))  # revealed: Unknown

Multiple arguments

overloaded.pyi:

from typing import Any, overload

class A: ...
class B: ...

@overload
def f(x: list[int], y: tuple[int, str]) -> A: ...
@overload
def f(x: list[Any], y: tuple[int, Any]) -> A: ...
@overload
def f(x: list[Any], y: tuple[Any, Any]) -> B: ...
from typing import Any

from overloaded import A, f

def _(list_int: list[int], list_any: list[Any], int_str: tuple[int, str], int_any: tuple[int, Any], any_any: tuple[Any, Any]):
    # All materializations of both argument types are assignable to the first overload, so the
    # second and third overloads are filtered out
    reveal_type(f(list_int, int_str))  # revealed: A
    reveal_type(f(*(list_int, int_str)))  # revealed: A

    # All materialization of first argument is assignable to first overload and for the second
    # argument, they're assignable to the second overload, so the third overload is filtered out
    reveal_type(f(list_int, int_any))  # revealed: A
    reveal_type(f(*(list_int, int_any)))  # revealed: A

    # All materialization of first argument is assignable to second overload and for the second
    # argument, they're assignable to the first overload, so the third overload is filtered out
    reveal_type(f(list_any, int_str))  # revealed: A
    reveal_type(f(*(list_any, int_str)))  # revealed: A

    # All materializations of both arguments are assignable to the second overload, so the third
    # overload is filtered out
    reveal_type(f(list_any, int_any))  # revealed: A
    reveal_type(f(*(list_any, int_any)))  # revealed: A

    # All materializations of first argument is assignable to the second overload and for the second
    # argument, they're assignable to the third overload, so no overloads are filtered out; the
    # return types of the remaining overloads are not equivalent, so overload matching is ambiguous
    reveal_type(f(list_int, any_any))  # revealed: Unknown
    reveal_type(f(*(list_int, any_any)))  # revealed: Unknown

LiteralString and str

overloaded.pyi:

from typing import overload
from typing_extensions import LiteralString

@overload
def f(x: LiteralString) -> LiteralString: ...
@overload
def f(x: str) -> str: ...
from typing import Any
from typing_extensions import LiteralString

from overloaded import f

def _(literal: LiteralString, string: str, any: Any):
    reveal_type(f(literal))  # revealed: LiteralString
    reveal_type(f(*(literal,)))  # revealed: LiteralString

    reveal_type(f(string))  # revealed: str
    reveal_type(f(*(string,)))  # revealed: str

    # `Any` matches both overloads, but the return types are not equivalent.
    # Pyright and mypy both reveal `str` here, contrary to the spec.
    reveal_type(f(any))  # revealed: Unknown
    reveal_type(f(*(any,)))  # revealed: Unknown

Generics

overloaded.pyi:

from typing import Any, TypeVar, overload

_T = TypeVar("_T")

class A: ...
class B: ...

@overload
def f(x: list[int]) -> A: ...
@overload
def f(x: list[_T]) -> _T: ...
@overload
def f(x: Any) -> B: ...
from typing import Any

from overloaded import f

def _(list_int: list[int], list_str: list[str], list_any: list[Any], any: Any):
    reveal_type(f(list_int))  # revealed: A
    reveal_type(f(*(list_int,)))  # revealed: A

    reveal_type(f(list_str))  # revealed: str
    reveal_type(f(*(list_str,)))  # revealed: str

    reveal_type(f(list_any))  # revealed: Unknown
    reveal_type(f(*(list_any,)))  # revealed: Unknown

    reveal_type(f(any))  # revealed: Unknown
    reveal_type(f(*(any,)))  # revealed: Unknown

Generics (multiple arguments)

overloaded.pyi:

from typing import Any, TypeVar, overload

_T = TypeVar("_T")

@overload
def f(x: int, y: Any) -> int: ...
@overload
def f(x: str, y: _T) -> _T: ...
from typing import Any

from overloaded import f

def _(integer: int, string: str, any: Any, list_any: list[Any]):
    reveal_type(f(integer, string))  # revealed: int
    reveal_type(f(*(integer, string)))  # revealed: int

    reveal_type(f(string, integer))  # revealed: int
    reveal_type(f(*(string, integer)))  # revealed: int

    # This matches the second overload and is _not_ the case of ambiguous overload matching.
    reveal_type(f(string, any))  # revealed: Any
    reveal_type(f(*(string, any)))  # revealed: Any

    reveal_type(f(string, list_any))  # revealed: list[Any]
    reveal_type(f(*(string, list_any)))  # revealed: list[Any]

Generic self

overloaded.pyi:

from typing import Any, overload, TypeVar, Generic

_T = TypeVar("_T")

class A(Generic[_T]):
    @overload
    def method(self: "A[int]") -> int: ...
    @overload
    def method(self: "A[Any]") -> int: ...

class B(Generic[_T]):
    @overload
    def method(self: "B[int]") -> int: ...
    @overload
    def method(self: "B[Any]") -> str: ...
from typing import Any

from overloaded import A, B

def _(a_int: A[int], a_str: A[str], a_any: A[Any]):
    reveal_type(a_int.method())  # revealed: int
    reveal_type(a_str.method())  # revealed: int
    reveal_type(a_any.method())  # revealed: int

def _(b_int: B[int], b_str: B[str], b_any: B[Any]):
    reveal_type(b_int.method())  # revealed: int
    reveal_type(b_str.method())  # revealed: str
    reveal_type(b_any.method())  # revealed: Unknown

Variadic argument

overloaded.pyi:

from typing import Any, overload

class A: ...
class B: ...

@overload
def f1(x: int) -> A: ...
@overload
def f1(x: Any, y: Any) -> A: ...
@overload
def f2(x: int) -> A: ...
@overload
def f2(x: Any, y: Any) -> B: ...
@overload
def f3(x: int) -> A: ...
@overload
def f3(x: Any, y: Any) -> A: ...
@overload
def f3(x: Any, y: Any, *, z: str) -> B: ...
@overload
def f4(x: int) -> A: ...
@overload
def f4(x: Any, y: Any) -> B: ...
@overload
def f4(x: Any, y: Any, *, z: str) -> B: ...
from typing import Any

from overloaded import f1, f2, f3, f4

def _(arg: list[Any]):
    # Matches both overload and the return types are equivalent
    reveal_type(f1(*arg))  # revealed: A
    # Matches both overload but the return types aren't equivalent
    reveal_type(f2(*arg))  # revealed: Unknown
    # Filters out the final overload and the return types are equivalent
    reveal_type(f3(*arg))  # revealed: A
    # Filters out the final overload but the return types aren't equivalent
    reveal_type(f4(*arg))  # revealed: Unknown

Variable-length arguments matched to different arities

A variable-length argument can match different numbers of parameters in each overload. Here, the later keyword argument does not cause an otherwise viable overload to be discarded.

overloaded.pyi:

from typing import overload

@overload
def f(x: int, y: int, /, *, flag: str) -> int: ...
@overload
def f(x: int, /, *, flag: str) -> str: ...
from overloaded import f

def _(args: tuple[int, ...]):
    reveal_type(f(*args, flag=""))  # revealed: Unknown

Required tuple elements before a later positional argument

The tuple's required final bytes element selects the second overload. Its variable-length part must be empty to leave room for 1.0:

overloaded.pyi:

from typing import overload

@overload
def f(a: str, b: float) -> str: ...
@overload
def f(a: bytes, b: float) -> bytes: ...
from overloaded import f

def _(args: tuple[*tuple[str, ...], bytes]) -> None:
    reveal_type(f(*args, 1.0))  # revealed: bytes

Variadic argument with generics

overloaded.pyi:

from typing import Any, TypeVar, overload

T1 = TypeVar("T1")
T2 = TypeVar("T2")
T3 = TypeVar("T3")

@overload
def f1(x: T1, /) -> tuple[T1]: ...
@overload
def f1(x1: T1, x2: T2, /) -> tuple[T1, T2]: ...
@overload
def f1(x1: T1, x2: T2, x3: T3, /) -> tuple[T1, T2, T3]: ...
@overload
def f1(*args: Any) -> tuple[Any, ...]: ...
@overload
def f2(x1: T1) -> tuple[T1]: ...
@overload
def f2(x1: T1, x2: T2) -> tuple[T1, T2]: ...
@overload
def f2(*args: Any, **kwargs: Any) -> tuple[Any, ...]: ...
@overload
def f3(x: T1) -> tuple[T1]: ...
@overload
def f3(x1: T1, x2: T2) -> tuple[T1, T2]: ...
@overload
def f3(*args: Any) -> tuple[Any, ...]: ...
@overload
def f3(**kwargs: Any) -> dict[str, Any]: ...
from overloaded import f1, f2, f3
from typing import Any

# These calls only match the last overload
reveal_type(f1())  # revealed: tuple[Any, ...]
reveal_type(f1(1, 2, 3, 4))  # revealed: tuple[Any, ...]

# While these calls match multiple overloads but step 5 filters out all the remaining overloads
# except the most specific one in terms of the number of arguments.
reveal_type(f1(1))  # revealed: tuple[Literal[1]]
reveal_type(f1(1, 2))  # revealed: tuple[Literal[1], Literal[2]]
reveal_type(f1(1, 2, 3))  # revealed: tuple[Literal[1], Literal[2], Literal[3]]

def _(args1: list[int], args2: list[Any]):
    reveal_type(f1(*args1))  # revealed: tuple[Any, ...]
    reveal_type(f1(*args2))  # revealed: tuple[Any, ...]

reveal_type(f2())  # revealed: tuple[Any, ...]
reveal_type(f2(1, 2))  # revealed: tuple[Literal[1], Literal[2]]
reveal_type(f2(x1=1, x2=2))  # revealed: tuple[Literal[1], Literal[2]]
reveal_type(f2(x2=1, x1=2))  # revealed: tuple[Literal[2], Literal[1]]
reveal_type(f2(1, 2, z=3))  # revealed: tuple[Any, ...]

reveal_type(f3(1, 2))  # revealed: tuple[Literal[1], Literal[2]]
reveal_type(f3(1, 2, 3))  # revealed: tuple[Any, ...]
reveal_type(f3(x1=1, x2=2))  # revealed: tuple[Literal[1], Literal[2]]
reveal_type(f3(z=1))  # revealed: dict[str, Any]

# error: [no-matching-overload]
reveal_type(f3(1, 2, x=3))  # revealed: Unknown

Variadic argument with generic iterable

overloaded.pyi:

from typing import TypeVar, overload
from collections.abc import Iterable

T = TypeVar("T")
T1 = TypeVar("T1")
T2 = TypeVar("T2")
T3 = TypeVar("T3")

@overload
def f(x: Iterable[T1], /) -> tuple[T1]: ...
@overload
def f(x: Iterable[T1], y: Iterable[T2], /) -> tuple[T1, T2]: ...
@overload
def f(x: Iterable[T1], y: Iterable[T2], z: Iterable[T3], /) -> tuple[T1, T2, T3]: ...
@overload
def f(*args: Iterable[T]) -> tuple[T, ...]: ...
from overloaded import f

class A: ...
class B: ...
class C: ...

def _(lista: list[A], listb: list[B], listc: list[C]):
    reveal_type(f(lista))  # revealed: tuple[A]
    reveal_type(f(lista, listb))  # revealed: tuple[A, B]
    reveal_type(f(lista, listb, listc))  # revealed: tuple[A, B, C]
    reveal_type(f())  # revealed: tuple[Unknown, ...]

Non-participating fully-static parameter

Ref: https://github.com/astral-sh/ty/issues/552#issuecomment-2969052173

A non-participating parameter would be the one where the set of materializations of the argument type, that are assignable to the parameter type at the same index, is same for the overloads for which step 5 needs to be performed.

overloaded.pyi:

from typing import Literal, overload

@overload
def f(x: str, *, flag: Literal[True]) -> int: ...
@overload
def f(x: str, *, flag: Literal[False] = ...) -> str: ...
@overload
def f(x: str, *, flag: bool = ...) -> int | str: ...

In the following example, for the f(any, flag=True) call, the materializations of first argument type Any that are assignable to str is same for overloads 1 and 3 (at the time of step 5), so for the purposes of overload matching that parameter can be ignored. If Any materializes to anything that's not assignable to str, all of the overloads would already be filtered out which will raise a no-matching-overload error.

from typing import Any

from overloaded import f

def _(any: Any):
    reveal_type(f(any, flag=True))  # revealed: int
    reveal_type(f(*(any,), flag=True))  # revealed: int

    reveal_type(f(any, flag=False))  # revealed: str
    reveal_type(f(*(any,), flag=False))  # revealed: str

Non-participating gradual parameter

overloaded.pyi:

from typing import Any, Literal, overload

@overload
def f(x: tuple[str, Any], flag: Literal[True]) -> int: ...
@overload
def f(x: tuple[str, Any], flag: Literal[False] = ...) -> str: ...
@overload
def f(x: tuple[str, Any], flag: bool = ...) -> int | str: ...
from typing import Any, Literal

from overloaded import f

def _(any: Any):
    reveal_type(f(any, flag=True))  # revealed: int
    reveal_type(f(*(any,), flag=True))  # revealed: int

    reveal_type(f(any, flag=False))  # revealed: str
    reveal_type(f(*(any,), flag=False))  # revealed: str

def _(args: tuple[Any, Literal[True]]):
    reveal_type(f(*args))  # revealed: int

def _(args: tuple[Any, Literal[False]]):
    reveal_type(f(*args))  # revealed: str

Argument type expansion

This filtering can also happen for each of the expanded argument lists.

No ambiguity

overloaded.pyi:

from typing import Any, overload

class A: ...
class B: ...

@overload
def f(x: tuple[A, B]) -> A: ...
@overload
def f(x: tuple[B, A]) -> B: ...
@overload
def f(x: tuple[A, Any]) -> A: ...
@overload
def f(x: tuple[B, Any]) -> B: ...

Here, the argument tuple[A | B, Any] doesn't match any of the overloads, so we perform argument type expansion which results in two argument lists:

  1. tuple[A, Any]
  2. tuple[B, Any]

The first argument list matches overload 1 and 3 via Any materialization for which the return types are equivalent (A). Similarly, the second argument list matches overload 2 and 4 via Any materialization for which the return types are equivalent (B). The final return type for the call will be the union of the return types.

from typing import Any

from overloaded import A, B, f

def _(arg: tuple[A | B, Any]):
    reveal_type(f(arg))  # revealed: A | B
    reveal_type(f(*(arg,)))  # revealed: A | B

One argument list ambiguous

The example used here is same as the previous one, but the return type of the last overload is changed so that it's not equivalent to the return type of the second overload, creating an ambiguous matching for the second argument list.

overloaded.pyi:

from typing import Any, overload

class A: ...
class B: ...
class C: ...

@overload
def f(x: tuple[A, B]) -> A: ...
@overload
def f(x: tuple[B, A]) -> B: ...
@overload
def f(x: tuple[A, Any]) -> A: ...
@overload
def f(x: tuple[B, Any]) -> C: ...
from typing import Any

from overloaded import A, B, C, f

def _(arg: tuple[A | B, Any]):
    reveal_type(f(arg))  # revealed: A | Unknown
    reveal_type(f(*(arg,)))  # revealed: A | Unknown

# Ambiguity from the first expansion must not affect the second expansion's return type.
def _(arg: tuple[B | A, Any]):
    reveal_type(f(arg))  # revealed: Unknown | A

Both argument lists ambiguous

Here, both argument lists created by expanding the argument type are ambiguous, so the final return type is Any.

overloaded.pyi:

from typing import Any, overload

class A: ...
class B: ...
class C: ...

@overload
def f(x: tuple[A, B]) -> A: ...
@overload
def f(x: tuple[B, A]) -> B: ...
@overload
def f(x: tuple[A, Any]) -> C: ...
@overload
def f(x: tuple[B, Any]) -> C: ...
from typing import Any

from overloaded import A, B, C, f

def _(arg: tuple[A | B, Any]):
    reveal_type(f(arg))  # revealed: Unknown
    reveal_type(f(*(arg,)))  # revealed: Unknown

Unknown argument with TypeVar overload

When an Unknown argument is passed to an overloaded function where one overload has a concrete parameter type and another uses a TypeVar, the parameter types must not be considered equivalent during step 5's "participating parameter" determination. If TypeVar solving were allowed during that equivalence check, the solver could find an assignment (e.g. T = None) that makes the parameters look equivalent, causing step 5 to skip filtering entirely and incorrectly pick the first overload.

overloaded.pyi:

from typing import TypeVar, overload, Literal, Iterable

T = TypeVar("T")

@overload
def f(components: Iterable[None]) -> Literal[b""]: ...
@overload
def f(components: Iterable[T | None]) -> T: ...
from overloaded import f
from nonexistent_module import something_unknown  # error: [import-not-found]

reveal_type(something_unknown)  # revealed: Unknown

# The result should be `Unknown`, not `Literal[b""]`.
reveal_type(f(something_unknown))  # revealed: Unknown
reveal_type(f((something_unknown, something_unknown, something_unknown)))  # revealed: Unknown
reveal_type(f((something_unknown, None, something_unknown)))  # revealed: Unknown

# Concrete arguments should still resolve correctly.
def _(s: str):
    reveal_type(f((s, s, None)))  # revealed: str

reveal_type(f((None, None, None)))  # revealed: Literal[b""]

An unannotated parameter with a context-dependent argument

Both overloads initially match when index is 1. The first leaves value unannotated, so first() uses its type variable's default of int. Filtering with that argument type selects the first overload. When index is a string, only the second overload matches and it supplies Never as the expected type for first().

from typing import overload
from typing_extensions import Never, TypeVar

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

def first(*values: T) -> T:
    return values[0]

@overload
def choose(value, index: int) -> int: ...
@overload
def choose(value: Never, index: object) -> object: ...
def choose(value, index):
    return index

result = choose(reveal_type(first()), 1)  # revealed: int
reveal_type(result)  # revealed: int

choose(reveal_type(first()), "x")  # revealed: Never

Bidirectional Type Inference

[environment]
python-version = "3.12"

Type inference accounts for parameter type annotations across all overloads.

from typing import TypedDict, overload

class T(TypedDict):
    x: int

@overload
def f(a: list[T], b: int) -> int: ...
@overload
def f(a: list[dict[str, int]], b: str) -> str: ...
def f(a: list[dict[str, int]] | list[T], b: int | str) -> int | str:
    return 1

def int_or_str() -> int | str:
    return 1

x = f([{"x": 1}], int_or_str())
reveal_type(x)  # revealed: int | str

# error: [no-matching-overload] "No overload of function `f` matches arguments"
f([{"y": 1}], int_or_str())

An expected return type can specialize a generic overload and provide context for its arguments. Overload filtering should preserve that context:

from typing import Any, overload

@overload
def f[T](value: T) -> T: ...
@overload
def f(value: Any) -> Any: ...
def f(value: Any) -> Any: ...

values: list[int] = reveal_type(f([]))  # revealed: list[int]

Non-matching overloads do not produce diagnostics:

from typing import TypedDict, overload

class T(TypedDict):
    x: int

@overload
def f(a: T, b: int) -> int: ...
@overload
def f(a: dict[str, int], b: str) -> str: ...
def f(a: T | dict[str, int], b: int | str) -> int | str:
    return 1

x = f({"y": 1}, "a")
reveal_type(x)  # revealed: str

Only the types and diagnostics produced by inference against matching overloads are preserved:

from collections.abc import Callable
from typing import TypedDict, overload

@overload
def transform(value: str, callback: Callable[[int], str], /) -> str: ...
@overload
def transform(value: bytes, callback: Callable[[int], bytes], /) -> bytes: ...
def transform(value: str | bytes, callback: Callable[..., str | bytes], /) -> str | bytes:
    return value

string_result = transform(
    "",
    reveal_type(lambda x: str(x) * x),  # revealed: (x: int) -> str
)
reveal_type(string_result)  # revealed: str
bytes_result = transform(
    b"",
    reveal_type(lambda x: x.to_bytes(1)),  # revealed: (x: int) -> bytes
)
reveal_type(bytes_result)  # revealed: bytes

class Payload(TypedDict):
    name: str
    count: int

@overload
def select_payload(payload: Payload, discriminator: int, /) -> int: ...
@overload
def select_payload(payload: dict[str, object], discriminator: str, /) -> str: ...
def select_payload(payload: Payload | dict[str, object], discriminator: int | str, /) -> int | str:
    return discriminator

# error: [missing-typed-dict-key] "Missing required key 'count' in TypedDict `Payload` constructor"
# error: [no-matching-overload]
select_payload({"name": "missing count"}, 1)

# error: [invalid-argument-type]
# error: [no-matching-overload]
select_payload({"name": "bad count", "count": "not an int"}, 1)

# error: [unknown-typed-dict-constructor-key]
# error: [no-matching-overload]
select_payload({"name": "extra key", "count": 1, "extra": None}, 1)

select_payload({"extra": None}, "plain dictionary")

@overload
def select_generic_payload[T](value: T, payload: Payload, discriminator: int, /) -> T: ...
@overload
def select_generic_payload[T](value: T, payload: dict[str, object], discriminator: str, /) -> T: ...
def select_generic_payload[T](
    value: T,
    payload: Payload | dict[str, object],
    discriminator: int | str,
    /,
) -> T:
    return value

selected_generic_payload = select_generic_payload(
    1,
    reveal_type({"name": "generic", "count": 1}),  # revealed: Payload
    1,
)
reveal_type(selected_generic_payload)  # revealed: Literal[1]

# error: [missing-typed-dict-key] "Missing required key 'count' in TypedDict `Payload` constructor"
# error: [no-matching-overload]
select_generic_payload(1, {"name": "generic"}, 1)

select_generic_payload(1, {"extra": None}, "plain dictionary")
from typing import SupportsRound, overload

@overload
def takes_str_or_float(x: str): ...
@overload
def takes_str_or_float(x: float): ...
def takes_str_or_float(x: float | str): ...

takes_str_or_float(round(1.0))