kota's memex

Python 3.5 finally added support for indicating what type a given variable is supposed to be:

def describeNumber(number: int) -> str:
    if number % 2 == 1:
        return 'An odd number. '
    elif number == 42:
        return 'The answer. '
    else:
        return 'Yes, that is a number. '

myLuckyNumber: int = 42
print(describeNumber(myLuckyNumber))

typing package

The typing package adds support for a few more types common in other languages, such as the union type:

unions

from typing import Union
spam: Union[int, str, float] = 42
spam = 'hello'
spam = 3.14

optional

from typing import Optional
lastName: Optional[str] = None
lastName = 'Sweigart'

lists, tuple, dict, set, sequence, mapping

These are some of the most common type aliases: - List is for the list data type. - Tuple is for the tuple data type. - Dict is for the dictionary (dict) data type. - Set is for the set data type. - FrozenSet is for the frozenset data type. - Sequence is for the list, tuple, and any other sequence data type. - Mapping is for the dictionary (dict), set, frozenset, and any other mapping data type. - ByteString is for the bytes, bytearray, and memoryview types.

from typing import List, Union
catNames: List[str] = ['Zophie', 'Simon', 'Pooka', 'Theodore']
numbers: List[Union[int, float]] = [42, 3.14, 99.9, 86]

any

On the rare case you want to use a "nil pointer" or "blank interface" you can import type any. Obviously, if you just don't add any type hinting then you're already doing this.

from typing import Any
import datetime
spam: Any = 42
spam = datetime.date.today()
spam = True