Tutorial by Examples

The typing.TypeVar is a generic type factory. It's primary goal is to serve as a parameter/placeholder for generic function/class/method annotations: import typing T = typing.TypeVar("T") def get_first_element(l: typing.Sequence[T]) -> T: """Gets the first ele...
Let's take an example of a function which receives two arguments and returns a value indicating their sum: def two_sum(a, b): return a + b By looking at this code, one can not safely and without doubt indicate the type of the arguments for function two_sum. It works both when supplied with ...
class A: x = None # type: float def __init__(self, x: float) -> None: """ self should not be annotated init should be annotated to return None """ self.x = x @classmethod def from_int(cls, x: int...
Variables are annotated using comments: x = 3 # type: int x = negate(x) x = 'a type-checker might catch this error' Python 3.x3.6 Starting from Python 3.6, there is also new syntax for variable annotations. The code above might use the form x: int = 3 Unlike with comments, it is also pos...
Creating a namedtuple with type hints is done using the function NamedTuple from the typing module: import typing Point = typing.NamedTuple('Point', [('x', int), ('y', int)]) Note that the name of the resulting type is the first argument to the function, but it should be assigned to a variable ...
def hello_world(greeting: str = 'Hello'): print(greeting + ' world!') Note the spaces around the equal sign as opposed to how keyword arguments are usually styled.

Page 1 of 1