Python 3 (2 is EOL) allows to add some type hints. They are not enforced without special measures, but can be used by linters (like mypy), REPLs and langservers.
import typing to the top of a file
- Output type of a function is shown by an
-> before :
- Types of arguments are shown by adding
: TypeOfArg right after arg name
- Union types are
typing.Union[T1, T2]
- Lists are
typing.List[T], or maybe even more generic typing.Iterable[T]
- type of
self is usually not marked as a type of an arg
- If a func returns nothing, use
-> None
- You need to set the types as strings containing their names if the type is not yet defined:
def a(b: "A") -> "A":
return b
class A:
def __init__(self, asdf: typing.Optional["A"] = None) -> None:
pass
class B:
def __init__(self, asdf: A) -> None:
pass
Python 3 (2 is EOL) allows to add some type hints. They are not enforced without special measures, but can be used by linters (like
mypy), REPLs and langservers.import typingto the top of a file->before:: TypeOfArgright after arg nametyping.Union[T1, T2]typing.List[T], or maybe even more generictyping.Iterable[T]selfis usually not marked as a type of an arg-> None