3.9. Typing Callable

  • Before Python 3.9 you need from typing import List, Set, Tuple, Dict

  • Since Python 3.9: PEP 585 -- Type Hinting Generics In Standard Collections

3.9.1. Return

>>> def run() -> int:
...     ...

3.9.2. Required Parameters

>>> def run(a: int, b: int):
...     ...

3.9.3. Optional Parameters

>>> def run(a: int = 0, b: int = 1):
...     ...

3.9.4. Mixed Parameters

>>> def run(a: int, b: int = 1):
...     ...

3.9.5. Union

>>> def run(a: int | float, b: int | float) -> int | float:
...     ...

3.9.6. Optional

>>> def run(a: int | None, b: int | None) -> int | None:
...     ...

3.9.7. NoReturn

>>> from typing import NoReturn
>>> def run() -> NoReturn:
...     pass
>>> def run() -> NoReturn:
...     print('hello')

In Python functions always return something. If you don't specify a return value, Python will return None. If you want to indicate that a function never returns, you can use NoReturn.

>>> def run() -> None:
...     return None
>>> def run() -> None:
...     pass
>>> def run() -> None:
...     print('hello')

3.9.8. Exception

>>> from typing import NoReturn
>>>
>>> def run() -> NoReturn:
...     raise ValueError
>>> def run() -> Exception:
...     raise ValueError
>>> def run() -> ValueError:
...     raise ValueError
>>> def run(value: int) -> int | ValueError:
...     if value <= 0:
...         raise ValueError
...     else:
...         return value

3.9.9. Literal

SetUp:

>>> from typing import Literal

Definition:

>>> def open(filename: str, mode: Literal['r','w','a']) -> None:
...     pass

Usage:

>>> open('myfile.txt', mode='w')  # ok
>>> open('myfile.txt', mode='r')  # ok
>>> open('myfile.txt', mode='a')  # ok
>>> open('myfile.txt', mode='x')  # error

3.9.10. Literal String

  • Since Python 3.11: PEP 675 -- Arbitrary Literal String Type

SetUp:

>>> from typing import LiteralString

Example:

>>> def execute(sql: LiteralString):
...    ...
>>>
>>> username = 'mwatney'
>>>
>>>
>>> execute('SELECT * FROM users WHERE login="mwatney"')                       # ok
>>> execute('SELECT * FROM users WHERE login=' + username)                     # ok
>>> execute('SELECT * FROM users WHERE login=%s' % username)                   # error
>>> execute('SELECT * FROM users WHERE login=%(login)s' % {'login': username}) # error
>>> execute('SELECT * FROM users WHERE login={}'.format(username))             # error
>>> execute('SELECT * FROM users WHERE login={0}'.format(username))            # error
>>> execute('SELECT * FROM users WHERE login={login}'.format(login=username))  # error
>>> execute(f'SELECT * FROM users WHERE login={username}')                     # error

3.9.11. Callable

SetUp:

>>> from typing import Callable

Define:

>>> def run(a: int, b: int) -> float:
...     ...
>>>
>>> a: Callable = run
>>> b: Callable[..., float] = run
>>> c: Callable[[int,int], ...] = run
>>> d: Callable[[int,int], float] = run

Parameter:

>>> def run(func: Callable[[int, int], float]):
...     ...

3.9.12. Iterator

  • Iterator[yield_type]

SetUp:

>>> from typing import Iterator

Definition:

>>> def run() -> Iterator[int]:
...     yield 1

3.9.13. Generator

  • All Generators are Iterators

  • Generator[yield_type, send_type, return_type]

  • Iterator[yield_type]

SetUp:

>>> from typing import Iterator, Generator

Generator type annotations:

>>> def run() -> Generator[int, bool, str]:
...     yield 1         # int
...     data = yield    # bool (expected)
...     return 'done'   # str

All Generators are Iterators so you can write:

>>> def run() -> Iterator[int]:
...     yield 1

3.9.14. Convention

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

3.9.15. Use Case - 1

>>> def valid_email(email: str) -> str | Exception:
...     if '@' in email:
...         return email
...     else:
...         raise ValueError('Invalid Email')
>>>
>>>
>>> valid_email('mwatney@nasa.gov')
'mwatney@nasa.gov'
>>>
>>> valid_email('mwatney_at_nasa.gov')
Traceback (most recent call last):
ValueError: Invalid Email

3.9.16. Use Case - 2

>>> def find(text: str, what: str) -> int | None:
...     position = text.find(what)
...     if position == -1:
...         return None
...     else:
...         return position
>>>
>>>
>>> find('Python', 'x')
>>> find('Python', 'o')
4

3.9.17. Use Case - 3

>>> from urllib.request import urlopen
>>> from typing import Any
>>>
>>>
>>> def fetch(url: str,
...           on_success: Callable[[str], Any] = lambda result: ...,
...           on_error: Callable[[Exception], Any] = lambda error: ...,
...           ) -> None:
...     try:
...         result: str = urlopen(url).read().decode('utf-8')
...     except Exception as err:
...         on_error(err)
...     else:
...         on_success(result)
>>> def handle_result(result: str) -> None:
...     print('Success', result)
>>>
>>> def handle_error(error: Exception) -> None:
...     print('Error', error)
>>>
>>>
>>> fetch(
...     url='https://python3.info',
...     on_success=handle_result,
...     on_error=handle_error,
... )  
>>> fetch(
...     url='https://python3.info',
...     on_success=lambda result: print(result),
...     on_error=lambda error: print(error),
... )