Search notes:
Python standard library: typing
Any
Any is the default annotation for all arguments or return types that are not explicitely specified.
Callable
Callable[ [t1, t2], tr ] is a callback function that expects two arguments of types t1 and t2 and returns a tr.
It's possible to define only the return type: Callable[ ..., tr]. (Note there are no square brackets around the ellipsis).
Dict
from typing import Dict
opts: Dict[int, str] = {}
def add_opt(k: int, v: str) -> None:
opts[k] = v
def show_kv(d: Dict[int, str]):
for k in d:
print(str(k) + ': ' + d[k])
add_opt(4, 'four' )
add_opt(1, 'one' )
add_opt(8, 'eight')
show_kv(opts)
Compare with Mapping.
Mapping
Compare with Dict and MutableMapping.
None
The return type of __init__ should be annotated with -> None.
NoReturn
NoReturn indicates that a a function does not return normally, such as sys.exit.
from typing import NoReturn
def fail() -> NoReturn:
raise RuntimeError('failed')
Optional
from typing import Optional
def p(a: Optional[int] = 42, b: Optional[str] = 'Hello world'):
print(f'a = {a}')
print(f'b = {b}')
p(b='hi')
TypeVar
from typing import TypeVar
x = TypeVar('y')
$ pyright /tmp/u.py
/tmp/u.py:2:1 - error: TypeVar must be assigned to a variable named "y" (reportGeneralTypeIssues)
TYPE_CHECKING
Static type checkers must treat typeing.TYPE_CHECKING as True.
typing.TYPE_CHECKING will be deprecated.
See also PEP 781 (Make TYPE_CHECKING a built-in constant)