🎓 A1Learner
🔍

Python Typing Callables & Aliases

A function hint describes a function as a value. Callable lists the parameter types and the return type.

Describe a function value

Callable lists parameter types in brackets. The type after the comma is the return type.

from typing import Callable

def apply(func: Callable[[int], str], value: int) -> str:
    return func(value)

def label(n: int) -> str:
    return f"#{n}"

print(apply(label, 7))

Name a long hint

A named hint is called an alias. Points now stands for the whole list hint.

from typing import TypeAlias

Points: TypeAlias = list[tuple[int, int]]

path: Points = [(0, 0), (3, 4)]
print(len(path))
print(path[1])

Mark a name as final

Final says this name should keep its first value. Checkers can flag a second assignment.

from typing import Final

MAX_SCORE: Final = 100
print(MAX_SCORE)

Limit a value to fixed choices

A literal type lists the exact choices allowed. Here the mode must be one of two words.

from typing import Literal

def set_mode(mode: Literal["easy", "hard"]) -> None:
    print(mode)

set_mode("easy")

Use the escape hatch with care

Any lets one parameter accept every type. The cost is that checking stops for that value.

from typing import Any

def show(value: Any) -> None:
    print(value)

show(42)
show("cake")

Example

from typing import Callable, Literal, TypeAlias

Formatter: TypeAlias = Callable[[str], str]

def shout(text: str) -> str:
    return text.upper() + "!"

def bracket(text: str) -> str:
    return f"[{text}]"

formatters: dict[str, Formatter] = {"shout": shout, "bracket": bracket}

def run_formatter(name: Literal["shout", "bracket"], text: str) -> str:
    formatter = formatters[name]
    return formatter(text)

print(run_formatter("shout", "hello"))
print(run_formatter("bracket", "hello"))

Key points

  • Callable[[int], str]: a function that takes a whole number and returns text
  • TypeAlias: the marker for a named hint that you can reuse
  • Use Final for a name that should not be given a new value
  • Literal: a hint that allows only the exact values listed
  • Use Any only as a last resort, because it pauses checking for that value
  • Final and Literal are hints only, like the rest
  • A function can be described by a hint like any other value.

In this example, Formatter is an alias for a text function. A Formatter takes text and returns text. The shout function turns text into upper case. The bracket function wraps text in square brackets. The formatters dict pairs each name with its function. Its value hint uses the Formatter alias. The run_formatter function looks up one formatter by name. Its name hint lists the two allowed names. Each call runs the chosen function on hello. The prints show the two styled results.

Note

Python still runs code that breaks them.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does Callable[[int], str] describe?