Зачем нужны аннотации типов

от admin

Аннотация типов#

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

Например, приведенная выше функция f принимает один параметр x . Вызов этой функции с аргументом x типа X завершится без ошибок, если X поддерживает сложение с 1 . Рассмотрим чуть более сложный пример.

Такая функция duck отработает корректно, только если

У x есть атрибут swim . Иначе, AttributeError;

Этот атрибут является методом (ведёт себя как функция). Иначе, TypeError;

Этот метод может быть вызван без параметров. Иначе, TypeError.

То же самое про quack : есть атрибут, он является методом и может быть вызван без параметров.

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

Таким образом при передаче объекта в функцию важен не конкретный тип объекта, а набор действий, который над этим объектом можно произвести. Такую типизацию называют утиной в честь известного “утиного теста”:

Если это выглядит как утка, плавает как утка и крякает как утка, то это, вероятно, и есть утка.

На примере с функцией duck это выражение перекладывается приблизительно так: если x имеет метод swim , имеет метод quack , и оба они могут быть вызваны без аргументов, то это, вероятно, объект допустимого для функции duck типа.

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

Таким образом проектируя функцию в python , программист задаёт не тип её параметров, а их интерфейсы. Успешное завершение функции определяется не совпадением типов, а удовлетворением интерфейсов. При этом, если в функцию по ошибке передаётся объект с иным интерфейсом, то такая ошибка будет обнаружена только на этапе исполнения программы во время попытки совершить неподдерживаемую объектом операцию.

Расширенный синтаксис сигнатуры функции#

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

Например, если мы предполагаем, что функция f всегда должна вызываться с целочисленным аргументом x , то можно объявить её так.

Такое объявление функции не значит, что её можно вызвать только с целочисленным аргументом: на этапе исполнения программы аннотация типов не используется интерпретатором python для проверки типов аргументов на соответствие типам параметров при вызове функции.

Функция f в примере выше очевидно вернет целочисленное значение, если ей передать целое число. Это тоже можно обозначить: для этого используется комбинация символов -> .

Такое объявление функции не значит, что такая функция обязательно вернет целое число. На этапе исполнения программы аннотация типов не используется интерпретатором python для проверки типа возвращаемого значения на соответствие заявленному.

Пример в ячейке ниже демонстрирует, что объявленную “целочисленную” функцию f можно вызвать и с действительным числом.

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

В рамках данного курса не удаётся поместить полноценный рассказ про аннотацию типов. Да и далеко не все научные библиотеки начали аннотацию своих типов. Самостоятельное изучение аннотации типов можно начать со странички в официальной документации.

Преимущества статической типизации#

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

Обнаружение ошибок#

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

Его компиляция средствами g++ приводит к ошибке компиляции со следующим сообщением.

Эта ошибка связана с тем, что функция f объявлена с целочисленным параметром x , а вызывается она со строковым значением.

Сравним это с аналогичным кодом на python .

Запуск этого кода приведет к возникновению следующей ошибки.

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

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

Однако если добавить подсказку типа для параметра x следующим образом.

Тогда mypy обнаружит несоответствие типа параметра x и переменной s .

Статический анализатор кода встроен В большинство современных IDE . Анимация ниже демонстрирует, что при добавлении аннотации типа параметра x , появляется индикации ошибки в строке с вызовом функции f .

Документирование кода#

Рассмотрим следующий заголовок функции bisect .

Что делает эта функция bisect , и как правильно её вызывать? Из названия функции можно догадаться, что, наверное, она реализует метод бисекции. Но существует минимум два метода бисекции: а) поиск корня функции б) двоичный поиск элемента в отсортированном массиве. На реализацию какого из них мы смотрим?

Для контраста рассмотрим возможную сигнатуру схожей функции на языке С++ .

По сигнатуре сразу можно понять, что параметр f — функция. Разумно от сюда заключить, что это реализации именно метода бисекции для поиска корня функции, а не значения в массиве. Кроме этого, из сигнатуры можно понять, что f должна принимать и возвращать double . Т.е. сигнатура функции не только подсказывает пользователю, что она делает, но и как её правильно вызывать, тем самым осуществляя документирующую функцию.

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

Автозаполнение в IDE#

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

В анимации выше среда разработки с каждой набранной буквой метода push_back подсказывает все более узкий список возможных продолжений, т.к. среде разработки известно, что переменная x является контейнером std::vector, все методы которого ей (среде разработки) тоже известны.

В случае с динамической типизацией наблюдается совершенно иная картина.

При вызове функции f на месте переменной x может оказаться объект любого типа. Даже если программисту известно, что это всегда будет список, у которого есть метод append , то среде разработки это отнюдь не очевидно. Это приводит к тому, что она не может подсказать возможное продолжение, т.к. список возможных продолжений близок к безграничному.

Однако если подсказать среде разработке, что x — переменная типа list , то она начнет реагировать в соответствии.

Введение в аннотации типов 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-файлы, которые содержат информацию только для статических анализаторов.

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

Почему надо использовать Type Hinting?

Python — язык с динамической типизацией типов. Что это значит? Это значит, что переменная связывается с соответствующим типом в момент присваивания значения, а не в момент объявления переменной. Таким образом, в различных участках кода, одна и та же переменная может принимать различные типы.

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

Для решения этого вопроса на помощь разработчикам приходит Type Hinting, описанный в спецификации PEP 484 и впервые представленный в Python 3.5. Type Hinting зачастую называют ещё Type Annotation и для понимания, пожалуй, второе название лучше. Важно понимать, что Type Annotation — это всего лишь аннотация типа. С помощью TH мы не включаем некий волшебный режим в Python, делающий его языком со статической типизацией. Это всего лишь инструмент сделать код более прозрачным и и понятным. К TH можно относиться как неким комментариям, позволяющим сократить возможные ошибки и упростить последующую его поддержку.

Синтаксис

Основной синтаксис TH представлен в следующем примере:

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

Указывая тип аргумента обычно ставят двоеточие сразу после названия аргумента без пробелов, затем идет пробел и указание типа. Если необходимо присвоить аргументу значение по умолчанию, то ставим пробелы до и после знака равно. Так же необходимо использовать пробелы до и после стрелочки, указывающей на тип возвращаемых данных.

Чтобы указывать типы простых встроенных типов данных не требуется никаких дополнительных импортов. Чтобы указывать типы структур данных, таких как списки, множества, словари, кортежи — необходимо использовать пекедж typing:

Также интересным является тип Optional. Скажем, если у нас есть аргумент или возвращаемое значение, которое может быть None, то, чтобы указать корректный тип можно написать так:

Данная запись выше означает, что функция возвращает либо datetime, либо None. Фактически, Optional является сокращением для записи: Union[type1, type2, …]. Union позволяет указать, что объект может быть одним из типов указанных в перечислении. Скажем, для примера выше аналог Optional[datetime] с использованием Union будет выглядеть так: Union[datetime, None].

Предположим, необходимо задать тип объекта как вызываемая функция (callable). Для этого используем следующую запись — Callable[[arg1, arg2], return_type], где arg1, arg2 — типы передаваемых аргументов, а return_type — возвращаемый исполняемой функцией тип.

Очень удобно использовать альясы типов. Вся типизация, используемая в TH, может довольно сильно ухудшить читаемость кода, если типов будет в избытке, причем всяких сложных. Чтобы упростить код хорошо использовать альясы:

Как было упомянуто выше, TH — это всего лишь аннотация, которая сама по себе не будет возвращать никаких ошибок.

Запустив данный код мы не получим никаких ошибок, а выведется число 30. Чтобы проверять корректность TH используются специальные так называемые type checker-ы. MyPy — один из них. Для его установки необходимо поставить pip и затем написать pip install mypy. После чего, написанный вами код можно проверять из терминала командой mypy my_script.py.

Плюсы и минусы TH

Для начала, рассмотрим плюсы использования TH:

  • TH — это еще один крутой способ улучшить документацию своего проекта наряду с docstring-ами.
  • TH могут улучшить опыт работы с IDE путем получения более осмысленного фидбека, автокомплитов и пр.
  • Добавление TH в код заставляет разработчика думать о типизации, что должно приводить к принятию более правильных архитектурных решений.

К сожалению, есть некоторые минусы в использовании TH:

  • Становится физически больше кода и его, порой, уже не так быстро и просто прочесть.
  • Написание TH занимает время разработки.
  • Проекты, использующие TH, могут незначительно занимать больше времени для запуска, особенно, если импортируется пекедж typing.

Когда же целесообразно использовать TH?

  • Если ведется разработка библиотеки/пекеджа для использования другими разработчиками в их проектах, использовать TH крайне рекомендуется.
  • Если вы работаете над большим Python проектом (тысячи строк кода), TH так же будет здорово помогать разобраться в коде и пользоваться им.
  • TH так же хорошо помогают, если для кода будут писаться unit test-ы.

Безусловно, используя TH надо знать меру. Везде указывать типы — нецелесообразно, потому что это будет противоречить принципам языка, ведь Python поддерживает принцип “duck typing-а”, который гласит, что если объект реализует метод, то мы его используем. Или более складно: если нечто выглядит как утка, плавает как утка и крякает как утка, то это, вероятно, и есть утка! Поэтому, никаких типов строгих в Python и не используется. Зачастую в коде можно встретить такую конструкцию:

Т.е. Функция работает с любым типом объекта foo, который имеет атрибут name. Программе наплевать на его тип, главное, чтобы было нужное свойство.

Но несмотря на все это, TH — очень мощная вещь, которую следует применять. Как уже частично было сказано ранее, использование TH заставляет разработчика думать при реализации той же функции на более высоком уровне, а не просто думать о том как сделать конкретный функционал. А думать о функционале как бы “сверху”, взглядом архитектора, а не просто разработчика — очень полезно для кода.

Кроме того, несмотря на возможное незначительное увеличение физического количества кода, читать его все равно в конечном итоге намного проще. Давайте рассмотрим пример:

Что такое объект program? Это строка? Это пользовательский объект? Совершенно непонятно. А теперь посмотрим на такой код:

Теперь, при первом же прочтении, становится очевидно, что program — это экземпляр класса BeautifulSoup, реализующий метод find. Без этого пустячного type hint-а пришлось бы затратить какое-то количество времени на то, чтобы разобраться в коде, особенно, если проект очень большой, либо человек уже давно над ним не работал.

Учитывая все вышеописанное можно сделать вывод, что использовать TH необходимо, если только вы не пишите небольшой скрипт на 100 строчек кода. Как минимум указывая типы аргументов у функций и типы возвращаемых ими значений, вы значительно улучшите читаемость кода и значительно упростите жизнь и себе в последующей работой над проектом, и коллегам.

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 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.

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.

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. These include:

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) .

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. There is some additional runtime cost when calling NewType over a regular function. However, this cost will be reduced in 3.11.0.

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, abstract base classes have been extended to support subscription to denote expected types for 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 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:

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:

Do 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 types that are subclasses of pre-existing standard library classes which also extend Generic to support type variables inside [] . These types 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 will be 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.

Читать:
Почему в байте 8 бит

The deprecated types will be removed from the typing module in 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.

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 . For example:

See PEP 613 for more details about explicit type aliases.

New in version 3.10.

Special forms¶

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

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. 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 is equivalent to Tuple[Any, . ] , and in turn to tuple .

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 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 .

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 ).

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, 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.

A type, introduced in PEP 593 ( Flexible function and variable annotations ), to decorate existing types with context-specific metadata (possibly multiple pieces of it, as Annotated is variadic). Specifically, a type T can be annotated with metadata x via the typehint Annotated[T, x] . This metadata can be used for either static analysis or at runtime. If a library (or tool) encounters a typehint Annotated[T, x] and has no special logic for metadata x , it should ignore it and simply treat the type as T . Unlike the no_type_check functionality that currently exists in the typing module which completely disables typechecking annotations on a function or a class, the Annotated type allows for both static typechecking of T (which can safely ignore x ) together with runtime access to x within a specific application.

Ultimately, the responsibility of how to interpret the annotations (if at all) is the responsibility of the tool or library encountering the Annotated type. A tool or library encountering an Annotated type can scan through the annotations to determine if they are of interest (e.g., using isinstance() ).

When a tool or a library does not support annotations or encounters an unknown annotation it should just ignore it and treat annotated type as the underlying type.

It’s up to the tool consuming the annotations to decide whether the client is allowed to have several annotations on one type and how to merge those annotations.

Since the Annotated type allows you to put several annotations of the same (or different) type(s) on any node, the tools or libraries consuming those annotations are in charge of dealing with potential duplicates. For example, if you are doing value range analysis you might allow this:

Passing include_extras=True to get_type_hints() lets one access the extra annotations at runtime.

The details of the syntax:

The first argument to Annotated must be a valid type

Multiple type annotations are supported ( Annotated supports variadic arguments):

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

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

Nested Annotated types are flattened, with metadata ordered starting with the innermost annotation:

Duplicated annotations are not removed:

Annotated can be used with nested and generic aliases:

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.

Building generic types¶

These are not used in annotations. 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 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.

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 . 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.

class typing. TypeVarTuple ¶

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.

New in version 3.11.

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 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.

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 .

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.

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:

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, not their type signatures. 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 .

New in version 3.8.

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:

New in version 3.5.2.

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

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:

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¶

A generic version of dict . Useful for annotating return types. To annotate arguments it is preferred to use an abstract collection type such as Mapping .

This type can be used as follows:

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

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

This type may be used as follows:

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

A generic version of builtins.set . Useful for annotating return types. To annotate arguments it is preferred to use an abstract collection type such as AbstractSet .

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 wherever possible.

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.

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

Похожие статьи