Как определить тип аргумента в функции python
Перейти к содержимому

Как определить тип аргумента в функции python

  • автор:

Модуль typing и аннотация типов в Python

Модуль typing, который добавлен в Python 3.5, предоставляет способ указания типов, что позволяет программам проверки статических типов и линтерам точно предсказывать ошибки.

Иногда разработчикам бывает сложно выяснить, что именно происходит в коде из-за того, что Python должен определять тип объектов во время выполнения.

Внешние средства проверки типов, например PyCharm IDE, не дают нужных результатов. Он правильно прогнозирует ошибки всего в 50% случаев, согласно доступной статистике.

Python решает эту проблему, вводя так называемуые подсказки типов (также известную как аннотация типов) – так он помогает внешним средствам проверки типов находить ошибки. Так разработчики могут указать тип используемого объекта (объектов) во время самой компиляции и убедиться, что средства проверки типов работают правильно.

Код Python становится читабельным и понятным для других пользователей!

Примечание: Фактически проверка типов во время компиляции не выполняется. Ошибки компиляции не будет, если фактический возвращенный объект не был того же типа, что и подсказка. Поэтому для выявления любых ошибок типов мы используем внешние средства проверки типов, к примеру mypy.

Требования

Для эффективного использования модуля typing и тестирования статического соответствия типов рекомендуется использовать программную проверку типов – линтер. Mypy одна из наиболее широко используемых программ для проверки, поэтому мы советуем вам установить ее прямо сейчас.

Для этого используйте команду:

pip3 install mypy

Вы можете запустить mypy для любого файла Python, чтобы проверить соответствие типов. Это делается так:

После устранения ошибок попробуйте запустить программу в обычном режиме, используя:

Теперь давайте попробуем использовать некоторые функции модуля.

Подсказки типа, или типовая аннотация

Типовая аннотация в функциях

Мы можем аннотировать функцию, чтобы указать ее возвращаемый тип и типы ее параметров.

Этот код сообщает средству проверки типов (у нас это mypy), что у нас есть функция print_list(), которая принимает list в качестве аргумента и возвращает None.

Сначала давайте запустим это в mypy:

Поскольку строка № 5 имеет аргумент int, а не list, мы получаем ошибку.

Аннотация типов в переменных

Начиная с Python 3.6, мы также можем аннотировать типы переменных. Но если вы хотите, чтобы тип переменной изменился до возврата из функции, то делать это не обязательно.

Это рекомендуемый способ использования mypy: сначала предоставляем аннотации типов, а уже потом применяем средство проверки типов.

Псевдонимы типов

Модуль typing предоставляет нам псевдонимы типов. Чтобы определить такой псевдоним, присвойте его типу.

В результате получится:

В фрагменте выше Vector — это псевдоним, обозначающий список значений с плавающей запятой. Приведенная выше программа может вывести подсказку для псевдонима.

Полный список допустимых псевдонимов приведен здесь .

Теперь давайте рассмотрим еще один пример, который проверяет каждую пару “ключ:значение” на соответствие формату name:email.

Вывод mypy будет выглядеть так:

Поскольку параметр name в нашем втором словаре является целым числом (123), то здесь мы получаем статическую ошибку времени компиляции в mypy. Таким образом, псевдонимы — это еще один способ обеспечить точную проверку типов из mypy.

Создание пользовательских типов данных с помощью NewType()

Для создания новых пользовательских типов мы можем использовать функцию NewType().

Средство проверки типов будет рассматривать новый тип, как если бы он был подклассом исходного. Это помогает находить логические ошибки.

Вывод mypy будет иметь следующий вид:

Тип Any

Any – это особый тип, который сообщает другим инструментам проверки типов (в нашем случае mypy), что каждый тип совместим с этим ключевым словом.

Рассмотрим нашу старую функцию print_list(), которая теперь принимает аргументы любого типа.

Теперь при запуске mypy ошибок не будет.

Все функции без возвращаемого типа значения или параметров будут по умолчанию использовать Any.

То есть, тип Any можно использовать, чтобы смешивать статически и динамически типизированный код.

Заключение

В этой статье мы разобрались с модулем typing в Python, который очень полезен в контексте проверки типов. Он позволяет внешним средствам проверки типов, таким как mypy, точно сообщать обо всех ошибках.

Это дает нам возможность писать статически типизированный код на Python, который является языком с динамической типизацией.

Введение в аннотации типов Python


Автор иллюстрации — Magdalena Tomczyk

Python — язык с динамической типизацией и позволяет нам довольно вольно оперировать переменными разных типов. Однако при написании кода мы так или иначе предполагаем переменные каких типов будут использоваться (это может быть вызвано ограничением алгоритма или бизнес логики). И для корректной работы программы нам важно как можно раньше найти ошибки, связанные с передачей данных неверного типа.

Сохраняя идею динамической утиной типизации в современных версиях Python (3.6+) поддерживает аннотации типов переменных, полей класса, аргументов и возвращаемых значений функций:

Аннотации типов просто считываются интерпретатором Python и никак более не обрабатываются, но доступны для использования из стороннего кода и в первую очередь рассчитаны для использования статическими анализаторами.

Меня зовут Тихонов Андрей и я занимаюсь backend-разработкой в Lamoda.

В этой статье я хочу объяснить основы использования аннотаций типов и рассмотреть типичные примеры, реализуемые аннотациями из пакета typing .

Инструменты, поддерживающие аннотации

Аннотации типов поддерживаются многими IDE для Python, которые выделяют некорректный код или выдают подсказки в процессе набора текста.

Например, так это выглядит в Pycharm:

Так же аннотации типов обрабатываются и консольными линтерами.

Вот вывод pylint:

А вот для того же файла что нашел mypy:

Поведение разных анализаторов может отличаться. Например, mypy и pycharm по разному обрабатывают смену типа переменной. Далее в примерах я буду ориентироваться на вывод mypy.

В некоторых примерах код при запуске может работать без исключений, но может содержать логические ошибки из-за использования переменных не того типа. А в некоторых примерах он может даже не выполняться.

Основы

В отличие от старых версий Python, аннотации типов пишутся не в комментариях или docstring, а непосредственно в коде. С одной стороны, это ломает обратную совместимость, с другой — явно означает что это часть кода и может обрабатываться соответственно

В простейшем случае аннотация содержит непосредственно ожидаемый тип. Более сложные кейсы будут рассмотрены ниже. Если в качестве аннотации указан базовый класс, допустимо передача экземпляров его наследников в качестве значений. Однако использовать можно только те возможности, что реализованы в базовом классе.

Аннотации для переменных пишут через двоеточие после идентификатора. После этого может идти инициализация значения. Например,

Параметры функции аннотируются так же как переменные, а возвращаемое значение указывается после стрелки -> и до завершающего двоеточия. Например,

Для полей класса аннотации должны быть указаны явно при определении класса. Однако анализаторы могут выводить автоматически их на основе __init__ метода, но в этом случае они не будут доступны во время выполнения программы. Подробнее про работу с аннотациями в рантайме во второй части статьи

Кстати, при использовании dataclass типы полей необходимо указывать именно в классе. Подробнее про dataclass

Встроенные типы

Хоть вы и можете использовать стандартные типы в качестве аннотаций, много полезного сокрыто в модуле typing .

Optional

Если вы пометите переменную типом int и попытаетесь присвоить ей None , будет ошибка:

Incompatible types in assignment (expression has type «None», variable has type «int»)

Для таких случаев предусмотрена в модуле typing аннотация Optional с указанием конкретного типа. Обратите внимание, тип опциональной переменной указывается в квадратных скобках

Иногда вы не хотите ограничивать возможные типы переменной. Например, если это действительно не важно, или если вы планируете сделать обработку разных типов самостоятельно. В этом случае, можно использовать аннотацию Any . На следующий код mypy не будет ругаться:

Может возникнуть вопрос, почему не использовать object ? Однако в этом случае предполагается, что хоть передан может быть любой объект, обращаться с ним можно только как с экземпляром object .

Union

Для случаев, когда необходимо допустить использование не любых типов, а только некоторых, можно использовать аннотацию typing.Union с указанием списка типов в квадратных скобках.

Кстати, аннотация Optional[T] эквивалентна Union[T, None] , хотя такая запись и не рекомендуется.

Коллекции

Механизм аннотаций типов поддерживает механизм дженериков (Generics, подробнее во второй части статьи), которые позволяют специфицировать для контейнеров типы элементов, хранящихся в них.

Списки

Для того, чтобы указать, что переменная содержит список можно использовать тип list в качестве аннотации. Однако если хочется конкретизировать, какие элементы содержит список, он такая аннотация уже не подойдёт. Для этого есть typing.List . Аналогично тому, как мы указывали тип опциональной переменной, мы указываем тип элементов списка в квадратных скобках.

Предполагается, что список содержит неопределенное количество однотипных элементов. Но при этом нет ограничений на аннотацию элемента: можно использовать Any , Optional , List и другие. Если тип элемента не указан, предполагается, что это Any .

Кроме списка аналогичные аннотации есть для множеств: typing.Set и typing.FrozenSet .

Кортежи

Кортежи в отличие от списков часто используются для разнотипных элементов. Синтаксис похож с одним отличием: в квадратных скобках указывается тип каждого элемента кортежа по отдельности.

Если же планируется использовать кортеж аналогично списку: хранить неизвестное количество однотипных элементов, можно воспользоваться многоточием ( . ).

Аннотация Tuple без указания типов элементов работает аналогично Tuple[Any, . ]

Словари

Для словарей используется typing.Dict . Отдельно аннотируется тип ключа и тип значений:

Аналогично используются typing.DefaultDict и typing.OrderedDict

Результат выполнения функции

Для указания типа результата функции можно использовать любую аннотацию. Но есть несколько особенных случаев.

Если функция ничего не возвращает (например, как print ), её результат всегда равен None . Для аннотации так же используем None .

Корректными вариантами завершения такой функции будут: явный возврат None , возврат без указания значения и завершение без вызова return .

Если же функция никогда не возвращает управление (например, как sys.exit ), следует использовать аннотацию NoReturn :

Если это генераторная функция, то есть её тело содержит оператор yield , для возвращаемого можно воспользоватьтся аннотацией Iterable[T] , либо Generator[YT, ST, RT] :

Вместо заключения

Для многих ситуаций в модуле typing есть подходящие типы, однако я не буду рассматривать все, так как поведение аналогично рассмотренным.
Например, есть Iterator как generic-версия для collections.abc.Iterator , typing.SupportsInt для того, чтобы указать что объект поддерживает метод __int__ , или Callable для функций и объектов, поддерживающих метод __call__

Так же стандарт определяет формат аннотаций в виде комментариев и stub-файлы, которые содержат информацию только для статических анализаторов.

В следующей статье я бы хотел остановиться на механизме работы дженериков и обработке аннотаций в рантайме.

typing — Support for type hints¶

The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.

This module provides runtime support for type hints. The most fundamental support consists of the types Any , Union , Callable , TypeVar , and Generic . For a specification, please see PEP 484. For a simplified introduction to type hints, see PEP 483.

The function below takes and returns a string and is annotated as follows:

In the function greeting , the argument name is expected to be of type str and the return type str . Subtypes are accepted as arguments.

New features are frequently added to the typing module. The typing_extensions package provides backports of these new features to older versions of Python.

For a summary of deprecated features and a deprecation timeline, please see Deprecation Timeline of Major Features.

For a quick overview of type hints, refer to this cheat sheet.

The “Type System Reference” section of https://mypy.readthedocs.io/ – since the Python typing system is standardised via PEPs, this reference should broadly apply to most Python type checkers, although some parts may still be specific to mypy.

The documentation at https://typing.readthedocs.io/ serves as useful reference for type system features, useful typing related tools and typing best practices.

Relevant PEPs¶

Since the initial introduction of type hints in PEP 484 and PEP 483, a number of PEPs have modified and enhanced Python’s framework for type annotations:

Introducing syntax for annotating variables outside of function definitions, and ClassVar

Introducing types.GenericAlias and the ability to use standard library classes as generic types

Introducing Final and the @final decorator

Introducing types.UnionType and the ability to use the binary-or operator | to signify a union of types

Type aliases¶

A type alias is defined by assigning the type to the alias. In this example, Vector and list[float] will be treated as interchangeable synonyms:

Type aliases are useful for simplifying complex type signatures. For example:

Note that None as a type hint is a special case and is replaced by type(None) .

Type aliases may be marked with TypeAlias to make it explicit that the statement is a type alias declaration, not a normal variable assignment:

NewType¶

Use the NewType helper to create distinct types:

The static type checker will treat the new type as if it were a subclass of the original type. This is useful in helping catch logical errors:

You may still perform all int operations on a variable of type UserId , but the result will always be of type int . This lets you pass in a UserId wherever an int might be expected, but will prevent you from accidentally creating a UserId in an invalid way:

Note that these checks are enforced only by the static type checker. At runtime, the statement Derived = NewType(‘Derived’, Base) will make Derived a callable that immediately returns whatever parameter you pass it. That means the expression Derived(some_value) does not create a new class or introduce much overhead beyond that of a regular function call.

More precisely, the expression some_value is Derived(some_value) is always true at runtime.

It is invalid to create a subtype of Derived :

However, it is possible to create a NewType based on a ‘derived’ NewType :

and typechecking for ProUserId will work as expected.

Recall that the use of a type alias declares two types to be equivalent to one another. Doing Alias = Original will make the static type checker treat Alias as being exactly equivalent to Original in all cases. This is useful when you want to simplify complex type signatures.

In contrast, NewType declares one type to be a subtype of another. Doing Derived = NewType(‘Derived’, Original) will make the static type checker treat Derived as a subclass of Original , which means a value of type Original cannot be used in places where a value of type Derived is expected. This is useful when you want to prevent logic errors with minimal runtime cost.

New in version 3.5.2.

Changed in version 3.10: NewType is now a class rather than a function. As a result, there is some additional runtime cost when calling NewType over a regular function.

Changed in version 3.11: The performance of calling NewType has been restored to its level in Python 3.9.

Callable¶

Frameworks expecting callback functions of specific signatures might be type hinted using Callable[[Arg1Type, Arg2Type], ReturnType] .

It is possible to declare the return type of a callable without specifying the call signature by substituting a literal ellipsis for the list of arguments in the type hint: Callable[. ReturnType] .

Callables which take other callables as arguments may indicate that their parameter types are dependent on each other using ParamSpec . Additionally, if that callable adds or removes arguments from other callables, the Concatenate operator may be used. They take the form Callable[ParamSpecVariable, ReturnType] and Callable[Concatenate[Arg1Type, Arg2Type, . ParamSpecVariable], ReturnType] respectively.

Changed in version 3.10: Callable now supports ParamSpec and Concatenate . See PEP 612 for more details.

The documentation for ParamSpec and Concatenate provides examples of usage in Callable .

Generics¶

Since type information about objects kept in containers cannot be statically inferred in a generic way, many container classes in the standard library support subscription to denote the expected types of container elements.

Generics can be parameterized by using a factory available in typing called TypeVar .

User-defined generic types¶

A user-defined class can be defined as a generic class.

Generic[T] as a base class defines that the class LoggedVar takes a single type parameter T . This also makes T valid as a type within the class body.

The Generic base class defines __class_getitem__() so that LoggedVar[T] is valid as a type:

A generic type can have any number of type variables. All varieties of TypeVar are permissible as parameters for a generic type:

Each type variable argument to Generic must be distinct. This is thus invalid:

You can use multiple inheritance with Generic :

When inheriting from generic classes, some type parameters could be fixed:

In this case MyDict has a single parameter, T .

Using a generic class without specifying type parameters assumes Any for each position. In the following example, MyIterable is not generic but implicitly inherits from Iterable[Any] :

User-defined generic type aliases are also supported. Examples:

Changed in version 3.7: Generic no longer has a custom metaclass.

User-defined generics for parameter expressions are also supported via parameter specification variables in the form Generic[P] . The behavior is consistent with type variables’ described above as parameter specification variables are treated by the typing module as a specialized type variable. The one exception to this is that a list of types can be used to substitute a ParamSpec :

Furthermore, a generic with only one parameter specification variable will accept parameter lists in the forms X[[Type1, Type2, . ]] and also X[Type1, Type2, . ] for aesthetic reasons. Internally, the latter is converted to the former, so the following are equivalent:

Note that generics with ParamSpec may not have correct __parameters__ after substitution in some cases because they are intended primarily for static type checking.

Changed in version 3.10: Generic can now be parameterized over parameter expressions. See ParamSpec and PEP 612 for more details.

A user-defined generic class can have ABCs as base classes without a metaclass conflict. Generic metaclasses are not supported. The outcome of parameterizing generics is cached, and most types in the typing module are hashable and comparable for equality.

The Any type¶

A special kind of type is Any . A static type checker will treat every type as being compatible with Any and Any as being compatible with every type.

This means that it is possible to perform any operation or method call on a value of type Any and assign it to any variable:

Notice that no type checking is performed when assigning a value of type Any to a more precise type. For example, the static type checker did not report an error when assigning a to s even though s was declared to be of type str and receives an int value at runtime!

Furthermore, all functions without a return type or parameter types will implicitly default to using Any :

This behavior allows Any to be used as an escape hatch when you need to mix dynamically and statically typed code.

Contrast the behavior of Any with the behavior of object . Similar to Any , every type is a subtype of object . However, unlike Any , the reverse is not true: object is not a subtype of every other type.

That means when the type of a value is object , a type checker will reject almost all operations on it, and assigning it to a variable (or using it as a return value) of a more specialized type is a type error. For example:

Use object to indicate that a value could be any type in a typesafe manner. Use Any to indicate that a value is dynamically typed.

Nominal vs structural subtyping¶

Initially PEP 484 defined the Python static type system as using nominal subtyping. This means that a class A is allowed where a class B is expected if and only if A is a subclass of B .

This requirement previously also applied to abstract base classes, such as Iterable . The problem with this approach is that a class had to be explicitly marked to support them, which is unpythonic and unlike what one would normally do in idiomatic dynamically typed Python code. For example, this conforms to PEP 484:

PEP 544 allows to solve this problem by allowing users to write the above code without explicit base classes in the class definition, allowing Bucket to be implicitly considered a subtype of both Sized and Iterable[int] by static type checkers. This is known as structural subtyping (or static duck-typing):

Moreover, by subclassing a special class Protocol , a user can define new custom protocols to fully enjoy structural subtyping (see examples below).

Module contents¶

The module defines the following classes, functions and decorators.

This module defines several deprecated aliases to pre-existing standard library classes. These were originally included in the typing module in order to support parameterizing these generic classes using [] . However, the aliases became redundant in Python 3.9 when the corresponding pre-existing classes were enhanced to support [] .

The redundant types are deprecated as of Python 3.9 but no deprecation warnings are issued by the interpreter. It is expected that type checkers will flag the deprecated types when the checked program targets Python 3.9 or newer.

The deprecated types will be removed from the typing module no sooner than the first Python version released 5 years after the release of Python 3.9.0. See details in PEP 585Type Hinting Generics In Standard Collections.

Special typing primitives¶

Special types¶

These can be used as types in annotations and do not support [] .

Special type indicating an unconstrained type.

Every type is compatible with Any .

Any is compatible with every type.

Changed in version 3.11: Any can now be used as a base class. This can be useful for avoiding type checker errors with classes that can duck type anywhere or are highly dynamic.

AnyStr is a constrained type variable defined as AnyStr = TypeVar(‘AnyStr’, str, bytes) .

It is meant to be used for functions that may accept any kind of string without allowing different kinds of strings to mix. For example:

Special type that includes only literal strings. A string literal is compatible with LiteralString , as is another LiteralString , but an object typed as just str is not. A string created by composing LiteralString -typed objects is also acceptable as a LiteralString .

This is useful for sensitive APIs where arbitrary user-generated strings could generate problems. For example, the two cases above that generate type checker errors could be vulnerable to an SQL injection attack.

New in version 3.11.

The bottom type, a type that has no members.

This can be used to define a function that should never be called, or a function that never returns:

New in version 3.11: On older Python versions, NoReturn may be used to express the same concept. Never was added to make the intended meaning more explicit.

Special type indicating that a function never returns. For example:

NoReturn can also be used as a bottom type, a type that has no values. Starting in Python 3.11, the Never type should be used for this concept instead. Type checkers should treat the two equivalently.

New in version 3.5.4.

New in version 3.6.2.

Special type to represent the current enclosed class. For example:

This annotation is semantically equivalent to the following, albeit in a more succinct fashion:

In general if something currently follows the pattern of:

You should use Self as calls to SubclassOfFoo.return_self would have Foo as the return type and not SubclassOfFoo .

Other common use cases include:

classmethod s that are used as alternative constructors and return instances of the cls parameter.

Annotating an __enter__() method which returns self.

New in version 3.11.

Special annotation for explicitly declaring a type alias .

TypeAlias is particularly useful for annotating aliases that make use of forward references, as it can be hard for type checkers to distinguish these from normal variable assignments:

New in version 3.10.

Special forms¶

These can be used as types in annotations using [] , each having a unique syntax.

Deprecated alias for tuple .

Tuple[X, Y] is the type of a tuple of two items with the first item of type X and the second of type Y. The type of the empty tuple can be written as Tuple[()] .

Example: Tuple[T1, T2] is a tuple of two elements corresponding to type variables T1 and T2. Tuple[int, float, str] is a tuple of an int, a float and a string.

To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g. Tuple[int, . ] . A plain Tuple annotation is equivalent to tuple , Tuple[Any, . ] , or tuple[Any, . ] .

Deprecated since version 3.9: builtins.tuple now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Union type; Union[X, Y] is equivalent to X | Y and means either X or Y.

To define a union, use e.g. Union[int, str] or the shorthand int | str . Using that shorthand is recommended. Details:

The arguments must be types and there must be at least one.

Unions of unions are flattened, e.g.:

Unions of a single argument vanish, e.g.:

Redundant arguments are skipped, e.g.:

When comparing unions, the argument order is ignored, e.g.:

You cannot subclass or instantiate a Union .

You cannot write Union[X][Y] .

Changed in version 3.7: Don’t remove explicit subclasses from unions at runtime.

Changed in version 3.10: Unions can now be written as X | Y . See union type expressions .

Optional[X] is equivalent to X | None (or Union[X, None] ).

Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require the Optional qualifier on its type annotation just because it is optional. For example:

On the other hand, if an explicit value of None is allowed, the use of Optional is appropriate, whether the argument is optional or not. For example:

Changed in version 3.10: Optional can now be written as X | None . See union type expressions .

Callable[[int], str] signifies a function that takes a single parameter of type int and returns a str .

The subscription syntax must always be used with exactly two values: the argument list and the return type. The argument list must be a list of types, a ParamSpec , Concatenate , or an ellipsis. The return type must be a single type.

There is no syntax to indicate optional or keyword arguments; such function types are rarely used as callback types. Callable[. ReturnType] (literal ellipsis) can be used to type hint a callable taking any number of arguments and returning ReturnType . A plain Callable is equivalent to Callable[. Any] , and in turn to collections.abc.Callable .

Callables which take other callables as arguments may indicate that their parameter types are dependent on each other using ParamSpec . Additionally, if that callable adds or removes arguments from other callables, the Concatenate operator may be used. They take the form Callable[ParamSpecVariable, ReturnType] and Callable[Concatenate[Arg1Type, Arg2Type, . ParamSpecVariable], ReturnType] respectively.

Deprecated since version 3.9: collections.abc.Callable now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Changed in version 3.10: Callable now supports ParamSpec and Concatenate . See PEP 612 for more details.

The documentation for ParamSpec and Concatenate provide examples of usage with Callable .

Used with Callable and ParamSpec to type annotate a higher order callable which adds, removes, or transforms parameters of another callable. Usage is in the form Concatenate[Arg1Type, Arg2Type, . ParamSpecVariable] . Concatenate is currently only valid when used as the first argument to a Callable . The last parameter to Concatenate must be a ParamSpec or ellipsis ( . ).

For example, to annotate a decorator with_lock which provides a threading.Lock to the decorated function, Concatenate can be used to indicate that with_lock expects a callable which takes in a Lock as the first argument, and returns a callable with a different type signature. In this case, the ParamSpec indicates that the returned callable’s parameter types are dependent on the parameter types of the callable being passed in:

New in version 3.10.

PEP 612 – Parameter Specification Variables (the PEP which introduced ParamSpec and Concatenate ).

Deprecated alias to type .

A variable annotated with C may accept a value of type C . In contrast, a variable annotated with type[C] or Type[C] may accept values that are classes themselves – specifically, it will accept the class object of C . For example:

Note that Type[C] is covariant:

The fact that Type[C] is covariant implies that all subclasses of C should implement the same constructor signature and class method signatures as C . The type checker should flag violations of this, but should also allow constructor calls in subclasses that match the constructor calls in the indicated base class. How the type checker is required to handle this particular case may change in future revisions of PEP 484.

The only legal parameters for Type are classes, Any , type variables , and unions of any of these types. For example:

Type[Any] is equivalent to Type which in turn is equivalent to type , which is the root of Python’s metaclass hierarchy.

New in version 3.5.2.

Deprecated since version 3.9: builtins.type now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

A type that can be used to indicate to type checkers that the corresponding variable or function parameter has a value equivalent to the provided literal (or one of several literals). For example:

Literal[. ] cannot be subclassed. At runtime, an arbitrary value is allowed as type argument to Literal[. ] , but type checkers may impose restrictions. See PEP 586 for more details about literal types.

New in version 3.8.

Changed in version 3.9.1: Literal now de-duplicates parameters. Equality comparisons of Literal objects are no longer order dependent. Literal objects will now raise a TypeError exception during equality comparisons if one of their parameters are not hashable .

Special type construct to mark class variables.

As introduced in PEP 526, a variable annotation wrapped in ClassVar indicates that a given attribute is intended to be used as a class variable and should not be set on instances of that class. Usage:

ClassVar accepts only types and cannot be further subscribed.

ClassVar is not a class itself, and should not be used with isinstance() or issubclass() . ClassVar does not change Python runtime behavior, but it can be used by third-party type checkers. For example, a type checker might flag the following code as an error:

New in version 3.5.3.

A special typing construct to indicate to type checkers that a name cannot be re-assigned or overridden in a subclass. For example:

There is no runtime checking of these properties. See PEP 591 for more details.

New in version 3.8.

Special typing constructs that mark individual keys of a TypedDict as either required or non-required respectively.

New in version 3.11.

Special typing form to add context-specific metadata to an annotation.

Add metadata x to a given type T by using the annotation Annotated[T, x] . Metadata added using Annotated can be used by static analysis tools or at runtime. At runtime, the metadata is stored in a __metadata__ attribute.

If a library or tool encounters an annotation Annotated[T, x] and has no special logic for the metadata, it should ignore the metadata and simply treat the annotation as T . As such, Annotated can be useful for code that wants to use annotations for purposes outside Python’s static typing system.

Using Annotated[T, x] as an annotation still allows for static typechecking of T , as type checkers will simply ignore the metadata x . In this way, Annotated differs from the @no_type_check decorator, which can also be used for adding annotations outside the scope of the typing system, but completely disables typechecking for a function or class.

The responsibility of how to interpret the metadata lies with the the tool or library encountering an Annotated annotation. A tool or library encountering an Annotated type can scan through the metadata elements to determine if they are of interest (e.g., using isinstance() ).

Here is an example of how you might use Annotated to add metadata to type annotations if you were doing range analysis:

Details of the syntax:

The first argument to Annotated must be a valid type

Multiple metadata elements can be supplied ( Annotated supports variadic arguments):

It is up to the tool consuming the annotations to decide whether the client is allowed to add multiple metadata elements to one annotation and how to merge those annotations.

Annotated must be subscripted with at least two arguments ( Annotated[int] is not valid)

The order of the metadata elements is preserved and matters for equality checks:

Nested Annotated types are flattened. The order of the metadata elements starts with the innermost annotation:

Duplicated metadata elements are not removed:

Annotated can be used with nested and generic aliases:

Annotated cannot be used with an unpacked TypeVarTuple :

This would be equivalent to:

where T1 , T2 , etc. are TypeVars . This would be invalid: only one type should be passed to Annotated.

By default, get_type_hints() strips the metadata from annotations. Pass include_extras=True to have the metadata preserved:

At runtime, the metadata associated with an Annotated type can be retrieved via the __metadata__ attribute:

PEP 593 — Flexible function and variable annotations

The PEP introducing Annotated to the standard library.

New in version 3.9.

Special typing form used to annotate the return type of a user-defined type guard function. TypeGuard only accepts a single type argument. At runtime, functions marked this way should return a boolean.

TypeGuard aims to benefit type narrowing – a technique used by static type checkers to determine a more precise type of an expression within a program’s code flow. Usually type narrowing is done by analyzing conditional code flow and applying the narrowing to a block of code. The conditional expression here is sometimes referred to as a “type guard”:

Sometimes it would be convenient to use a user-defined boolean function as a type guard. Such a function should use TypeGuard[. ] as its return type to alert static type checkers to this intention.

Using -> TypeGuard tells the static type checker that for a given function:

The return value is a boolean.

If the return value is True , the type of its argument is the type inside TypeGuard .

If is_str_list is a class or instance method, then the type in TypeGuard maps to the type of the second parameter after cls or self .

In short, the form def foo(arg: TypeA) -> TypeGuard[TypeB]: . , means that if foo(arg) returns True , then arg narrows from TypeA to TypeB .

TypeB need not be a narrower form of TypeA – it can even be a wider form. The main reason is to allow for things like narrowing list[object] to list[str] even though the latter is not a subtype of the former, since list is invariant. The responsibility of writing type-safe type guards is left to the user.

TypeGuard also works with type variables. See PEP 647 for more details.

New in version 3.10.

A typing operator that conceptually marks an object as having been unpacked. For example, using the unpack operator * on a type variable tuple is equivalent to using Unpack to mark the type variable tuple as having been unpacked:

In fact, Unpack can be used interchangeably with * in the context of typing.TypeVarTuple and builtins.tuple types. You might see Unpack being used explicitly in older versions of Python, where * couldn’t be used in certain places:

New in version 3.11.

Building generic types¶

The following objects are not used directly in annotations. Instead, they are building blocks for creating generic types.

class typing. Generic ¶

Abstract base class for generic types.

A generic type is typically declared by inheriting from an instantiation of this class with one or more type variables. For example, a generic mapping type might be defined as:

This class can then be used as follows:

Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function and type alias definitions. See Generic for more information on generic types. Generic functions work as follows:

Note that type variables can be bound, constrained, or neither, but cannot be both bound and constrained.

Created type variables may be explicitly marked covariant or contravariant by passing covariant=True or contravariant=True . By default, type variables are invariant. See PEP 484 and PEP 695 for more details.

Bound type variables and constrained type variables have different semantics in several important ways. Using a bound type variable means that the TypeVar will be solved using the most specific type possible:

Type variables can be bound to concrete types, abstract types (ABCs or protocols), and even unions of types:

Using a constrained type variable, however, means that the TypeVar can only ever be solved as being exactly one of the constraints given:

At runtime, isinstance(x, T) will raise TypeError .

The name of the type variable.

Whether the type var has been marked as covariant.

Whether the type var has been marked as contravariant.

The bound of the type variable, if any.

A tuple containing the constraints of the type variable, if any.

class typing. TypeVarTuple ( name ) ¶

Type variable tuple. A specialized form of type variable that enables variadic generics.

A normal type variable enables parameterization with a single type. A type variable tuple, in contrast, allows parameterization with an arbitrary number of types by acting like an arbitrary number of type variables wrapped in a tuple. For example:

Note the use of the unpacking operator * in tuple[T, *Ts] . Conceptually, you can think of Ts as a tuple of type variables (T1, T2, . ) . tuple[T, *Ts] would then become tuple[T, *(T1, T2, . )] , which is equivalent to tuple[T, T1, T2, . ] . (Note that in older versions of Python, you might see this written using Unpack instead, as Unpack[Ts] .)

Type variable tuples must always be unpacked. This helps distinguish type variable tuples from normal type variables:

Type variable tuples can be used in the same contexts as normal type variables. For example, in class definitions, arguments, and return types:

Type variable tuples can be happily combined with normal type variables:

However, note that at most one type variable tuple may appear in a single list of type arguments or type parameters:

Finally, an unpacked type variable tuple can be used as the type annotation of *args :

In contrast to non-unpacked annotations of *args — e.g. *args: int , which would specify that all arguments are int — *args: *Ts enables reference to the types of the individual arguments in *args . Here, this allows us to ensure the types of the *args passed to call_soon match the types of the (positional) arguments of callback .

See PEP 646 for more details on type variable tuples.

The name of the type variable tuple.

New in version 3.11.

Parameter specification variable. A specialized version of type variables .

Parameter specification variables exist primarily for the benefit of static type checkers. They are used to forward the parameter types of one callable to another callable – a pattern commonly found in higher order functions and decorators. They are only valid when used in Concatenate , or as the first argument to Callable , or as parameters for user-defined Generics. See Generic for more information on generic types.

For example, to add basic logging to a function, one can create a decorator add_logging to log function calls. The parameter specification variable tells the type checker that the callable passed into the decorator and the new callable returned by it have inter-dependent type parameters:

Without ParamSpec , the simplest way to annotate this previously was to use a TypeVar with bound Callable[. Any] . However this causes two problems:

The type checker can’t type check the inner function because *args and **kwargs have to be typed Any .

cast() may be required in the body of the add_logging decorator when returning the inner function, or the static type checker must be told to ignore the return inner .

Since ParamSpec captures both positional and keyword parameters, P.args and P.kwargs can be used to split a ParamSpec into its components. P.args represents the tuple of positional parameters in a given call and should only be used to annotate *args . P.kwargs represents the mapping of keyword parameters to their values in a given call, and should be only be used to annotate **kwargs . Both attributes require the annotated parameter to be in scope. At runtime, P.args and P.kwargs are instances respectively of ParamSpecArgs and ParamSpecKwargs .

The name of the parameter specification.

Parameter specification variables created with covariant=True or contravariant=True can be used to declare covariant or contravariant generic types. The bound argument is also accepted, similar to TypeVar . However the actual semantics of these keywords are yet to be decided.

New in version 3.10.

Only parameter specification variables defined in global scope can be pickled.

PEP 612 – Parameter Specification Variables (the PEP which introduced ParamSpec and Concatenate ).

Arguments and keyword arguments attributes of a ParamSpec . The P.args attribute of a ParamSpec is an instance of ParamSpecArgs , and P.kwargs is an instance of ParamSpecKwargs . They are intended for runtime introspection and have no special meaning to static type checkers.

Calling get_origin() on either of these objects will return the original ParamSpec :

New in version 3.10.

Other special directives¶

These are not used in annotations. They are building blocks for declaring types.

class typing. NamedTuple ¶

This is equivalent to:

To give a field a default value, you can assign to it in the class body:

Fields with a default value must come after any fields without a default.

The resulting class has an extra attribute __annotations__ giving a dict that maps the field names to the field types. (The field names are in the _fields attribute and the default values are in the _field_defaults attribute, both of which are part of the namedtuple() API.)

NamedTuple subclasses can also have docstrings and methods:

NamedTuple subclasses can be generic:

Changed in version 3.6: Added support for PEP 526 variable annotation syntax.

Changed in version 3.6.1: Added support for default values, methods, and docstrings.

Changed in version 3.8: The _field_types and __annotations__ attributes are now regular dictionaries instead of instances of OrderedDict .

Changed in version 3.9: Removed the _field_types attribute in favor of the more standard __annotations__ attribute which has the same information.

Changed in version 3.11: Added support for generic namedtuples.

A helper class to indicate a distinct type to a typechecker, see NewType . At runtime it returns an object that returns its argument when called. Usage:

The module in which the new type is defined.

The name of the new type.

The type that the new type is based on.

New in version 3.5.2.

Changed in version 3.10: NewType is now a class rather than a function.

Base class for protocol classes. Protocol classes are defined like this:

Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing), for example:

See PEP 544 for more details. Protocol classes decorated with runtime_checkable() (described later) act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures.

Protocol classes can be generic, for example:

New in version 3.8.

Mark a protocol class as a runtime protocol.

Such a protocol can be used with isinstance() and issubclass() . This raises TypeError when applied to a non-protocol class. This allows a simple-minded structural check, very similar to “one trick ponies” in collections.abc such as Iterable . For example:

runtime_checkable() will check only the presence of the required methods or attributes, not their type signatures or types. For example, ssl.SSLObject is a class, therefore it passes an issubclass() check against Callable . However, the ssl.SSLObject.__init__ method exists only to raise a TypeError with a more informative message, therefore making it impossible to call (instantiate) ssl.SSLObject .

An isinstance() check against a runtime-checkable protocol can be surprisingly slow compared to an isinstance() check against a non-protocol class. Consider using alternative idioms such as hasattr() calls for structural checks in performance-sensitive code.

New in version 3.8.

Special construct to add type hints to a dictionary. At runtime it is a plain dict .

TypedDict declares a dictionary type that expects all of its instances to have a certain set of keys, where each key is associated with a value of a consistent type. This expectation is not checked at runtime but is only enforced by type checkers. Usage:

To allow using this feature with older versions of Python that do not support PEP 526, TypedDict supports two additional equivalent syntactic forms:

Using a literal dict as the second argument:

Using keyword arguments:

Deprecated since version 3.11, will be removed in version 3.13: The keyword-argument syntax is deprecated in 3.11 and will be removed in 3.13. It may also be unsupported by static type checkers.

The functional syntax should also be used when any of the keys are not valid identifiers , for example because they are keywords or contain hyphens. Example:

By default, all keys must be present in a TypedDict . It is possible to mark individual keys as non-required using NotRequired :

This means that a Point2D TypedDict can have the label key omitted.

It is also possible to mark all keys as non-required by default by specifying a totality of False :

This means that a Point2D TypedDict can have any of the keys omitted. A type checker is only expected to support a literal False or True as the value of the total argument. True is the default, and makes all items defined in the class body required.

Individual keys of a total=False TypedDict can be marked as required using Required :

It is possible for a TypedDict type to inherit from one or more other TypedDict types using the class-based syntax. Usage:

Point3D has three items: x , y and z . It is equivalent to this definition:

A TypedDict cannot inherit from a non- TypedDict class, except for Generic . For example:

A TypedDict can be generic:

T = TypeVar(“T”)

class Group(TypedDict, Generic[T]):

key: T group: list[T]

A TypedDict can be introspected via annotations dicts (see Annotations Best Practices for more information on annotations best practices), __total__ , __required_keys__ , and __optional_keys__ .

Point2D.__total__ gives the value of the total argument. Example:

New in version 3.9.

Point2D.__required_keys__ and Point2D.__optional_keys__ return frozenset objects containing required and non-required keys, respectively.

Keys marked with Required will always appear in __required_keys__ and keys marked with NotRequired will always appear in __optional_keys__ .

For backwards compatibility with Python 3.10 and below, it is also possible to use inheritance to declare both required and non-required keys in the same TypedDict . This is done by declaring a TypedDict with one value for the total argument and then inheriting from it in another TypedDict with a different value for total :

New in version 3.9.

See PEP 589 for more examples and detailed rules of using TypedDict .

New in version 3.8.

Changed in version 3.11: Added support for marking individual keys as Required or NotRequired . See PEP 655.

Changed in version 3.11: Added support for generic TypedDict s.

Generic concrete collections¶

Corresponding to built-in types¶

Deprecated alias to dict .

Note that to annotate arguments, it is preferred to use an abstract collection type such as Mapping rather than to use dict or typing.Dict .

This type can be used as follows:

Deprecated since version 3.9: builtins.dict now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to list .

Note that to annotate arguments, it is preferred to use an abstract collection type such as Sequence or Iterable rather than to use list or typing.List .

This type may be used as follows:

Deprecated since version 3.9: builtins.list now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated alias to builtins.set .

Note that to annotate arguments, it is preferred to use an abstract collection type such as AbstractSet rather than to use set or typing.Set .

Deprecated since version 3.9: builtins.set now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Deprecated since version 3.9: builtins.frozenset now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Tuple is a special form.

Corresponding to types in collections ¶

New in version 3.5.2.

Deprecated since version 3.9: collections.defaultdict now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

New in version 3.7.2.

Deprecated since version 3.9: collections.OrderedDict now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

New in version 3.5.4.

New in version 3.6.1.

Deprecated since version 3.9: collections.ChainMap now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

New in version 3.5.4.

New in version 3.6.1.

Deprecated since version 3.9: collections.Counter now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

New in version 3.5.4.

New in version 3.6.1.

Deprecated since version 3.9: collections.deque now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

Other concrete types¶

Generic type IO[AnyStr] and its subclasses TextIO(IO[str]) and BinaryIO(IO[bytes]) represent the types of I/O streams such as returned by open() .

Deprecated since version 3.8, will be removed in version 3.13: The typing.io namespace is deprecated and will be removed. These types should be directly imported from typing instead.

These type aliases correspond to the return types from re.compile() and re.match() . These types (and the corresponding functions) are generic in AnyStr and can be made specific by writing Pattern[str] , Pattern[bytes] , Match[str] , or Match[bytes] .

Deprecated since version 3.8, will be removed in version 3.13: The typing.re namespace is deprecated and will be removed. These types should be directly imported from typing instead.

Deprecated since version 3.9: Classes Pattern and Match from re now support [] . See PEP 585 and Generic Alias Type .

Text is an alias for str . It is provided to supply a forward compatible path for Python 2 code: in Python 2, Text is an alias for unicode .

Use Text to indicate that a value must contain a unicode string in a manner that is compatible with both Python 2 and Python 3:

New in version 3.5.2.

Deprecated since version 3.11: Python 2 is no longer supported, and most type checkers also no longer support type checking Python 2 code. Removal of the alias is not currently planned, but users are encouraged to use str instead of Text .

Abstract Base Classes¶

Corresponding to collections in collections.abc ¶

Deprecated since version 3.9: collections.abc.Set now supports subscripting ( [] ). See PEP 585 and Generic Alias Type .

This type represents the types bytes , bytearray , and memoryview of byte sequences.

26.1. typing — Support for type hints¶

The typing module has been included in the standard library on a provisional basis . New features might be added and API may change even between minor releases if deemed necessary by the core developers.

This module supports type hints as specified by PEP 484 and PEP 526. The most fundamental support consists of the types Any , Union , Tuple , Callable , TypeVar , and Generic . For full specification please see PEP 484. For a simplified introduction to type hints see PEP 483.

The function below takes and returns a string and is annotated as follows:

In the function greeting , the argument name is expected to be of type str and the return type str . Subtypes are accepted as arguments.

26.1.1. Type aliases¶

A type alias is defined by assigning the type to the alias. In this example, Vector and List[float] will be treated as interchangeable synonyms:

Type aliases are useful for simplifying complex type signatures. For example:

Note that None as a type hint is a special case and is replaced by type(None) .

26.1.2. NewType¶

Use the NewType() helper function to create distinct types:

The static type checker will treat the new type as if it were a subclass of the original type. This is useful in helping catch logical errors:

You may still perform all int operations on a variable of type UserId , but the result will always be of type int . This lets you pass in a UserId wherever an int might be expected, but will prevent you from accidentally creating a UserId in an invalid way:

Note that these checks are enforced only by the static type checker. At runtime the statement Derived = NewType(‘Derived’, Base) will make Derived a function that immediately returns whatever parameter you pass it. That means the expression Derived(some_value) does not create a new class or introduce any overhead beyond that of a regular function call.

More precisely, the expression some_value is Derived(some_value) is always true at runtime.

This also means that it is not possible to create a subtype of Derived since it is an identity function at runtime, not an actual type:

However, it is possible to create a NewType() based on a ‘derived’ NewType :

and typechecking for ProUserId will work as expected.

Recall that the use of a type alias declares two types to be equivalent to one another. Doing Alias = Original will make the static type checker treat Alias as being exactly equivalent to Original in all cases. This is useful when you want to simplify complex type signatures.

In contrast, NewType declares one type to be a subtype of another. Doing Derived = NewType(‘Derived’, Original) will make the static type checker treat Derived as a subclass of Original , which means a value of type Original cannot be used in places where a value of type Derived is expected. This is useful when you want to prevent logic errors with minimal runtime cost.

26.1.3. Callable¶

Frameworks expecting callback functions of specific signatures might be type hinted using Callable[[Arg1Type, Arg2Type], ReturnType] .

It is possible to declare the return type of a callable without specifying the call signature by substituting a literal ellipsis for the list of arguments in the type hint: Callable[. ReturnType] .

26.1.4. Generics¶

Since type information about objects kept in containers cannot be statically inferred in a generic way, abstract base classes have been extended to support subscription to denote expected types for container elements.

Generics can be parametrized by using a new factory available in typing called TypeVar .

26.1.5. User-defined generic types¶

A user-defined class can be defined as a generic class.

Generic[T] as a base class defines that the class LoggedVar takes a single type parameter T . This also makes T valid as a type within the class body.

The Generic base class uses a metaclass that defines __getitem__() so that LoggedVar[t] is valid as a type:

A generic type can have any number of type variables, and type variables may be constrained:

Each type variable argument to Generic must be distinct. This is thus invalid:

You can use multiple inheritance with Generic :

When inheriting from generic classes, some type variables could be fixed:

In this case MyDict has a single parameter, T .

Using a generic class without specifying type parameters assumes Any for each position. In the following example, MyIterable is not generic but implicitly inherits from Iterable[Any] :

User defined generic type aliases are also supported. Examples:

The metaclass used by Generic is a subclass of abc.ABCMeta . A generic class can be an ABC by including abstract methods or properties, and generic classes can also have ABCs as base classes without a metaclass conflict. Generic metaclasses are not supported. The outcome of parameterizing generics is cached, and most types in the typing module are hashable and comparable for equality.

26.1.6. The Any type¶

A special kind of type is Any . A static type checker will treat every type as being compatible with Any and Any as being compatible with every type.

This means that it is possible to perform any operation or method call on a value of type on Any and assign it to any variable:

Notice that no typechecking is performed when assigning a value of type Any to a more precise type. For example, the static type checker did not report an error when assigning a to s even though s was declared to be of type str and receives an int value at runtime!

Furthermore, all functions without a return type or parameter types will implicitly default to using Any :

This behavior allows Any to be used as an escape hatch when you need to mix dynamically and statically typed code.

Contrast the behavior of Any with the behavior of object . Similar to Any , every type is a subtype of object . However, unlike Any , the reverse is not true: object is not a subtype of every other type.

That means when the type of a value is object , a type checker will reject almost all operations on it, and assigning it to a variable (or using it as a return value) of a more specialized type is a type error. For example:

Use object to indicate that a value could be any type in a typesafe manner. Use Any to indicate that a value is dynamically typed.

26.1.7. Classes, functions, and decorators¶

The module defines the following classes, functions and decorators:

class typing. TypeVar ¶

Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function definitions. See class Generic for more information on generic types. Generic functions work as follows:

The latter example’s signature is essentially the overloading of (str, str) -> str and (bytes, bytes) -> bytes . Also note that if the arguments are instances of some subclass of str , the return type is still plain str .

At runtime, isinstance(x, T) will raise TypeError . In general, isinstance() and issubclass() should not be used with types.

Type variables may be marked covariant or contravariant by passing covariant=True or contravariant=True . See PEP 484 for more details. By default type variables are invariant. Alternatively, a type variable may specify an upper bound using bound=<type> . This means that an actual type substituted (explicitly or implicitly) for the type variable must be a subclass of the boundary type, see PEP 484.

class typing. Generic ¶

Abstract base class for generic types.

A generic type is typically declared by inheriting from an instantiation of this class with one or more type variables. For example, a generic mapping type might be defined as:

This class can then be used as follows:

A variable annotated with C may accept a value of type C . In contrast, a variable annotated with Type[C] may accept values that are classes themselves – specifically, it will accept the class object of C . For example:

Note that Type[C] is covariant:

The fact that Type[C] is covariant implies that all subclasses of C should implement the same constructor signature and class method signatures as C . The type checker should flag violations of this, but should also allow constructor calls in subclasses that match the constructor calls in the indicated base class. How the type checker is required to handle this particular case may change in future revisions of PEP 484.

The only legal parameters for Type are classes, unions of classes, and Any . For example:

Type[Any] is equivalent to Type which in turn is equivalent to type , which is the root of Python’s metaclass hierarchy.

class typing. Iterable ( Generic[T_co] ) ¶

class typing. Iterator ( Iterable[T_co] ) ¶

class typing. Reversible ( Iterable[T_co] ) ¶

class typing. SupportsInt ¶

An ABC with one abstract method __int__ .

class typing. SupportsFloat ¶

An ABC with one abstract method __float__ .

class typing. SupportsComplex ¶

An ABC with one abstract method __complex__ .

class typing. SupportsBytes ¶

An ABC with one abstract method __bytes__ .

class typing. SupportsAbs ¶

An ABC with one abstract method __abs__ that is covariant in its return type.

class typing. SupportsRound ¶

An ABC with one abstract method __round__ that is covariant in its return type.

class typing. Container ( Generic[T_co] ) ¶

class typing. Hashable ¶

class typing. Sized ¶

class typing. Collection ( Sized, Iterable[T_co], Container[T_co] ) ¶

New in version 3.6.

class typing. MutableSet ( AbstractSet[T] ) ¶

class typing. Mapping ( Sized, Collection[KT], Generic[VT_co] ) ¶

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

class typing. Sequence ( Reversible[T_co], Collection[T_co] ) ¶

class typing. MutableSequence ( Sequence[T] ) ¶

class typing. ByteString ( Sequence[int] ) ¶

This type represents the types bytes , bytearray , and memoryview .

As a shorthand for this type, bytes can be used to annotate arguments of any of the types mentioned above.

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

New in version 3.6.1.

Generic version of list . Useful for annotating return types. To annotate arguments it is preferred to use abstract collection types such as Mapping , Sequence , or AbstractSet .

This type may be used as follows:

A generic version of builtins.set .

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

class typing. MappingView ( Sized, Iterable[T_co] ) ¶

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

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

class typing. ValuesView ( MappingView[VT_co] ) ¶

class typing. Awaitable ( Generic[T_co] ) ¶

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

A generic version of collections.abc.Coroutine . The variance and order of type variables correspond to those of Generator , for example:

class typing. AsyncIterator ( AsyncIterable[T_co] ) ¶

class typing. ContextManager ( Generic[T_co] ) ¶

New in version 3.6.

A generic version of dict . The usage of this type is as follows:

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

New in version 3.6.1.

New in version 3.6.1.

A generator can be annotated by the generic type Generator[YieldType, SendType, ReturnType] . For example:

Note that unlike many other generics in the typing module, the SendType of Generator behaves contravariantly, not covariantly or invariantly.

If your generator will only yield values, set the SendType and ReturnType to None :

Alternatively, annotate your generator as having a return type of either Iterable[YieldType] or Iterator[YieldType] :

An async generator can be annotated by the generic type AsyncGenerator[YieldType, SendType] . For example:

Unlike normal generators, async generators cannot return a value, so there is no ReturnType type parameter. As with Generator , the SendType behaves contravariantly.

If your generator will only yield values, set the SendType to None :

Alternatively, annotate your generator as having a return type of either AsyncIterable[YieldType] or AsyncIterator[YieldType] :

New in version 3.5.4.

Text is an alias for str . It is provided to supply a forward compatible path for Python 2 code: in Python 2, Text is an alias for unicode .

Use Text to indicate that a value must contain a unicode string in a manner that is compatible with both Python 2 and Python 3:

Wrapper namespace for I/O stream types.

This defines the generic type IO[AnyStr] and aliases TextIO and BinaryIO for respectively IO[str] and IO[bytes] . These represent the types of I/O streams such as returned by open() .

These types are also accessible directly as typing.IO , typing.TextIO , and typing.BinaryIO .

Wrapper namespace for regular expression matching types.

This defines the type aliases Pattern and Match which correspond to the return types from re.compile() and re.match() . These types (and the corresponding functions) are generic in AnyStr and can be made specific by writing Pattern[str] , Pattern[bytes] , Match[str] , or Match[bytes] .

These types are also accessible directly as typing.Pattern and typing.Match .

class typing. NamedTuple ¶

Typed version of namedtuple.

This is equivalent to:

To give a field a default value, you can assign to it in the class body:

Fields with a default value must come after any fields without a default.

The resulting class has two extra attributes: _field_types , giving a dict mapping field names to types, and _field_defaults , a dict mapping field names to default values. (The field names are in the _fields attribute, which is part of the namedtuple API.)

NamedTuple subclasses can also have docstrings and methods:

Changed in version 3.6: Added support for PEP 526 variable annotation syntax.

Changed in version 3.6.1: Added support for default values, methods, and docstrings.

A helper function to indicate a distinct types to a typechecker, see NewType . At runtime it returns a function that returns its argument. Usage:

Cast a value to a type.

This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don’t check anything (we want this to be as fast as possible).

typing. get_type_hints ( obj [ , globals [ , locals ] ] ) ¶

Return a dictionary containing type hints for a function, method, module or class object.

This is often the same as obj.__annotations__ . In addition, forward references encoded as string literals are handled by evaluating them in globals and locals namespaces. If necessary, Optional[t] is added for function and method annotations if a default value equal to None is set. For a class C , return a dictionary constructed by merging all the __annotations__ along C.__mro__ in reverse order.

The @overload decorator allows describing functions and methods that support multiple different combinations of argument types. A series of @overload -decorated definitions must be followed by exactly one non- @overload -decorated definition (for the same function/method). The @overload -decorated definitions are for the benefit of the type checker only, since they will be overwritten by the non- @overload -decorated definition, while the latter is used at runtime but should be ignored by a type checker. At runtime, calling a @overload -decorated function directly will raise NotImplementedError . An example of overload that gives a more precise type than can be expressed using a union or a type variable:

See PEP 484 for details and comparison with other typing semantics.

Decorator to indicate that annotations are not type hints.

This works as class or function decorator . With a class, it applies recursively to all methods defined in that class (but not to methods defined in its superclasses or subclasses).

This mutates the function(s) in place.

Decorator to give another decorator the no_type_check() effect.

This wraps the decorator with something that wraps the decorated function in no_type_check() .

Special type indicating an unconstrained type.

  • Every type is compatible with Any . is compatible with every type.

Union type; Union[X, Y] means either X or Y.

To define a union, use e.g. Union[int, str] . Details:

The arguments must be types and there must be at least one.

Unions of unions are flattened, e.g.:

Unions of a single argument vanish, e.g.:

Redundant arguments are skipped, e.g.:

When comparing unions, the argument order is ignored, e.g.:

When a class and its subclass are present, the latter is skipped, e.g.:

You cannot subclass or instantiate a union.

You cannot write Union[X][Y] .

You can use Optional[X] as a shorthand for Union[X, None] .

Optional[X] is equivalent to Union[X, None] .

Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default needn’t use the Optional qualifier on its type annotation (although it is inferred if the default is None ). A mandatory argument may still have an Optional type if an explicit value of None is allowed.

Tuple type; Tuple[X, Y] is the type of a tuple of two items with the first item of type X and the second of type Y.

Example: Tuple[T1, T2] is a tuple of two elements corresponding to type variables T1 and T2. Tuple[int, float, str] is a tuple of an int, a float and a string.

To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g. Tuple[int, . ] . A plain Tuple is equivalent to Tuple[Any, . ] , and in turn to tuple .

Callable type; Callable[[int], str] is a function of (int) -> str.

The subscription syntax must always be used with exactly two values: the argument list and the return type. The argument list must be a list of types or an ellipsis; the return type must be a single type.

There is no syntax to indicate optional or keyword arguments; such function types are rarely used as callback types. Callable[. ReturnType] (literal ellipsis) can be used to type hint a callable taking any number of arguments and returning ReturnType . A plain Callable is equivalent to Callable[. Any] , and in turn to collections.abc.Callable .

Special type construct to mark class variables.

As introduced in PEP 526, a variable annotation wrapped in ClassVar indicates that a given attribute is intended to be used as a class variable and should not be set on instances of that class. Usage:

ClassVar accepts only types and cannot be further subscribed.

ClassVar is not a class itself, and should not be used with isinstance() or issubclass() . ClassVar does not change Python runtime behavior, but it can be used by third-party type checkers. For example, a type checker might flag the following code as an error:

New in version 3.5.3.

AnyStr is a type variable defined as AnyStr = TypeVar(‘AnyStr’, str, bytes) .

It is meant to be used for functions that may accept any kind of string without allowing different kinds of strings to mix. For example:

A special constant that is assumed to be True by 3rd party static type checkers. It is False at runtime. Usage:

Note that the first type annotation must be enclosed in quotes, making it a “forward reference”, to hide the expensive_mod reference from the interpreter runtime. Type annotations for local variables are not evaluated, so the second annotation does not need to be enclosed in quotes.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *