typestar

overload in Python

Several signatures for one function, so the checker knows what comes back.

from typing import overload


@overload
def parse(text: str) -> int:
    ...


@overload
def parse(text: str, default: str) -> int | str:
    ...


def parse(text, default=None):
    try:
        return int(text)
    except ValueError:
        if default is None:
            raise
        return default


print(parse("42"), parse("x", "fallback"))
print(parse.__name__)

How it works

  1. Each @overload stub declares one calling shape.
  2. The real implementation follows, untyped by overload.
  3. At run time only the implementation exists.

Keywords and builtins used here

The run, in numbers

Lines
24
Characters to type
319
Tokens
94
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 51 seconds.

Type this snippet

Step 4 of 4 in Typing in depth, step 44 of 53 in Pythonic Python.

← Previous Next →