10.7. Functions and Methods

10.7.1. Simple

def add(a: int, b: float) -> float:
    return a + b

add(1, 2.5)

10.7.2. The NoReturn type

from typing import NoReturn

def stop() -> NoReturn:
    raise RuntimeError

10.7.3. Iterator

from typing import Iterator

def fib(n: int) -> Iterator[int]:
    a, b = 0, 1
    while a < n:
        yield a
        a, b = b, a + b

10.7.4. Callable

from typing import Callable

def feeder(get_next_item: Callable[[], str]) -> None:

def async_query(on_success: Callable[[int], None],
                on_error: Callable[[int, Exception], None]) -> None:

10.7.5. Overload

New in version Python: 3.8 See PEP 589

  • The @overload decorator allows describing functions and methods that support multiple different combinations of argument types.

  • A series of @overload-decorated definitions must be followed by exactly one non-@overload-decorated definition (for the same function/method)

  • The @overload-decorated definitions are for the benefit of the type checker only, since they will be overwritten by the non-@overload-decorated definition

def process(response: None) -> None:

def process(response: int) -> Tuple[int, str]:

def process(response: bytes) -> str:

def process(response):
    <actual implementation>

10.7.6. Final

New in version Python: 3.8 See PEP 589

from typing import final

class Base:
    def foo(self) -> None:

class Derived(Base):
    def foo(self) -> None:  # Error: Cannot override final attribute "foo"
                            # (previously declared in base class "Base")