typing

New in version 3.5.

TYPE_CHECKING

typing.TYPE_CHECKING

Булево, в runtime’е будет False

cast()

typing.cast()

final()

typing.final()

New in version 3.8.

# от этого класса нельзя наследоваться
@final
class SomeClass:
    pass
# нельзя переопределять метод
class SomeClass:

    @final
    def foo(self):
        pass

get_args()

typing.get_args()
get_origin(Dict[str, int]) is dict
get_args(Dict[int, str]) == (int, str)

get_origin(Union[int, str]) is Union
get_args(Union[int, str]) == (int, str)

get_origin()

typing.get_origin(tp)

get_type_hints()

typing.get_type_hints(obj, globals, locals)

no_type_check()

typing.no_type_check()

no_type_check_decorator()

typing.no_type_check_decorator()

overload()

typing.overload()
@overload
def process(response: None) -> None: ...

@overload
def process(response: int) -> Tuple[int, str]: ...

@overload
def process(response: bytes) -> str: ...

def process(response):
    # implementation

runtime_checkable()

typing.runtime_checkable()
New in version 3.8: @runtime_checkable
class Closable(Protocol):

    def close(self):
        pass

assert isinstance(open(path), Closable)

type_check_only()

typing.type_check_only()
@type_check_only
class Response:
    pass

def fetch() -> Response:
    pass

AbstractSet()

class typing.AbstractSet(Sized, Collection)

Generic версия collections.abc.Set

Any()

class typing.Any
def func(item: Any):
    pass

AnyStr()

class typing.AnyStr
AnyStr == TypeVar('AnyStr', str, bytes)

AsyncContextManager()

class typing.AsyncContextManager(Generic[T_co])

Generic версия collections.AbstractAsyncContextManager

AsyncGenerator()

class typing.AsyncGenerator(AsyncIterator[T_co], Generic[T_co, T_contra])
# AsyncGenerator[YieldType, SendType]

async def func() -> AsyncGenerator[int, float]:

    sent = yield =0
    while sent >= 0.0:
        rounded = await round(sent)
        sent = yield rounded

AsyncIterable()

class typing.AsyncIterable(Generic[_coT])

New in version 3.5.2.

Generic версия collections.abc.AsyncIterable

AsyncIterator()

class typing.AsyncIterator(AsyncIterable[T])

Generic версия collections.abc.AsyncIterator

Awaitable()

class typing.Awaitable(Generic[T_co])

New in version 3.5.2.

Generic версия collections.abc.Awaitable

BinaryIO()

class typing.BinaryIO

ByteString()

class typing.ByteString(Sequence[T])

Generic версия collections.abc.ByteString

Callable()

class typing.Callable([ArgTypes, ..., ]ReturnValue)
def func(get_next_item: Callable[[], str]):
    pass

ChainMap()

class typing.ChainMap(collections.ChainMap, MutableMapping[KT, VT])

Generic версия collections.ChainMap

ClassVar()

class typing.ClassVar
class Starship:
    stats: ClassVar[Dict[str, int]] = {}

ship = Starship()

ship.stats = {}
# Error, setting class variable on instance

Starship.stats = {}
# ok

Collection()

class typing.Collection(Sized, Iterable, Container)

New in version 3.6.

Generic версия collections.abc.Collection

Container()

class typing.Container

Generic версия collections.abc.Container

ContextManager()

class typing.ContextManager(Generic[T_co])

Generic версия collections.AbstractContextManager

Coroutine()

class typing.Coroutine(Awaitable[V_co], Generic[T_co T_contra, V_co])

New in version 3.5.3.

Generic версия collections.abc.Coroutine

c = None  # type: Coroutine[List[str], str, int]
x = c.send('hi)  # type: List[str]

async def bar() -> None:
    x = await c  # type: int

Counter()

class typing.Counter(collections.Counter, Dict[T, int])

Generic версия collections.Counter

DefaultDict()

class typing.DefaultDict(collections.defaultdict, MutableMapping[KT, VT])

Generic версия collections.defaultdict

Deque()

class typing.Deque(deque, MutableSequence[T])

New in version 3.5.4.

Generic версия collections.deque

Dict()

class typing.Dict(dict, MutableMapping[KT, VT])
def func(item: Dict[str, str]):
    pass

Final()

class typing.Final

New in version 3.8.

# переменную нельзя переприсвоить
ID: FINAL[float] = 1
ID = 2  # error: Cannot assign to final name "ID"

STR: Final = 'final'
STR = "oops"  # error: Cannot assign to final name "STR"

letters: Final = []
letters.append('c')  # ok

class ImmutablePoint:
    x: Final[int]
    y: Final[int]  # error: Final name must be initialized with a value

    def __init__(self) -> None:
        self.x = 1  # ok

ImmutablePoint().x = 2 # error: Cannot assign to final attribute "x"

ForwardRef()

class typing.ForwardRef

FrozenSet()

class typing.FrozenSet(frozenset, AbstractSet[T_co])

Generic версия frozenset

Generator()

class typing.Generator(Iterator[T_co], Generic[T_co, T_contra, V_co])
# Generator[YieldType, SendType, ReturnType]

def func() -> Generator[int, float, str]:
    sent = yield 0
    while send > 0:
        sent = yield round(sent)
    return 'Done'

Generic()

class typing.Generic
T = TypeVar('T')

def func(item: Generic[T]):
    pass

Hashable()

class typing.Hashable

Generic версия collections.abc.Hashable

KeysView()

class typing.KeysView(MappingView[KT_co], AbstractSet[KT_co])

Generic версия collections.abc.KeysView

IO()

class typing.IO

ItemsView()

class typing.ItemsView(MappingView, Generic[KT_co, VT_co])

Generic версия collections.abc.ItemsView

Iterable()

class typing.Iterable

Generic версия collections.abc.Iterable

Iterator()

class typing.Iterator

Generic версия collections.abc.Iterator

Literal()

class typing.Literal

New in version 3.8.

def give_me_four(x: Literal[4]):
    pass

give_me_four(4)
# ok

give_me_four(4.0)
# error: Argument 1 to "give_me_four" has incompatible type "float"; expected "Literal[4]"

give_me_four(42)
# error: Argument 1 to "give_me_four" has incompatible type "Literal[42]"; expected "Literal[4]"

List()

class typing.List(list, MutableSequence[T])
def func(items: List[str]):
    pass

Vector = List[float]
def func(items: Vector):
    pass

Mapping()

class typing.Mapping(Sized, Collection, Generic)

Generic версия collections.abc.Mapping

overrides = Mapping[str, str]

MappingView()

class typing.MappingView(Sized, Iterable[T_col])

Generic версия collections.abc.MappingView

Match()

class typing.Match

MutableMapping()

class typing.MutableMapping(Mapping[KT, VT])

Generic версия collections.abc.MutableMapping

MutableSequence()

class typing.MutableSequence(Sequence[T])

Generic версия collections.abc.MutableSequence

MutableSet()

class typing.MutableSet(AbstractSet)

Generic версия collections.abc.MutableSet

NamedTuple()

class typing.NamedTuple

Типизированная версия collections.namedtuple

class Employee(NamedTuple):
    name: str
    id: int

People = NamedTuple('People', [('name', str), ('id', int)])

NewType()

class typing.NewType
UserId = NewType('UserId', int)
some_id = UserId(12345)

NoReturn()

class typing.NoReturn
def func() -> NoReturn:
    raise RuntimeError('no way')

Optional()

class typing.Optional

OrderedDict()

class typing.OrderedDict(collections.OrderedDict, MutableMapping[KT, VT])

Generic версия collections.OrderedDict

Pattern()

class typing.Pattern

Protocol()

class typing.Protocol

New in version 3.8.

Протокол

from abc import abstractmethod
from typing import Protocol, Iterable


class SupportsRoar(Protocol):
    @abstractmethod
    def roar(self) -> None:
        raise NotImplementedError

class Lion(SupportsRoar):
    def roar(self) -> None:
        print("roar")

class Cat:
    def meow(self) -> None:
        print("meow")

def roar_all(bigcats: Iterable[SupportsRoar]) -> None:
    for t in bigcats:
        t.roar()

roar_all([Lion(), Tiger()])  # ok

roar_all([Cat()])
# error: List item 0 has incompatible type "Cat"; expected "SupportsRoar"

Reversible()

class typing.Reversible

Generic версия collections.abc.Reversible

Sequence()

class typing.Sequence(Reversible[T], Collection[T])

Generic версия collections.abc.Sequence

Address = Tuple[str, int]
ConnectionOptions = Dict[str, str]
Server = Tuple[Address, ConnectionOptions]

def func(servers: Sequence[Server]):
    pass

Set()

class typing.Set(set, MutableSet[T])

Generic версия set

Sized()

class typing.Sized

Алиас collections.abc.Sized

SupportsAbs()

class typing.SupportsAbs

ABC класс с абстрактынм методом __abs__.

SupportsBytes()

class typing.SupportsBytes

ABC класс с абстрактынм методом __bytes__.

SupportsComplex()

class typing.SupportsComplex

ABC класс с абстрактынм методом __complex__.

SupportsFloat()

class typing.SupportsFloat

ABC класс с абстрактынм методом __float__.

SupportsIndex()

class typing.SupportsIndex

New in version 3.8.

ABC класс с абстрактынм методом __index__.

SupportsInt()

class typing.SupportsInt

ABC класс с абстрактынм методом __int__.

SupportsRound()

class typing.SupportsRound

ABC класс с абстрактынм методом __round__.

Text()

class typing.Text

Алиас str

TextIO()

class typing.TextIO

Type()

class typing.Type(Generic[])

New in version 3.5.2.

class User:
    pass

def func(user: Type[User]):
    pass

TypeVar()

class typing.TypeVar

# любой тип T = TypeVar(‘T’)

# стркоа или байты A = TypeVar(‘A’, str, bytes)

def func(l: Sequence[T]) - > T:

pass

TypedDict()

class typing.TypedDict

New in version 3.8.

class Book(TypedDict):
    title: str
    author: str

Book = TypedDict(
    'Book',
    {
        'title': str,
        'author': str,
    }
)

book: Book = {
    'title': 'title',
    'author': 'author'
}

book: Book = {
    'title': 'title',
    'artist': 'artist'
}
# error: Extra key 'artist' for TypedDict "Book"

book: Book = {
    'title': 'Fareneheit 481'
}
# error: Key 'author' missing for TypedDict "Book"
# total=False - не обязательное заполнение всех полей
class Book(TypedDict, total=False):
    title: str
    artist: str

book: Book = {
    'title': 'Fareneheit 481'
}
# ok

Tuple()

class typing.Tuple
def func(item: Tuple[str, int]):
    pass

Union()

class typing.Union

… code-block:: py

Union[Union[int, str], float] == Union[str, int, float] Union[int] == int Union[int, str, float] == Union[int, str]

ValuesView()

class typing.ValuesView(MappingView[VT_co])

Generic версия collections.abc.ValuesView