Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Typing & static analysisSeniorSpecialistPractical

What does `@typing.overload` let you express that a single type-hinted function signature cannot?

Answer

`@overload` lets you declare multiple type signatures for the same function name, each describing a different valid combination of argument and return types, followed by one real implementation without the decorator that actually runs at call time. A type checker uses the overloaded signatures — never the implementation's own signature — to pick the correct, most specific return type for a given call, which is essential for functions whose return type genuinely depends on which arguments or argument types were passed, something a single generic signature cannot express precisely.

Strong answer includes

  • declares multiple signatures for the same function name for checkers to pick from
  • followed by one real, undecorated implementation that runs at call time
  • needed when return type genuinely depends on which arguments were passed

Practical example

Python example
@overload
def parse(value: str) -> dict: ...
@overload
def parse(value: bytes) -> bytes: ...
def parse(value): ...

lets a checker know

Python example
parse("x")

returns a `dict` while

Python example
parse(b"x")

returns `bytes` .

#typing#overload

Sources

typing — Support for type hintsPython Software Foundation · Generics, protocols, overloads and typing-module semantics