typing¶
New in version 3.5.
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)
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
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
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
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
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"
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'
KeysView()¶
- class
typing.
KeysView
(MappingView[KT_co], AbstractSet[KT_co])¶ Generic версия
collections.abc.KeysView
ItemsView()¶
- class
typing.
ItemsView
(MappingView, Generic[KT_co, VT_co])¶ Generic версия
collections.abc.ItemsView
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
MutableMapping()¶
- class
typing.
MutableMapping
(Mapping[KT, VT])¶ Generic версия
collections.abc.MutableMapping
MutableSequence()¶
- class
typing.
MutableSequence
(Sequence[T])¶ Generic версия
collections.abc.MutableSequence
NamedTuple()¶
- class
typing.
NamedTuple
¶ Типизированная версия
collections.namedtuple
class Employee(NamedTuple): name: str id: int People = NamedTuple('People', [('name', str), ('id', int)])
OrderedDict()¶
- class
typing.
OrderedDict
(collections.OrderedDict, MutableMapping[KT, VT])¶ Generic версия
collections.OrderedDict
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"
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
SupportsIndex()¶
- class
typing.
SupportsIndex
¶ New in version 3.8.
ABC класс с абстрактынм методом __index__.
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