New in version 3.5.
typing.
TYPE_CHECKING
Булево, в runtime’е будет False
typing.
cast
()typing.
final
()New in version 3.8.
# от этого класса нельзя наследоваться
@final
class SomeClass:
pass
# нельзя переопределять метод
class SomeClass:
@final
def foo(self):
pass
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)
typing.
get_origin
(tp)typing.
get_type_hints
(obj, globals, locals)typing.
no_type_check
()typing.
no_type_check_decorator
()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
typing.
runtime_checkable
()New in version 3.8: @runtime_checkable
class Closable(Protocol):
def close(self):
pass
assert isinstance(open(path), Closable)
typing.
type_check_only
()@type_check_only
class Response:
pass
def fetch() -> Response:
pass
typing.
AbstractSet
(Sized, Collection)Generic версия collections.abc.Set
typing.
Any
def func(item: Any):
pass
typing.
AnyStr
AnyStr == TypeVar('AnyStr', str, bytes)
typing.
AsyncContextManager
(Generic[T_co])Generic версия collections.AbstractAsyncContextManager
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
typing.
AsyncIterable
(Generic[_coT])New in version 3.5.2.
Generic версия collections.abc.AsyncIterable
typing.
AsyncIterator
(AsyncIterable[T])Generic версия collections.abc.AsyncIterator
typing.
Awaitable
(Generic[T_co])New in version 3.5.2.
Generic версия collections.abc.Awaitable
typing.
BinaryIO
typing.
ByteString
(Sequence[T])Generic версия collections.abc.ByteString
typing.
Callable
([ArgTypes, ..., ]ReturnValue)def func(get_next_item: Callable[[], str]):
pass
typing.
ChainMap
(collections.ChainMap, MutableMapping[KT, VT])Generic версия collections.ChainMap
typing.
ClassVar
class Starship:
stats: ClassVar[Dict[str, int]] = {}
ship = Starship()
ship.stats = {}
# Error, setting class variable on instance
Starship.stats = {}
# ok
typing.
Collection
(Sized, Iterable, Container)New in version 3.6.
Generic версия collections.abc.Collection
typing.
Container
Generic версия collections.abc.Container
typing.
ContextManager
(Generic[T_co])Generic версия collections.AbstractContextManager
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
typing.
Counter
(collections.Counter, Dict[T, int])Generic версия collections.Counter
typing.
DefaultDict
(collections.defaultdict, MutableMapping[KT, VT])Generic версия collections.defaultdict
typing.
Deque
(deque, MutableSequence[T])New in version 3.5.4.
Generic версия collections.deque
typing.
Dict
(dict, MutableMapping[KT, VT])def func(item: Dict[str, str]):
pass
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"
typing.
ForwardRef
typing.
FrozenSet
(frozenset, AbstractSet[T_co])Generic версия frozenset
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'
typing.
Generic
T = TypeVar('T')
def func(item: Generic[T]):
pass
typing.
Hashable
Generic версия collections.abc.Hashable
typing.
KeysView
(MappingView[KT_co], AbstractSet[KT_co])Generic версия collections.abc.KeysView
typing.
IO
typing.
ItemsView
(MappingView, Generic[KT_co, VT_co])Generic версия collections.abc.ItemsView
typing.
Iterable
Generic версия collections.abc.Iterable
typing.
Iterator
Generic версия collections.abc.Iterator
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]"
typing.
List
(list, MutableSequence[T])def func(items: List[str]):
pass
Vector = List[float]
def func(items: Vector):
pass
typing.
Mapping
(Sized, Collection, Generic)Generic версия collections.abc.Mapping
overrides = Mapping[str, str]
typing.
MappingView
(Sized, Iterable[T_col])Generic версия collections.abc.MappingView
typing.
Match
typing.
MutableMapping
(Mapping[KT, VT])Generic версия collections.abc.MutableMapping
typing.
MutableSequence
(Sequence[T])Generic версия collections.abc.MutableSequence
typing.
MutableSet
(AbstractSet)Generic версия collections.abc.MutableSet
typing.
NamedTuple
Типизированная версия collections.namedtuple
class Employee(NamedTuple):
name: str
id: int
People = NamedTuple('People', [('name', str), ('id', int)])
typing.
NewType
UserId = NewType('UserId', int)
some_id = UserId(12345)
typing.
NoReturn
def func() -> NoReturn:
raise RuntimeError('no way')
typing.
Optional
typing.
OrderedDict
(collections.OrderedDict, MutableMapping[KT, VT])Generic версия collections.OrderedDict
typing.
Pattern
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"
typing.
Reversible
Generic версия collections.abc.Reversible
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
typing.
Set
(set, MutableSet[T])Generic версия set
typing.
Sized
Алиас collections.abc.Sized
typing.
SupportsAbs
ABC класс с абстрактынм методом __abs__.
typing.
SupportsBytes
ABC класс с абстрактынм методом __bytes__.
typing.
SupportsComplex
ABC класс с абстрактынм методом __complex__.
typing.
SupportsFloat
ABC класс с абстрактынм методом __float__.
typing.
SupportsIndex
New in version 3.8.
ABC класс с абстрактынм методом __index__.
typing.
SupportsInt
ABC класс с абстрактынм методом __int__.
typing.
SupportsRound
ABC класс с абстрактынм методом __round__.
typing.
Text
Алиас str
typing.
TextIO
typing.
Type
(Generic[])New in version 3.5.2.
class User:
pass
def func(user: Type[User]):
pass
typing.
TypeVar
# любой тип T = TypeVar(‘T’)
# стркоа или байты A = TypeVar(‘A’, str, bytes)
pass
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
typing.
Tuple
def func(item: Tuple[str, int]):
pass
typing.
Union
… code-block:: py
Union[Union[int, str], float] == Union[str, int, float] Union[int] == int Union[int, str, float] == Union[int, str]
typing.
ValuesView
(MappingView[VT_co])Generic версия collections.abc.ValuesView