Problem Log

Full Stack Introduction

PEP 484: Type Hints in Python

Beginning in Python 3.5, type hints are allowed in function signatures. This PEP aims to define a common syntax for type hints. The module, typing, defines base types and has some basic tooling for dealing with types. But static analysis is done by third-party software, like mypy.

Definition syntax

def greeting(name: str) -> str:
  return f'Hi {name}'
  • __init__ should have a return type of None
  • __annotations__ attribute contains the type hint information
  • Available type hints: None, Any, Union, Tuple, Callable, all ABCs and stand-ins for concrete classes exported from typing (e.g. Sequence and Dict), type variables, and type aliases
    • The type hint None evaluates to type(None)

Example of type alias, concrete classes, and generics:

from typing import TypeVar, Iterable, Tuple

T = TypeVar('T', int, float, complex)
Vector = Iterable[Tuple[T, T]]

Example of Callable types. A callable return type can leave the arguments unspecified by using an ellipsis:

from typing import Callable

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

def partial(func: Callable[..., str], *args) -> Callable[..., str]:
  pass