Глоссарий

>>>

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

...

Может обозначать:

  • Стандартное приглашение Python в интерактивной оболочке при вводе блока кода с отступом, внутри пары соответствующих друг другу разделителей (круглых, квадратных или фигурных скобок, а также тройных кавычек) или после указания декоратора.

  • Форму записи объекта Ellipsis в виде многоточия.

абстрактный базовый класс

Абстрактные базовые классы дополняют утиную типизацию, предоставляя способ определения интерфейсов в случаях, когда другие методы, вроде функции hasattr(), были бы громоздкими или могли бы привести к трудноуловимым ошибкам (например, при работе с магическими методами). Абстрактные базовые классы вводят виртуальные подклассы — классы, которые не наследуются от другого класса, но тем не менее распознаются функциями isinstance() и issubclass(); см. документацию модуля abc. Python предоставляет множество встроенных абстрактных базовых классов для структур данных (в модуле collections.abc), чисел (в модуле numbers), потоков (в модуле io), а также для механизма поиска и загрузки при импорте (в модуле importlib.abc). Создавать собственные абстрактные базовые классы можно с помощью модуля abc.

функция аннотации

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

аннотация

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

Аннотации локальных переменных недоступны во время выполнения, но аннотации глобальных переменных, атрибутов классов и функций можно получить, вызвав annotationlib.get_annotations() для модулей, классов и функций соответственно.

См. аннотацию переменных, аннотацию функций, PEP 484, PEP 526 и PEP 649, в которых описывается эта функциональность. См. также раздел Annotations Best Practices с рекомендациями по работе с аннотациями.

аргумент

Значение, передаваемое в функцию (или метод) при вызове функции. Есть два вида аргументов:

  • именованный аргумент: аргумент, которому в вызове функции предшествует идентификатор (например, name=), или значение, передаваемое в словаре с предшествующим ему **. Например, 3 и 5 являются именованными аргументами в следующих вызовах complex():

    complex(real=3, imag=5)
    complex(**{'real': 3, 'imag': 5})
    
  • позиционный аргумент: аргумент, который не является именованным. Позиционные аргументы могут находиться в начале списка аргументов и/или передаваться как элементы итерируемого объекта, перед которым стоит *. Например, 3 и 5 являются позиционными аргументами в следующих вызовах:

    complex(3, 5)
    complex(*(3, 5))
    

Аргументы присваиваются именованным локальным переменным в теле функции. Правила такого присваивания см. в разделе Calls. Синтаксически для представления аргумента можно использовать любое выражение. Его значение вычисляется и присваивается локальной переменной.

См. также статью глоссария параметр, раздел о различии между аргументами и параметрами в часто задаваемых вопросах и PEP 362.

асинхронный менеджер контекста

Объект, управляющий окружением, доступным в инструкции async with, посредством определения методов __aenter__() и __aexit__(). Представлен в PEP 492.

асинхронный генератор

Неформально используется для обозначения либо асинхронной генераторной функции, либо асинхронного генераторного итератора — в зависимости от контекста. Формальные термины асинхронная генераторная функция и асинхронный генераторный итератор редко используются на практике; почти всегда достаточно термина «асинхронный генератор».

асинхронная генераторная функция

Функция, возвращающая асинхронный генераторный итератор. Она похожа на функцию сопрограммы, определённую с помощью async def, но содержит выражения yield, генерирующие последовательность значений, которые можно использовать в цикле async for. См. PEP 525.

Асинхронная генераторная функция может содержать выражения await, а также инструкции async for и async with.

асинхронный генераторный итератор

Объект, созданный асинхронной генераторной функцией.

Это асинхронный итератор, у которого вызов метода __anext__() возвращает ожидаемый объект, выполняющий тело асинхронной генераторной функции до следующего выражения yield.

Каждое выражение yield временно приостанавливает выполнение, сохраняя состояние выполнения (включая локальные переменные и ожидающие выполнения инструкции try). Когда асинхронный генераторный итератор фактически возобновляется при ожидании очередного объекта после вызова __anext__(), он продолжает выполнение с того места, на котором остановился. См. PEP 492 и PEP 525.

асинхронный итерируемый объект

Объект, который можно использовать в инструкции async for. Должен возвращать асинхронный итератор из своего метода __aiter__(). Представлен в PEP 492.

асинхронный итератор

Объект, реализующий методы __aiter__() и __anext__(). Метод __anext__() должен возвращать объект, допускающий ожидание. Инструкция async for ожидает объекты, возвращаемые методом асинхронного итератора __anext__(), до тех пор, пока тот не вызовет исключение StopAsyncIteration. Представлен в PEP 492.

атомарная операция

Операция, которая выполняется как единый неделимый шаг: ни один другой поток не может увидеть её в промежуточном состоянии, а все её эффекты становятся видимыми одновременно. Python не гарантирует атомарность инструкций высокого уровня (например, x += 1 выполняет несколько операций в байт-коде и не является атомарной). Атомарность гарантируется только там, где это явно указано в документации. См. также состояние гонки и гонка данных.

присоединённое состояние потока

Состояние потока, активное для текущего потока ОС.

Когда состояние потока присоединено к потоку ОС, послений получает доступ ко всему C API Python и может безопасно вызывать интерпретатор байт-кода.

Если для функции явно не указано иное, попытка вызвать C API без присоединённого состояния потока приведёт к фатальной ошибке или неопределённому поведению. Состояние потока может быть явно присоединено или отсоединено пользователем через C API либо неявно — средой выполнения, в том числе во время блокирующих вызовов C и интерпретатором байт-кода между вызовами.

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

атрибут

Значение, связанное с объектом, на который обычно ссылаются по имени, с помощью выражения с точками. Например, если объект o имеет атрибут a, на него ссылаются как o.a.

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

ожидаемый объект

Объект, который можно использовать в выражении await. Это может быть сопрограмма или объект с методом __await__(). См. также PEP 492.

BDFL

Великодушный пожизненный диктатор, он же Гвидо ван Россум, создатель Python.

двоичный файл

Файловый объект, способный читать и записывать объекты, подобные байтам. Примеры двоичных файлов: файлы, открытые в двоичном режиме ('rb', 'wb' или 'rb+'), sys.stdin.buffer, sys.stdout.buffer, а также экземпляры io.BytesIO и gzip.GzipFile.

См. также текстовый файл для файлового объекта, способного читать и записывать объекты str.

заимствованная ссылка

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

За исключением случаев, когда объект не может быть уничтожен до последнего использования заимствованной ссылки, её рекомендуется преобразовать на месте в сильную ссылку, вызвав функцию Py_INCREF(). А для создания новой сильной ссылки можно использовать функцию Py_NewRef().

объект, подобный bytes

Объект, поддерживающий Buffer Protocol и способный экспортировать непрерывный C-буфер. Сюда входят все объекты bytes, bytearray и array.array, а также многие распространённые объекты memoryview. Объекты, подобные bytes, можно использовать для различных операций с двоичными данными, включая сжатие, сохранение в двоичный файл и отправку через сокет.

Некоторым операциям требуется, чтобы двоичные данные были изменяемыми. В документации такие объекты часто называются «объектами, подобными bytes, доступными для чтения и записи». Примерами изменяемых объектов буфера являются bytearray`и :class:`memoryview типа bytearray. Другим операциям требуется, чтобы двоичные данные хранились в неизменяемых объектах («объектах, подобных bytes, доступных только для чтения»); к таким объектам относятся, например, bytes и memoryview типа bytes.

байт-код

Исходный код Python компилируется в байт-код — внутреннее представление программы Python в интерпретаторе CPython. Байт-код также кэшируется в файлах .pyc благодаря повторное выполнение того же файла происходит быстрее (повторной компиляции исходного кода в байт-код можно избежать). Этот «промежуточный язык» выполняется на виртуальной машине, которая исполняет машинный код, соответствующий каждой инструкции байт-кода. Следует учитывать, что байт-код не предназначен для работы на разных виртуальных машинах Python и не гарантирует стабильность между разными версиями Python.

Список инструкций байт-кода можно найти в документации к модулю dis.

вызываемый объект

Вызываемый объект — это объект, который можно вызвать, возможно, с набором аргументов (см. аргумент), используя следующий синтаксис:

callable(argument1, argument2, argumentN)

Функция, а также производный от неё метод, является вызываемым объектом. Экземпляр класса, реализующего метод __call__(), также является вызываемым.

функция обратного вызова

Подпрограмма в виде функции, переданная в качестве аргумента для выполнения в некоторый момент в будущем.

класс

Шаблон для создания пользовательских объектов. Определения классов обычно содержат определения методов, которые работают с экземплярами класса.

переменная класса

Переменная, определённая в классе и предназначенная для изменения только на уровне класса (то есть не в экземпляре класса).

переменная замыкания

Свободная переменная, на которую ссылаются из вложенной области видимости и которая определена во внешней области видимости, а не разрешается во время выполнения через глобальное пространство имён или пространство имён встроенных объектов. Может быть явно объявлена с помощью ключевого слова nonlocal, чтобы разрешить запись, или определена неявно, если переменная только считывается.

Например, в функции inner в приведённом ниже коде x и print являются свободными переменными, но только x является переменной замыкания:

def outer():
    x = 0
    def inner():
        nonlocal x
        x += 1
        print(x)
    return inner

Из-за атрибута codeobject.co_freevars (который, несмотря на своё название, содержит только имена переменных замыкания, а не перечисляет все свободные переменные, на которые имеются ссылки) более общий термин свободная переменная иногда используется даже тогда, когда имеется в виду именно переменная замыкания.

комплексное число

Расширение привычной системы действительных чисел, в которой все числа выражаются как сумма действительной и мнимой частей. Мнимые числа — это произведения действительных чисел и мнимой единицы (квадратного корня из -1), которую в математике обычно обозначают i, а в инженерных дисциплинах — j. Python имеет встроенную поддержку комплексных чисел, которые записываются с использованием последнего обозначения; мнимая часть записывается с суффиксом j, например 3+1j. Чтобы получить доступ к комплексным аналогам функций модуля math, используйте cmath. Использование комплексных чисел — довольно продвинутая математическая возможность. Если вы не осознаёте необходимости в них, вы почти наверняка можете спокойно их игнорировать.

конкурентность

Способность компьютерной программы выполнять несколько задач одновременно. Python предоставляет библиотеки для написания программ, использующих различные формы конкурентности. Библиотека asyncio предназначена для работы с асинхронными задачами и сопрограммами. threading предоставляет доступ к потокам операционной системы, а multiprocessing — к процессам операционной системы. Многоядерные процессоры могут одновременно выполнять потоки и процессы на разных ядрах ЦП (см. параллелизм).

конкурентное изменение

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

контекст

Этот термин имеет разные значения в зависимости от того, где и как он используется. Некоторые распространённые значения:

  • Временное состояние или окружение, устанавливаемое менеджером контекста с помощью инструкции with.

  • Коллекция связей «ключ—значение», содержащихся в конкретном объекте contextvars.Context и доступных через объекты ContextVar. См. также контекстная переменная.

  • Объект contextvars.Context. См. также текущий контекст.

протокол управления контекстом

Методы __enter__() и __exit__(), вызываемые инструкцией with. См. PEP 343.

менеджер контекста

Объект, реализующий протокол управления контекстом и управляющий окружением, доступным внутри инструкции with. См. PEP 343.

переменная контекста

Переменная, значение которой зависит от того, какой контекст является текущим контекстом. Доступ к значениям осуществляется через объекты contextvars.ContextVar. Переменные контекста в основном используются для изоляции состояния между конкурентно выполняемыми асинхронными задачами.

непрерывный

Буфер считается непрерывным, если он является либо C-непрерывным, либо Fortran-непрерывным. Буферы нулевой размерности являются непрерывными и в смысле C, и в смысле Fortran. В одномерных массивах элементы должны быть расположены в памяти друг за другом в порядке возрастания индексов, начиная с нулевого. При последовательном обходе элементов многомерных C-непрерывных массивов в порядке возрастания их адресов в памяти быстрее всего изменяется последний индекс. В Fortran-непрерывных массивах, напротив, быстрее всего изменяется первый индекс.

сопрограмма

Сопрограммы являются более обобщённой формой подпрограмм. Подпрограмма запускается в одной точке и завершается в другой. Сопрограмма же может запускаться, завершаться и возобновляться в различных точках. Она может быть реализована с помощью инструкции async def. См. также PEP 492.

сопрограммная функция

Функция, возвращающая сопрограмму. Сопрограммная функция может быть определена с помощью инструкции async def и может содержать выражения await, а также инструкции async for и async with. Представлены в PEP 492.

CPython

Каноническая реализация языка программирования Python, распространяемая на python.org. Термин «CPython» используется, когда необходимо отличить эту реализацию от других, таких как Jython или IronPython.

текущий контекст

Контекст (объект contextvars.Context), который в данный момент используется объектами ContextVar для доступа (получения и изменения) к значениям переменных контекста. У каждого потока есть собственный текущий контекст. Фреймворки для выполнения асинхронных задач (см. asyncio) связывают каждую задачу с контекстом, который становится текущим контекстом всякий раз, когда задача начинает или возобновляет выполнение.

циклический изолят

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

гонка данных

Ситуация, при которой несколько потоков одновременно обращаются к одной и той же области памяти, причём как минимум одно из обращений выполняет запись, а потоки не используют синхронизацию для управления доступом к этой области памяти. Гонки данных приводят к недетерминированному поведению и могут вызвать повреждение данных. Правильное использование блокировок и других примитивов синхронизации предотвращает гонки данных. Обратите внимание, что гонки данных могут возникать только в нативном коде, однако нативный код может быть доступен через API Python. См. также состояние гонки и потокобезопасный.

взаимная блокировка

Ситуация, при которой две или более задачи (потоки, процессы или сопрограммы) бесконечно ждут друг от друга освобождения ресурсов или завершения действий, не позволяя ни одной из них продолжить выполнение. Например, если поток A удерживает блокировку 1 и ждёт блокировку 2, а поток B удерживает блокировку 2 и ждёт блокировку 1, оба потока будут ждать бесконечно. В Python взаимные блокировки часто возникают из-за получения нескольких блокировок в конфликтующем порядке или из-за циклических зависимостей между join и await. Взаимных блокировок можно избежать, всегда получая несколько блокировок в одном и том же порядке. См. также блокировка и реентерабельность.

декоратор

Функция, возвращающая другую функцию; обычно применяется для преобразования функции с помощью синтаксиса @wrapper. Типичные примеры декораторов — @classmethod и @staticmethod.

Синтаксис декораторов является лишь синтаксическим сахаром: следующие два определения функций семантически эквивалентны:

def f(arg):
    ...
f = staticmethod(f)

@staticmethod
def f(arg):
    ...

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

дескриптор

Любой объект, определяющий методы __get__(), __set__() или __delete__(). Когда атрибут класса является дескриптором, при обращении к этому атрибуту срабатывает специальный механизм связывания. Обычно выражение a.b для получения, изменения или удаления атрибута ищет объект с именем b в словаре класса a, но если b является дескриптором, вызывается соответствующий метод дескриптора. Понимание дескрипторов является ключом к глубокому пониманию Python, поскольку они лежат в основе многих возможностей языка, включая функции, методы, свойства, методы класса, статические методы и обращение к суперклассам.

Подробнее о методах дескрипторов см. раздел Implementing Descriptors или Практическое руководство по дескрипторам.

словарь

Ассоциативный массив, в котором произвольные ключи сопоставляются со значениями. Ключами могут быть любые объекты, имеющие методы __hash__() и __eq__(). В Perl называется хешем.

включение словаря

Компактный способ обработать все или часть элементов итерируемого объекта и вернуть словарь с результатами. results = {n: n ** 2 for n in range(10)} создаёт словарь, содержащий ключ n, сопоставленный со значением n ** 2. См. раздел Displays for lists, sets and dictionaries.

представление словаря

Объекты, возвращаемые методами dict.keys(), dict.values() и dict.items(), называются представлениями словаря. Они предоставляют динамическое представление элементов словаря, то есть при изменении словаря эти изменения отражаются в представлении. Чтобы преобразовать представление словаря в полноценный список, используйте list(dictview). См. раздел Dictionary view objects.

строка документации

Строковый литерал, который является первым выражением в классе, функции или модуле. Хотя при выполнении набора инструкций он игнорируется, компилятор распознаёт его и помещает в атрибут __doc__ содержащего его класса, функции или модуля. Поскольку к нему можно получить доступ средствами интроспекции, это стандартное место для документации объекта.

утиная типизация

Стиль программирования, при котором тип объекта не используется для определения его интерфейса. Вместо этого метод или атрибут просто вызывается или используется («Если что-то выглядит как утка и крякает как утка, значит, это и есть утка».) Делая акцент на интерфейсах, а не на конкретных типах, хорошо спроектированный код повышает свою гибкость, позволяя выполнять полиморфную замену объектов. Утиная типизация избегает проверок с использованием type() или isinstance(). (Однако обратите внимание, что утиная типизация может быть дополнена абстрактными базовыми классами.) Вместо этого обычно используются проверки hasattr() или программирование в стиле EAFP.

dunder

Неформальное сокращение от «double underscore» («двойное подчёркивание»), используемое при упоминании специального метода. Например, __init__ часто произносится как «dunder init».

EAFP

«Проще попросить прощения, чем разрешения» («Easier to ask for forgiveness than permission»). Распространённый в Python стиль программирования, при котором предполагается наличие допустимых ключей или атрибутов, а исключения перехватываются, если это предположение оказывается неверным. Этот чистый и быстрый стиль характеризуется наличием множества инструкций try и except. Этот подход противопоставляется стилю LBYL, распространённому во многих других языках, например в C.

вычисляющая функция

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

выражение

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

модуль расширения

Модуль, написанный на C или C++, использующий C API Python для взаимодействия с ядром и пользовательским кодом.

f-строка
f-строки

Строковые литералы с префиксом f или F обычно называются «f-строками» — это сокращение от форматированные строковые литералы. См. также PEP 498.

файловый объект

Объект, предоставляющий файлово-ориентированный API (с такими методами, как read() или write()) к базовому ресурсу. В зависимости от способа создания, файловый объект может выступать посредником при доступе к реальному файлу на диске или к другому типу устройства хранения или связи (например, стандартному вводу/выводу, буферам в памяти, сокетам, каналам и т. д.). Файловые объекты также называются файлоподобными объектами или потоками.

На самом деле существует три категории файловых объектов: сырые двоичные файлы, буферизованные двоичные файлы и текстовые файлы. Их интерфейсы определены в модуле io. Канонический способ создания файлового объекта — использование функции open().

файлоподобный объект

Синоним файлового объекта.

кодировка файловой системы и обработчик ошибок

Кодировка и обработчик ошибок, используемые Python для декодирования байтов, получаемых от операционной системы, и кодирования Unicode при передаче данных операционной системе.

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

Функции sys.getfilesystemencoding() и sys.getfilesystemencodeerrors() можно использовать для получения кодировки файловой системы и обработчика ошибок.

Кодировка файловой системы и обработчик ошибок настраиваются при запуске Python функцией PyConfig_Read(): см. члены filesystem_encoding и filesystem_errors объекта PyConfig.

См. также кодировку локали.

поисковик

Объект, который пытается найти загрузчик для импортируемого модуля.

Существует два типа поисковиков: поисковики метапути, используемые с sys.meta_path и поисковики элемента пути, используемые с sys.path_hooks.

Подробнее см. в Finders and loaders и importlib.

целочисленное деление с округлением вниз

Математическое деление, округляющее результат до ближайшего целого числа в меньшую сторону. Оператор целочисленного деления с округлением вниз — это //. Например, выражение 11 // 4 вычисляется как 2, в отличие от 2.75, возвращаемого истинным делением чисел с плавающей точкой. Обратите внимание, что (-11) // 4 равно -3, поскольку это значение -2.75, округлённое вниз. См. также PEP 238.

свободная многопоточность

Модель потоков, в которой несколько потоков могут одновременно выполнять байт-код Python в одном интерпретаторе. Это противопоставляется глобальной блокировке интерпретатора, которая позволяет выполнять байт-код Python только одному потоку за раз. См. PEP 703.

сборка с поддержкой свободной многопоточности

Сборка CPython, поддерживающая свободную многопоточность и настроенная с помощью параметра --disable-gil перед компиляцией.

См. Python support for free threading.

свободная переменная

Формально, как определено в модели выполнения языка, свободная переменная — это любая переменная, используемая в пространстве имён, которая не является локальной переменной в этом пространстве имён. См. пример в статье о переменной замыкания. На практике, из-за названия атрибута codeobject.co_freevars, этот термин также иногда используется как синоним переменной замыкания.

функция

Последовательность инструкций, возвращающая некоторое значение вызывающему её коду. Ей также может быть передано ноль или более аргументов, которые могут использоваться при выполнении её тела. См. также параметр, метод и раздел Function definitions.

аннотация функции

Аннотация параметра функции или возвращаемого значения.

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

def sum_two_numbers(a: int, b: int) -> int:
   return a + b

Синтаксис аннотации функции описан в разделе Function definitions.

См. аннотация переменной и PEP 484, которые описывают эту функциональность. Рекомендации по работе с аннотациями см. также в Annotations Best Practices.

__future__

Инструкция future, from __future__ import <feature>, указывает компилятору обрабатывать текущий модуль с использованием синтаксиса или семантики, которые станут стандартными в будущей версии Python. Модуль __future__ документирует возможные значения feature. Импортировав этот модуль и изучив его переменные, можно узнать, когда новая функциональность была впервые добавлена в язык и когда она станет (или стала) используемой по умолчанию:

>>> import __future__
>>> __future__.division
_Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)
сборка мусора

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

генератор

Неформально используется для обозначения либо генераторной функции, либо генераторного итератора в зависимости от контекста. Формальные термины генераторная функция и генераторный итератор на практике используются редко; одного слова «генератор» почти всегда достаточно.

генераторная функция

Функция, возвращающая объект генератора. Выглядит как обычная функция, но содержит выражения yield, порождающие последовательность значений, которые можно использовать в цикле for или получать по одному с помощью функции next(). См. Yield expressions.

генераторный итератор

Объект, созданный генераторной функцией или генераторным выражением.

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

Генераторные итераторы также реализуют метод send(), позволяющий передать значение приостановленному генератору, и метод throw(), позволяющий возбудить исключение в точке, где генератор был приостановлен. См. Generator-iterator methods.

генераторное выражение

Выражение, возвращающее итератор. Выглядит как обычное выражение, за которым следует конструкция for, определяющая переменную цикла и диапазон, а также необязательная часть if. Такое составное выражение порождает значения для объемлющей функции:

>>> sum(i*i for i in range(10))         # сумма квадратов 0, 1, 4, ... 81
285
обобщённая функция

A function composed of multiple functions implementing the same operation for different types. Which implementation should be used during a call is determined by the dispatch algorithm.

See also the single dispatch glossary entry, the @functools.singledispatch decorator, and PEP 443.

generic type

A type that can be parameterized; typically a container class such as list or dict. Used for type hints and annotations.

For more details, see generic alias types, PEP 483, PEP 484, PEP 585, and the typing module.

GIL

See global interpreter lock.

global interpreter lock

The mechanism used by the CPython interpreter to assure that only one thread executes Python bytecode at a time. This simplifies the CPython implementation by making the object model (including critical built-in types such as dict) implicitly safe against concurrent access. Locking the entire interpreter makes it easier for the interpreter to be multi-threaded, at the expense of much of the parallelism afforded by multi-processor machines.

However, some extension modules, either standard or third-party, are designed so as to release the GIL when doing computationally intensive tasks such as compression or hashing. Also, the GIL is always released when doing I/O.

As of Python 3.13, the GIL can be disabled using the --disable-gil build configuration. After building Python with this option, code must be run with -X gil=0 or after setting the PYTHON_GIL=0 environment variable. This feature enables improved performance for multi-threaded applications and makes it easier to use multi-core CPUs efficiently. For more details, see PEP 703.

In prior versions of Python’s C API, a function might declare that it requires the GIL to be held in order to use it. This refers to having an attached thread state.

global state

Data that is accessible throughout a program, such as module-level variables, class variables, or C static variables in extension modules. In multi-threaded programs, global state shared between threads typically requires synchronization to avoid race conditions and data races.

hash-based pyc

A bytecode cache file that uses the hash rather than the last-modified time of the corresponding source file to determine its validity. See Cached bytecode invalidation.

hashable

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

Most of Python’s immutable built-in objects are hashable; mutable containers (such as lists or dictionaries) are not; immutable containers (such as tuples and frozensets) are only hashable if their elements are hashable. Objects which are instances of user-defined classes are hashable by default. They all compare unequal (except with themselves), and their hash value is derived from their id().

IDLE

An Integrated Development and Learning Environment for Python. IDLE — Python editor and shell is a basic editor and interpreter environment which ships with the standard distribution of Python.

immortal

Immortal objects are a CPython implementation detail introduced in PEP 683.

If an object is immortal, its reference count is never modified, and therefore it is never deallocated while the interpreter is running. For example, True and None are immortal in CPython.

Immortal objects can be identified via sys._is_immortal(), or via PyUnstable_IsImmortal() in the C API.

immutable

An object with a fixed value. Immutable objects include numbers, strings and tuples. Such an object cannot be altered. A new object has to be created if a different value has to be stored. They play an important role in places where a constant hash value is needed, for example as a key in a dictionary. Immutable objects are inherently thread-safe because their state cannot be modified after creation, eliminating concerns about improperly synchronized concurrent modification.

import path

A list of locations (or path entries) that are searched by the path based finder for modules to import. During import, this list of locations usually comes from sys.path, but for subpackages it may also come from the parent package’s __path__ attribute.

importing

The process by which Python code in one module is made available to Python code in another module.

importer

An object that both finds and loads a module; both a finder and loader object.

индекс

Числовое значение, представляющее позицию элемента в последовательности.

В Python индексация начинается с нуля. Например, things[0] обозначает первый элемент things, а things[1] — второй.

В некоторых контекстах Python допускает отрицательные индексы для отсчёта от конца последовательности, а также индексацию с использованием срезов.

См. также индексатор.

interactive

Python has an interactive interpreter which means you can enter statements and expressions at the interpreter prompt, immediately execute them and see their results. Just launch python with no arguments (possibly by selecting it from your computer’s main menu). It is a very powerful way to test out new ideas or inspect modules and packages (remember help(x)). For more on interactive mode, see Интерактивный режим.

interpreted

Python is an interpreted language, as opposed to a compiled one, though the distinction can be blurry because of the presence of the bytecode compiler. This means that source files can be run directly without explicitly creating an executable which is then run. Interpreted languages typically have a shorter development/debug cycle than compiled ones, though their programs generally also run more slowly. See also interactive.

interpreter shutdown

When asked to shut down, the Python interpreter enters a special phase where it gradually releases all allocated resources, such as modules and various critical internal structures. It also makes several calls to the garbage collector. This can trigger the execution of code in user-defined destructors or weakref callbacks. Code executed during the shutdown phase can encounter various exceptions as the resources it relies on may not function anymore (common examples are library modules or the warnings machinery).

The main reason for interpreter shutdown is that the __main__ module or the script being run has finished executing.

iterable

An object capable of returning its members one at a time. Examples of iterables include all sequence types (such as list, str, and tuple) and some non-sequence types like dict, file objects, and objects of any classes you define with an __iter__() method or with a __getitem__() method that implements sequence semantics.

Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map(), …). When an iterable object is passed as an argument to the built-in function iter(), it returns an iterator for the object. This iterator is good for one pass over the set of values. When using iterables, it is usually not necessary to call iter() or deal with iterator objects yourself. The for statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also iterator, sequence, and generator.

iterator

An object representing a stream of data. Repeated calls to the iterator’s __next__() method (or passing it to the built-in function next()) return successive items in the stream. When no more data are available a StopIteration exception is raised instead. At this point, the iterator object is exhausted and any further calls to its __next__() method just raise StopIteration again. Iterators are required to have an __iter__() method that returns the iterator object itself so every iterator is also iterable and may be used in most places where other iterables are accepted. One notable exception is code which attempts multiple iteration passes. A container object (such as a list) produces a fresh new iterator each time you pass it to the iter() function or use it in a for loop. Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container.

More information can be found in Iterator Types.

CPython implementation detail: CPython does not consistently apply the requirement that an iterator define __iter__(). And also please note that free-threaded CPython does not guarantee thread-safe behavior of iterator operations.

key

A value that identifies an entry in a mapping. See also subscript.

key function

A key function or collation function is a callable that returns a value used for sorting or ordering. For example, locale.strxfrm() is used to produce a sort key that is aware of locale specific sort conventions.

A number of tools in Python accept key functions to control how elements are ordered or grouped. They include min(), max(), sorted(), list.sort(), heapq.merge(), heapq.nsmallest(), heapq.nlargest(), and itertools.groupby().

There are several ways to create a key function. For example. the str.casefold() method can serve as a key function for case insensitive sorts. Alternatively, a key function can be built from a lambda expression such as lambda r: (r[0], r[2]). Also, operator.attrgetter(), operator.itemgetter(), and operator.methodcaller() are three key function constructors. See the Sorting HOW TO for examples of how to create and use key functions.

keyword argument

See argument.

lambda

An anonymous inline function consisting of a single expression which is evaluated when the function is called. The syntax to create a lambda function is lambda [parameters]: expression

LBYL

Look before you leap. This coding style explicitly tests for pre-conditions before making calls or lookups. This style contrasts with the EAFP approach and is characterized by the presence of many if statements.

In a multi-threaded environment, the LBYL approach can risk introducing a race condition between «the looking» and «the leaping». For example, the code, if key in mapping: return mapping[key] can fail if another thread removes key from mapping after the test, but before the lookup. This issue can be solved with locks or by using the EAFP approach. See also thread-safe.

lexical analyzer

Formal name for the tokenizer; see token.

list

A built-in Python sequence. Despite its name it is more akin to an array in other languages than to a linked list since access to elements is O(1).

list comprehension

A compact way to process all or part of the elements in a sequence and return a list with the results. result = ['{:#04x}'.format(x) for x in range(256) if x % 2 == 0] generates a list of strings containing even hex numbers (0x..) in the range from 0 to 255. The if clause is optional. If omitted, all elements in range(256) are processed.

lock

A synchronization primitive that allows only one thread at a time to access a shared resource. A thread must acquire a lock before accessing the protected resource and release it afterward. If a thread attempts to acquire a lock that is already held by another thread, it will block until the lock becomes available. Python’s threading module provides Lock (a basic lock) and RLock (a reentrant lock). Locks are used to prevent race conditions and ensure thread-safe access to shared data. Alternative design patterns to locks exist such as queues, producer/consumer patterns, and thread-local state. See also deadlock, and reentrant.

lock-free

An operation that does not acquire any lock and uses atomic CPU instructions to ensure correctness. Lock-free operations can execute concurrently without blocking each other and cannot be blocked by operations that hold locks. In free-threaded Python, built-in types like dict and list provide lock-free read operations, which means other threads may observe intermediate states during multi-step modifications even when those modifications hold the per-object lock.

loader

An object that loads a module. It must define the exec_module() and create_module() methods to implement the Loader interface. A loader is typically returned by a finder. See also:

locale encoding

On Unix, it is the encoding of the LC_CTYPE locale. It can be set with locale.setlocale(locale.LC_CTYPE, new_locale).

On Windows, it is the ANSI code page (ex: "cp1252").

On Android and VxWorks, Python uses "utf-8" as the locale encoding.

locale.getencoding() can be used to get the locale encoding.

See also the filesystem encoding and error handler.

magic method

An informal synonym for special method.

mapping

A container object that supports arbitrary key lookups and implements the methods specified in the collections.abc.Mapping or collections.abc.MutableMapping abstract base classes. Examples include dict, collections.defaultdict, collections.OrderedDict and collections.Counter.

meta path finder

A finder returned by a search of sys.meta_path. Meta path finders are related to, but different from path entry finders.

See importlib.abc.MetaPathFinder for the methods that meta path finders implement.

metaclass

The class of a class. Class definitions create a class name, a class dictionary, and a list of base classes. The metaclass is responsible for taking those three arguments and creating the class. Most object oriented programming languages provide a default implementation. What makes Python special is that it is possible to create custom metaclasses. Most users never need this tool, but when the need arises, metaclasses can provide powerful, elegant solutions. They have been used for logging attribute access, adding thread-safety, tracking object creation, implementing singletons, and many other tasks.

More information can be found in Metaclasses.

method

A function which is defined inside a class body. If called as an attribute of an instance of that class, the method will get the instance object as its first argument (which is usually called self). See function and nested scope.

method resolution order

Method Resolution Order is the order in which base classes are searched for a member during lookup. See The Python 2.3 Method Resolution Order for details of the algorithm used by the Python interpreter since the 2.3 release.

module

An object that serves as an organizational unit of Python code. Modules have a namespace containing arbitrary Python objects. Modules are loaded into Python by the process of importing.

See also package.

module spec

A namespace containing the import-related information used to load a module. An instance of importlib.machinery.ModuleSpec.

See also Module specs.

MRO

See method resolution order.

mutable

An object with state that is allowed to change during the course of the program. In multi-threaded programs, mutable objects that are shared between threads require careful synchronization to avoid race conditions. See also immutable, thread-safe, and concurrent modification.

named tuple

The term «named tuple» applies to any type or class that inherits from tuple and whose indexable elements are also accessible using named attributes. The type or class may have other features as well.

Several built-in types are named tuples, including the values returned by time.localtime() and os.stat(). Another example is sys.float_info:

>>> sys.float_info[1]                   # indexed access
1024
>>> sys.float_info.max_exp              # named field access
1024
>>> isinstance(sys.float_info, tuple)   # kind of tuple
True

Some named tuples are built-in types (such as the above examples). Alternatively, a named tuple can be created from a regular class definition that inherits from tuple and that defines named fields. Such a class can be written by hand, or it can be created by inheriting typing.NamedTuple, or with the factory function collections.namedtuple(). The latter techniques also add some extra methods that may not be found in hand-written or built-in named tuples.

namespace

The place where a variable is stored. Namespaces are implemented as dictionaries. There are the local, global and built-in namespaces as well as nested namespaces in objects (in methods). Namespaces support modularity by preventing naming conflicts. For instance, the functions builtins.open and os.open() are distinguished by their namespaces. Namespaces also aid readability and maintainability by making it clear which module implements a function. For instance, writing random.seed() or itertools.islice() makes it clear that those functions are implemented by the random and itertools modules, respectively.

namespace package

A package which serves only as a container for subpackages. Namespace packages may have no physical representation, and specifically are not like a regular package because they have no __init__.py file.

Namespace packages allow several individually installable packages to have a common parent package. Otherwise, it is recommended to use a regular package.

For more information, see PEP 420 and Namespace packages.

See also module.

native code

Code that is compiled to machine instructions and runs directly on the processor, as opposed to code that is interpreted or runs in a virtual machine. In the context of Python, native code typically refers to C, C++, Rust or Fortran code in extension modules that can be called from Python. See also extension module.

nested scope

The ability to refer to a variable in an enclosing definition. For instance, a function defined inside another function can refer to variables in the outer function. Note that nested scopes by default work only for reference and not for assignment. Local variables both read and write in the innermost scope. Likewise, global variables read and write to the global namespace. The nonlocal allows writing to outer scopes.

new-style class

Old name for the flavor of classes now used for all class objects. In earlier Python versions, only new-style classes could use Python’s newer, versatile features like __slots__, descriptors, properties, __getattribute__(), class methods, and static methods.

non-deterministic

Behavior where the outcome of a program can vary between executions with the same inputs. In multi-threaded programs, non-deterministic behavior often results from race conditions where the relative timing or interleaving of threads affects the result. Proper synchronization using locks and other synchronization primitives helps ensure deterministic behavior.

object

Any data with state (attributes or value) and defined behavior (methods). Also the ultimate base class of any new-style class.

optimized scope

A scope where target local variable names are reliably known to the compiler when the code is compiled, allowing optimization of read and write access to these names. The local namespaces for functions, generators, coroutines, comprehensions, and generator expressions are optimized in this fashion. Note: most interpreter optimizations are applied to all scopes, only those relying on a known set of local and nonlocal variable names are restricted to optimized scopes.

optional module

An extension module that is part of the standard library, but may be absent in some builds of CPython, usually due to missing third-party libraries or because the module is not available for a given platform.

See Requirements for optional modules for a list of optional modules that require third-party libraries.

package

A Python module which can contain submodules or recursively, subpackages. Technically, a package is a Python module with a __path__ attribute.

See also regular package and namespace package.

parallelism

Executing multiple operations at the same time (e.g. on multiple CPU cores). In Python builds with the global interpreter lock (GIL), only one thread runs Python bytecode at a time, so taking advantage of multiple CPU cores typically involves multiple processes (e.g. multiprocessing) or native extensions that release the GIL. In free-threaded Python, multiple Python threads can run Python code simultaneously on different cores.

parameter

A named entity in a function (or method) definition that specifies an argument (or in some cases, arguments) that the function can accept. There are five kinds of parameter:

  • positional-or-keyword: specifies an argument that can be passed either positionally or as a keyword argument. This is the default kind of parameter, for example foo and bar in the following:

    def func(foo, bar=None): ...
    
  • positional-only: specifies an argument that can be supplied only by position. Positional-only parameters can be defined by including a / character in the parameter list of the function definition after them, for example posonly1 and posonly2 in the following:

    def func(posonly1, posonly2, /, positional_or_keyword): ...
    
  • keyword-only: specifies an argument that can be supplied only by keyword. Keyword-only parameters can be defined by including a single var-positional parameter or bare * in the parameter list of the function definition before them, for example kw_only1 and kw_only2 in the following:

    def func(arg, *, kw_only1, kw_only2): ...
    
  • var-positional: specifies that an arbitrary sequence of positional arguments can be provided (in addition to any positional arguments already accepted by other parameters). Such a parameter can be defined by prepending the parameter name with *, for example args in the following:

    def func(*args, **kwargs): ...
    
  • var-keyword: specifies that arbitrarily many keyword arguments can be provided (in addition to any keyword arguments already accepted by other parameters). Such a parameter can be defined by prepending the parameter name with **, for example kwargs in the example above.

Parameters can specify both optional and required arguments, as well as default values for some optional arguments.

See also the argument glossary entry, the FAQ question on the difference between arguments and parameters, the inspect.Parameter class, the Function definitions section, and PEP 362.

per-object lock

A lock associated with an individual object instance rather than a global lock shared across all objects. In free-threaded Python, built-in types like dict and list use per-object locks to allow concurrent operations on different objects while serializing operations on the same object. Operations that hold the per-object lock prevent other locking operations on the same object from proceeding, but do not block lock-free operations.

path entry

A single location on the import path which the path based finder consults to find modules for importing.

path entry finder

A finder returned by a callable on sys.path_hooks (i.e. a path entry hook) which knows how to locate modules given a path entry.

See importlib.abc.PathEntryFinder for the methods that path entry finders implement.

path entry hook

A callable on the sys.path_hooks list which returns a path entry finder if it knows how to find modules on a specific path entry.

path based finder

One of the default meta path finders which searches an import path for modules.

path-like object

An object representing a file system path. A path-like object is either a str or bytes object representing a path, or an object implementing the os.PathLike protocol. An object that supports the os.PathLike protocol can be converted to a str or bytes file system path by calling the os.fspath() function; os.fsdecode() and os.fsencode() can be used to guarantee a str or bytes result instead, respectively. Introduced by PEP 519.

PEP

Python Enhancement Proposal. A PEP is a design document providing information to the Python community, or describing a new feature for Python or its processes or environment. PEPs should provide a concise technical specification and a rationale for proposed features.

PEPs are intended to be the primary mechanisms for proposing major new features, for collecting community input on an issue, and for documenting the design decisions that have gone into Python. The PEP author is responsible for building consensus within the community and documenting dissenting opinions.

See PEP 1.

portion

A set of files in a single directory (possibly stored in a zip file) that contribute to a namespace package, as defined in PEP 420.

positional argument

See argument.

provisional API

A provisional API is one which has been deliberately excluded from the standard library’s backwards compatibility guarantees. While major changes to such interfaces are not expected, as long as they are marked provisional, backwards incompatible changes (up to and including removal of the interface) may occur if deemed necessary by core developers. Such changes will not be made gratuitously – they will occur only if serious fundamental flaws are uncovered that were missed prior to the inclusion of the API.

Even for provisional APIs, backwards incompatible changes are seen as a «solution of last resort» - every attempt will still be made to find a backwards compatible resolution to any identified problems.

This process allows the standard library to continue to evolve over time, without locking in problematic design errors for extended periods of time. See PEP 411 for more details.

provisional package

See provisional API.

Python 3000

Nickname for the Python 3.x release line (coined long ago when the release of version 3 was something in the distant future.) This is also abbreviated «Py3k».

Pythonic

An idea or piece of code which closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages. For example, a common idiom in Python is to loop over all elements of an iterable using a for statement. Many other languages don’t have this type of construct, so people unfamiliar with Python sometimes use a numerical counter instead:

for i in range(len(food)):
    print(food[i])

As opposed to the cleaner, Pythonic method:

for piece in food:
    print(piece)
qualified name

A dotted name showing the «path» from a module’s global scope to a class, function or method defined in that module, as defined in PEP 3155. For top-level functions and classes, the qualified name is the same as the object’s name:

>>> class C:
...     class D:
...         def meth(self):
...             pass
...
>>> C.__qualname__
'C'
>>> C.D.__qualname__
'C.D'
>>> C.D.meth.__qualname__
'C.D.meth'

When used to refer to modules, the fully qualified name means the entire dotted path to the module, including any parent packages, e.g. email.mime.text:

>>> import email.mime.text
>>> email.mime.text.__name__
'email.mime.text'
race condition

A condition of a program where the behavior depends on the relative timing or ordering of events, particularly in multi-threaded programs. Race conditions can lead to non-deterministic behavior and bugs that are difficult to reproduce. A data race is a specific type of race condition involving unsynchronized access to shared memory. The LBYL coding style is particularly susceptible to race conditions in multi-threaded code. Using locks and other synchronization primitives helps prevent race conditions.

reference count

The number of references to an object. When the reference count of an object drops to zero, it is deallocated. Some objects are immortal and have reference counts that are never modified, and therefore the objects are never deallocated. Reference counting is generally not visible to Python code, but it is a key element of the CPython implementation. Programmers can call the sys.getrefcount() function to return the reference count for a particular object.

In CPython, reference counts are not considered to be stable or well-defined values; the number of references to an object, and how that number is affected by Python code, may be different between versions.

regular package

A traditional package, such as a directory containing an __init__.py file.

See also namespace package.

реентерабельность

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

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

Для блокировок в Python threading.RLock (реентерабельная блокировка) является реентерабельной — поток, уже владеющий блокировкой, может снова захватить её без блокировки. В отличие от неё, threading.Lock не является реентерабельной — попытка дважды захватить её из одного и того же потока приведёт к взаимной блокировке.

См. также блокировка и взаимная блокировка.

REPL

An acronym for the «read–eval–print loop», another name for the interactive interpreter shell.

__slots__

A declaration inside a class that saves memory by pre-declaring space for instance attributes and eliminating instance dictionaries. Though popular, the technique is somewhat tricky to get right and is best reserved for rare cases where there are large numbers of instances in a memory-critical application.

sequence

An iterable which supports efficient element access using integer indices via the __getitem__() special method and defines a __len__() method that returns the length of the sequence. Some built-in sequence types are list, str, tuple, and bytes. Note that dict also supports __getitem__() and __len__(), but is considered a mapping rather than a sequence because the lookups use arbitrary hashable keys rather than integers.

The collections.abc.Sequence abstract base class defines a much richer interface that goes beyond just __getitem__() and __len__(), adding count(), index(), __contains__(), and __reversed__(). Types that implement this expanded interface can be registered explicitly using register(). For more documentation on sequence methods generally, see Common Sequence Operations.

set comprehension

A compact way to process all or part of the elements in an iterable and return a set with the results. results = {c for c in 'abracadabra' if c not in 'abc'} generates the set of strings {'r', 'd'}. See Displays for lists, sets and dictionaries.

single dispatch

A form of generic function dispatch where the implementation is chosen based on the type of a single argument.

срез

Объект типа slice, используемый для описания части последовательности. Для создания объекта среза используется специальный синтаксис срезов при обращении к элементам с помощью двоеточий в квадратных скобках, например variable_name[1:3:5].

soft deprecated

A soft deprecated API should not be used in new code, but it is safe for already existing code to use it. The API remains documented and tested, but will not be enhanced further.

Soft deprecation, unlike normal deprecation, does not plan on removing the API and will not emit warnings.

See PEP 387: Soft Deprecation.

special method

A method that is called implicitly by Python to execute a certain operation on a type, such as addition. Such methods have names starting and ending with double underscores. Special methods are documented in Special method names.

standard library

The collection of packages, modules and extension modules distributed as a part of the official Python interpreter package. The exact membership of the collection may vary based on platform, available system libraries, or other criteria. Documentation can be found at The Python Standard Library.

See also sys.stdlib_module_names for a list of all possible standard library module names.

инструкция

Инструкция является частью набора инструкций («блока» кода). Инструкция представляет собой либо выражение, либо одну из конструкций с ключевым словом, таких как if, while или for.

static type checker

An external tool that reads Python code and analyzes it, looking for issues such as incorrect types. See also type hints and the typing module.

stdlib

An abbreviation of standard library.

steal

In Python’s C API, «stealing» an argument means that ownership of the argument is transferred to the called function. The caller must not use that reference after the call. Generally, functions that «steal» an argument do so even if they fail.

See Reference Count Details for a full explanation.

strong reference

In Python’s C API, a strong reference is a reference to an object which is owned by the code holding the reference. The strong reference is taken by calling Py_INCREF() when the reference is created and released with Py_DECREF() when the reference is deleted.

The Py_NewRef() function can be used to create a strong reference to an object. Usually, the Py_DECREF() function must be called on the strong reference before exiting the scope of the strong reference, to avoid leaking one reference.

See also borrowed reference.

индексатор

Выражение в квадратных скобках при обращении к элементу, например 3 в items[3]. Обычно используется для выбора элемента контейнера. При обращении к отображению индексатор также называется ключом, а при обращении к последовательностииндексом.

synchronization primitive

A basic building block for coordinating (synchronizing) the execution of multiple threads to ensure thread-safe access to shared resources. Python’s threading module provides several synchronization primitives including Lock, RLock, Semaphore, Condition, Event, and Barrier. Additionally, the queue module provides multi-producer, multi-consumer queues that are especially useful in multithreaded programs. These primitives help prevent race conditions and coordinate thread execution. See also lock.

t-string
t-strings

String literals prefixed with t or T are commonly called «t-strings» which is short for template string literals.

text encoding

A string in Python is a sequence of Unicode code points (in range U+0000U+10FFFF). To store or transfer a string, it needs to be serialized as a sequence of bytes.

Serializing a string into a sequence of bytes is known as «encoding», and recreating the string from the sequence of bytes is known as «decoding».

There are a variety of different text serialization codecs, which are collectively referred to as «text encodings».

text file

A file object able to read and write str objects. Often, a text file actually accesses a byte-oriented datastream and handles the text encoding automatically. Examples of text files are files opened in text mode ('r' or 'w'), sys.stdin, sys.stdout, and instances of io.StringIO.

See also binary file for a file object able to read and write bytes-like objects.

thread state

The information used by the CPython runtime to run in an OS thread. For example, this includes the current exception, if any, and the state of the bytecode interpreter.

Each thread state is bound to a single OS thread, but threads may have many thread states available. At most, one of them may be attached at once.

An attached thread state is required to call most of Python’s C API, unless a function explicitly documents otherwise. The bytecode interpreter only runs under an attached thread state.

Each thread state belongs to a single interpreter, but each interpreter may have many thread states, including multiple for the same OS thread. Thread states from multiple interpreters may be bound to the same thread, but only one can be attached in that thread at any given moment.

See Thread State and the Global Interpreter Lock for more information.

thread-safe

A module, function, or class that behaves correctly when used by multiple threads concurrently. Thread-safe code uses appropriate synchronization primitives like locks to protect shared mutable state, or is designed to avoid shared mutable state entirely. In the free-threaded build, built-in types like dict, list, and set use internal locking to make many operations thread-safe, although thread safety is not necessarily guaranteed. Code that is not thread-safe may experience race conditions and data races when used in multi-threaded programs.

token

A small unit of source code, generated by the lexical analyzer (also called the tokenizer). Names, numbers, strings, operators, newlines and similar are represented by tokens.

The tokenize module exposes Python’s lexical analyzer. The token module contains information on the various types of tokens.

triple-quoted string

A string which is bound by three instances of either a quotation mark (») or an apostrophe („). While they don’t provide any functionality not available with single-quoted strings, they are useful for a number of reasons. They allow you to include unescaped single and double quotes within a string and they can span multiple lines without the use of the continuation character, making them especially useful when writing docstrings.

type

The type of a Python object determines what kind of object it is; every object has a type. An object’s type is accessible as its __class__ attribute or can be retrieved with type(obj).

type alias

A synonym for a type, created by assigning the type to an identifier.

Type aliases are useful for simplifying type hints. For example:

def remove_gray_shades(
        colors: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
    pass

could be made more readable like this:

Color = tuple[int, int, int]

def remove_gray_shades(colors: list[Color]) -> list[Color]:
    pass

See typing and PEP 484, which describe this functionality.

type hint

An annotation that specifies the expected type for a variable, a class attribute, or a function parameter or return value.

Type hints are optional and are not enforced by Python but they are useful to static type checkers. They can also aid IDEs with code completion and refactoring.

Type hints of global variables, class attributes, and functions, but not local variables, can be accessed using typing.get_type_hints().

See typing and PEP 484, which describe this functionality.

universal newlines

A manner of interpreting text streams in which all of the following are recognized as ending a line: the Unix end-of-line convention '\n', the Windows convention '\r\n', and the old Macintosh convention '\r'. See PEP 278 and PEP 3116, as well as bytes.splitlines() for an additional use.

variable annotation

An annotation of a variable or a class attribute.

When annotating a variable or a class attribute, assignment is optional:

class C:
    field: 'annotation'

Variable annotations are usually used for type hints: for example this variable is expected to take int values:

count: int = 0

Variable annotation syntax is explained in section Аннотированные инструкции присваивания.

See function annotation, PEP 484 and PEP 526, which describe this functionality. Also see Annotations Best Practices for best practices on working with annotations.

virtual environment

A cooperatively isolated runtime environment that allows Python users and applications to install and upgrade Python distribution packages without interfering with the behaviour of other Python applications running on the same system.

See also venv.

virtual machine

A computer defined entirely in software. Python’s virtual machine executes the bytecode emitted by the bytecode compiler.

walrus operator

A light-hearted way to refer to the assignment expression operator := because it looks a bit like a walrus if you turn your head.

Zen of Python

Listing of Python design principles and philosophies that are helpful in understanding and using the language. The listing can be found by typing «import this» at the interactive prompt.