> **Источник:** https://python-all.ru/3.16/whatsnew/3.16.html
>
> «Документация Python на русском» – неофициальный перевод официальной документации Python: версии от 2.6 до 3.16, полнотекстовый поиск, английский оригинал рядом с переводом. Эта Markdown-версия страницы предназначена для работы с LLM: вставьте её в ChatGPT, Claude или Cursor.

---

# Что нового в Python 3.16

**Редактор:**

Уточняется

В этой статье рассматриваются новые возможности Python 3.16 по сравнению с версией 3.15.

Полные сведения см. в [журнале изменений](https://python-all.ru/3.16/whatsnew/changelog.html#changelog).

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

## Краткое описание – основные возможности выпуска

## Новые возможности

## Прочие изменения в языке

## Новые модули

- Пока нет.

## Улучшенные модули

### curses

- Добавлена поддержка нескольких терминалов в модуль [`curses`](https://python-all.ru/3.16/library/curses.html#module-curses): новые функции [`curses.newterm()`](https://python-all.ru/3.16/library/curses.html#curses.newterm), [`curses.set_term()`](https://python-all.ru/3.16/library/curses.html#curses.set_term) и [`curses.new_prescr()`](https://python-all.ru/3.16/library/curses.html#curses.new_prescr), соответствующий объект [screen](https://python-all.ru/3.16/library/curses.html#curses-screen-objects) и метод [`window.use()`](https://python-all.ru/3.16/library/curses.html#curses.window.use). (Автор: Serhiy Storchaka; [gh-90092](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Методы окон [`curses`](https://python-all.ru/3.16/library/curses.html#module-curses) для работы с символьными ячейками теперь принимают полную символьную ячейку – пробельный символ, за которым необязательно следуют комбинирующие символы – помимо одного целого числа или байтового символа. Это затрагивает [`addch()`](https://python-all.ru/3.16/library/curses.html#curses.window.addch), [`bkgd()`](https://python-all.ru/3.16/library/curses.html#curses.window.bkgd), [`bkgdset()`](https://python-all.ru/3.16/library/curses.html#curses.window.bkgdset), [`border()`](https://python-all.ru/3.16/library/curses.html#curses.window.border), [`box()`](https://python-all.ru/3.16/library/curses.html#curses.window.box), [`echochar()`](https://python-all.ru/3.16/library/curses.html#curses.window.echochar), [`hline()`](https://python-all.ru/3.16/library/curses.html#curses.window.hline), [`insch()`](https://python-all.ru/3.16/library/curses.html#curses.window.insch) и [`vline()`](https://python-all.ru/3.16/library/curses.html#curses.window.vline). Также добавлены методы чтения широких символов [`get_wstr()`](https://python-all.ru/3.16/library/curses.html#curses.window.get_wstr) и [`in_wstr()`](https://python-all.ru/3.16/library/curses.html#curses.window.in_wstr), аналоги [`getstr()`](https://python-all.ru/3.16/library/curses.html#curses.window.getstr) и [`instr()`](https://python-all.ru/3.16/library/curses.html#curses.window.instr), возвращающие [`str`](https://python-all.ru/3.16/library/stdtypes.html#str) вместо [`bytes`](https://python-all.ru/3.16/library/stdtypes.html#bytes), а также функции модуля [`curses.erasewchar()`](https://python-all.ru/3.16/library/curses.html#curses.erasewchar), [`curses.killwchar()`](https://python-all.ru/3.16/library/curses.html#curses.killwchar) и [`curses.wunctrl()`](https://python-all.ru/3.16/library/curses.html#curses.wunctrl) – широкосимвольные аналоги [`curses.erasechar()`](https://python-all.ru/3.16/library/curses.html#curses.erasechar), [`curses.killchar()`](https://python-all.ru/3.16/library/curses.html#curses.killchar) и [`curses.unctrl()`](https://python-all.ru/3.16/library/curses.html#curses.unctrl). В узкой сборке (не ncursesw) символьная ячейка содержит один символ без комбинирующих знаков, представимый в виде одного байта в кодировке окна, а `in_wstr()` возвращает его декодированный текст. (Автор: Serhiy Storchaka; [gh-151757](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Функции и методы широких символов [`curses`](https://python-all.ru/3.16/library/curses.html#module-curses) – [`get_wch()`](https://python-all.ru/3.16/library/curses.html#curses.window.get_wch), [`get_wstr()`](https://python-all.ru/3.16/library/curses.html#curses.window.get_wstr), [`curses.unget_wch()`](https://python-all.ru/3.16/library/curses.html#curses.unget_wch), [`curses.erasewchar()`](https://python-all.ru/3.16/library/curses.html#curses.erasewchar), [`curses.killwchar()`](https://python-all.ru/3.16/library/curses.html#curses.killwchar) и [`curses.wunctrl()`](https://python-all.ru/3.16/library/curses.html#curses.wunctrl) – теперь также работают, когда Python собран без библиотеки curses, поддерживающей широкие символы, в 8-битной локали, где каждый символ представляет собой один байт в соответствующей кодировке. [`curses.ungetch()`](https://python-all.ru/3.16/library/curses.html#curses.ungetch) теперь также принимает строку из одного символа, например `curses.unget_wch()`; в широкосимвольной сборке это может быть любой символ (ранее многобайтовый символ вызывал [`OverflowError`](https://python-all.ru/3.16/library/exceptions.html#OverflowError)). (Автор: Serhiy Storchaka; [gh-152470](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлен [`curses.nofilter()`](https://python-all.ru/3.16/library/curses.html#curses.nofilter), отменяющий действие [`curses.filter()`](https://python-all.ru/3.16/library/curses.html#curses.filter). (Автор: Serhiy Storchaka; [gh-151744](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлены функции [`curses`](https://python-all.ru/3.16/library/curses.html#module-curses): [`curses.alloc_pair()`](https://python-all.ru/3.16/library/curses.html#curses.alloc_pair), [`curses.find_pair()`](https://python-all.ru/3.16/library/curses.html#curses.find_pair), [`curses.free_pair()`](https://python-all.ru/3.16/library/curses.html#curses.free_pair) и [`curses.reset_color_pairs()`](https://python-all.ru/3.16/library/curses.html#curses.reset_color_pairs) для динамического управления цветовыми парами, доступные при сборке с широкосимвольной ncurses с поддержкой расширенных цветов. (Автор: Serhiy Storchaka; [gh-151774](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлены функции [`curses`](https://python-all.ru/3.16/library/curses.html#module-curses) и методы окон, сообщающие состояние, которое ранее можно было только установить, например [`curses.window.is_keypad()`](https://python-all.ru/3.16/library/curses.html#curses.window.is_keypad), [`curses.window.getparent()`](https://python-all.ru/3.16/library/curses.html#curses.window.getparent) и [`curses.is_cbreak()`](https://python-all.ru/3.16/library/curses.html#curses.is_cbreak), доступные при сборке с ncurses с `NCURSES_EXT_FUNCS`. (Автор: Serhiy Storchaka; [gh-151776](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлены методы окна [`curses`](https://python-all.ru/3.16/library/curses.html#module-curses): [`attr_get()`](https://python-all.ru/3.16/library/curses.html#curses.window.attr_get), [`attr_set()`](https://python-all.ru/3.16/library/curses.html#curses.window.attr_set), [`attr_on()`](https://python-all.ru/3.16/library/curses.html#curses.window.attr_on), [`attr_off()`](https://python-all.ru/3.16/library/curses.html#curses.window.attr_off) и [`color_set()`](https://python-all.ru/3.16/library/curses.html#curses.window.color_set), которые передают цветовую пару отдельным аргументом вместо встраивания её в значение атрибута, а также соответствующие константы атрибутов `WA_*`. (Автор: Serhiy Storchaka; [gh-152219](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлен тип [`curses.complexchar`](https://python-all.ru/3.16/library/curses.html#curses.complexchar), представляющий стилизованную символьную ячейку (её текст, атрибуты и цветовую пару), и методы окна [`in_wch()`](https://python-all.ru/3.16/library/curses.html#curses.window.in_wch) и [`getbkgrnd()`](https://python-all.ru/3.16/library/curses.html#curses.window.getbkgrnd), возвращающие такой объект – аналоги [`inch()`](https://python-all.ru/3.16/library/curses.html#curses.window.inch) и [`getbkgd()`](https://python-all.ru/3.16/library/curses.html#curses.window.getbkgd). Методы символьных ячеек, такие как [`addch()`](https://python-all.ru/3.16/library/curses.html#curses.window.addch) и [`border()`](https://python-all.ru/3.16/library/curses.html#curses.window.border), теперь также принимают `complexchar`. Они работают независимо от того, собран ли Python с библиотекой curses, поддерживающей широкие символы; в узкой сборке ячейка содержит один символ, представимый в виде одного байта в кодировке окна (поэтому поддерживаются только 8-битные локали). (Автор: Serhiy Storchaka; [gh-152233](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлен тип [`curses.complexstr`](https://python-all.ru/3.16/library/curses.html#curses.complexstr) – неизменяемая последовательность стилизованных ячеек (строковый аналог [`complexchar`](https://python-all.ru/3.16/library/curses.html#curses.complexchar)) и метод окна [`in_wchstr()`](https://python-all.ru/3.16/library/curses.html#curses.window.in_wchstr), возвращающий такой объект. Методы строковых ячеек [`addstr()`](https://python-all.ru/3.16/library/curses.html#curses.window.addstr), [`addnstr()`](https://python-all.ru/3.16/library/curses.html#curses.window.addnstr), [`insstr()`](https://python-all.ru/3.16/library/curses.html#curses.window.insstr) и [`insnstr()`](https://python-all.ru/3.16/library/curses.html#curses.window.insnstr) теперь также принимают `complexstr`. Как и `complexchar`, он работает независимо от того, собран ли Python с библиотекой curses, поддерживающей широкие символы. (Автор: Serhiy Storchaka; [gh-152233](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлен метод окна [`curses`](https://python-all.ru/3.16/library/curses.html#module-curses): [`dupwin()`](https://python-all.ru/3.16/library/curses.html#curses.window.dupwin), возвращающий новое окно, которое является независимой копией существующего. (Автор: Serhiy Storchaka; [gh-152258](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлены функции [`curses`](https://python-all.ru/3.16/library/curses.html#module-curses): [`scr_dump()`](https://python-all.ru/3.16/library/curses.html#curses.scr_dump), [`scr_restore()`](https://python-all.ru/3.16/library/curses.html#curses.scr_restore), [`scr_init()`](https://python-all.ru/3.16/library/curses.html#curses.scr_init) и [`scr_set()`](https://python-all.ru/3.16/library/curses.html#curses.scr_set), которые сохраняют весь экран в файл и восстанавливают его. (Автор: Serhiy Storchaka; [gh-152260](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлены функции мягких клавиш-меток в модуль [`curses`](https://python-all.ru/3.16/library/curses.html#module-curses), управляющие строкой меток вдоль нижней строки экрана: [`slk_init()`](https://python-all.ru/3.16/library/curses.html#curses.slk_init), [`slk_set()`](https://python-all.ru/3.16/library/curses.html#curses.slk_set), [`slk_label()`](https://python-all.ru/3.16/library/curses.html#curses.slk_label), [`slk_refresh()`](https://python-all.ru/3.16/library/curses.html#curses.slk_refresh), [`slk_noutrefresh()`](https://python-all.ru/3.16/library/curses.html#curses.slk_noutrefresh), [`slk_clear()`](https://python-all.ru/3.16/library/curses.html#curses.slk_clear), [`slk_restore()`](https://python-all.ru/3.16/library/curses.html#curses.slk_restore), [`slk_touch()`](https://python-all.ru/3.16/library/curses.html#curses.slk_touch), функции атрибутов [`slk_attron()`](https://python-all.ru/3.16/library/curses.html#curses.slk_attron), [`slk_attroff()`](https://python-all.ru/3.16/library/curses.html#curses.slk_attroff), [`slk_attrset()`](https://python-all.ru/3.16/library/curses.html#curses.slk_attrset), [`slk_attr()`](https://python-all.ru/3.16/library/curses.html#curses.slk_attr), [`slk_attr_on()`](https://python-all.ru/3.16/library/curses.html#curses.slk_attr_on), [`slk_attr_off()`](https://python-all.ru/3.16/library/curses.html#curses.slk_attr_off), [`slk_attr_set()`](https://python-all.ru/3.16/library/curses.html#curses.slk_attr_set) и [`slk_color()`](https://python-all.ru/3.16/library/curses.html#curses.slk_color). (Автор: Serhiy Storchaka; [gh-152263](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлена функция [`curses.term_attrs()`](https://python-all.ru/3.16/library/curses.html#curses.term_attrs), возвращающая поддерживаемые видеоатрибуты в виде значений [WA\_\*](https://python-all.ru/3.16/library/curses.html#curses-wa-constants) – аналог [`curses.termattrs()`](https://python-all.ru/3.16/library/curses.html#curses.termattrs). (Автор: Serhiy Storchaka; [gh-152332](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлены функции управления клавишами [`curses`](https://python-all.ru/3.16/library/curses.html#module-curses): [`define_key()`](https://python-all.ru/3.16/library/curses.html#curses.define_key), [`key_defined()`](https://python-all.ru/3.16/library/curses.html#curses.key_defined) и [`keyok()`](https://python-all.ru/3.16/library/curses.html#curses.keyok), доступные при сборке с ncurses с `NCURSES_EXT_FUNCS`. (Автор: Serhiy Storchaka; [gh-152334](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлены функция [`curses.has_mouse()`](https://python-all.ru/3.16/library/curses.html#curses.has_mouse) и метод [`curses.window.mouse_trafo()`](https://python-all.ru/3.16/library/curses.html#curses.window.mouse_trafo), завершающие интерфейс мыши [`curses`](https://python-all.ru/3.16/library/curses.html#module-curses). (Автор: Serhiy Storchaka; [gh-152325](https://python-all.ru/3.16/whatsnew/3.16.html).)
- [`curses.textpad.Textbox`](https://python-all.ru/3.16/library/curses.html#curses.textpad.Textbox) теперь поддерживает ввод и считывание всего диапазона Unicode, включая комбинирующие символы, если curses собран с поддержкой широких символов. (Автор: Serhiy Storchaka; [gh-133031](https://python-all.ru/3.16/whatsnew/3.16.html).)

### gzip

- [`gzip.open()`](https://python-all.ru/3.16/library/gzip.html#gzip.open) теперь принимает необязательный аргумент `mtime`, который передаётся конструктору класса [`GzipFile`](https://python-all.ru/3.16/library/gzip.html#gzip.GzipFile). (Автор: Marin Misur; [gh-91372](https://python-all.ru/3.16/whatsnew/3.16.html).)

### io

- Добавлен метод [`io.BytesIO.peek()`](https://python-all.ru/3.16/library/io.html#io.BytesIO.peek) для чтения без перемещения позиции. (Автор: Marcel Martin; [gh-90533](https://python-all.ru/3.16/whatsnew/3.16.html).)

### imaplib

- Добавлен метод [`id()`](https://python-all.ru/3.16/library/imaplib.html#imaplib.IMAP4.id), обёртка для команды `ID` ([**RFC 2971**](https://python-all.ru/3.16/whatsnew/3.16.html)). (Автор: Serhiy Storchaka; [gh-98092](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлен метод [`move()`](https://python-all.ru/3.16/library/imaplib.html#imaplib.IMAP4.move), обёртка для команды `MOVE` ([**RFC 6851**](https://python-all.ru/3.16/whatsnew/3.16.html)). (Автор: Serhiy Storchaka; [gh-77508](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлен метод [`login_plain()`](https://python-all.ru/3.16/library/imaplib.html#imaplib.IMAP4.login_plain), выполняющий аутентификацию с помощью механизма SASL `PLAIN` ([**RFC 4616**](https://python-all.ru/3.16/whatsnew/3.16.html)) и поддерживающий не-ASCII имена пользователей и пароли. (Автор: Przemysław Buczkowski и Serhiy Storchaka; [gh-89869](https://python-all.ru/3.16/whatsnew/3.16.html).)

### logging

- [`TimedRotatingFileHandler`](https://python-all.ru/3.16/library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler) теперь использует время создания вместо времени последнего изменения существующего файла журнала в качестве основы для первой ротации после создания обработчика, если это поддерживается ОС и файловой системой. Это позволяет использовать его в короткоживущих программах, которые запускаются и завершаются до истечения интервала ротации. (Автор: Iván Márton и Serhiy Storchaka; [gh-84649](https://python-all.ru/3.16/whatsnew/3.16.html).)

### lzma

- Добавлена поддержка новых фильтров BCJ ARM64 и RISC-V через `lzma.FILTER_ARM64` и `lzma.FILTER_RISCV`. Обратите внимание, что новые фильтры будут работать только в том случае, если их поддерживает библиотека времени выполнения. Фильтр ARM64 требует `lzma` 5.4.0 или новее, а RISC-V – 5.6.0 или новее. (Автор: Chien Wong; [gh-115988](https://python-all.ru/3.16/whatsnew/3.16.html).)

### math

- Добавлены тригонометрические функции, работающие в единицах полуоборотов, а не радианов. Новые функции [`math.acospi()`](https://python-all.ru/3.16/library/math.html#math.acospi), [`math.asinpi()`](https://python-all.ru/3.16/library/math.html#math.asinpi), [`math.atanpi()`](https://python-all.ru/3.16/library/math.html#math.atanpi) и [`math.atan2pi()`](https://python-all.ru/3.16/library/math.html#math.atan2pi) возвращают углы в полуоборотах. Новые функции [`math.cospi()`](https://python-all.ru/3.16/library/math.html#math.cospi), [`math.sinpi()`](https://python-all.ru/3.16/library/math.html#math.sinpi) и [`math.tanpi()`](https://python-all.ru/3.16/library/math.html#math.tanpi) принимают аргументы в виде углов в полуоборотах. Эти функции рекомендованы стандартом IEEE 754-2019 и стандартизированы в C23. (Автор: Jeff Epler; [gh-150534](https://python-all.ru/3.16/whatsnew/3.16.html).)

### os

- Добавлена [`os.pidfd_getfd()`](https://python-all.ru/3.16/library/os.html#os.pidfd_getfd) для дублирования файлового дескриптора из другого процесса через pidfd. Доступно на Linux 5.6+. (Автор: Maurycy Pawłowski-Wieroński в [gh-149464](https://python-all.ru/3.16/whatsnew/3.16.html).)

### re

- [`re`](https://python-all.ru/3.16/library/re.html#module-re) теперь поддерживает операции над множествами и вложенные множества в символьных классах, как описано в [Unicode Technical Standard #18](https://python-all.ru/3.16/whatsnew/3.16.html): разность множеств (`[A--B]`), пересечение (`[A&&B]`) и объединение (`[A||B]`), где операндом может быть вложенное множество, записанное в квадратных скобках. Например, `[a-z--[aeiou]]` соответствует строчной согласной букве ASCII. (Автор: Serhiy Storchaka в [gh-152100](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Регулярные выражения теперь поддерживают экранирования свойств Unicode `\p{...}` и `\P{...}`, которые сопоставляют символ по свойству Unicode – например, `\p{Lu}` (заглавная буква), `\p{Cased}` или `\p{ASCII}`. Список поддерживаемых свойств см. в [синтаксисе регулярных выражений](https://python-all.ru/3.16/library/re.html#re-syntax). (Автор: Serhiy Storchaka в [gh-95555](https://python-all.ru/3.16/whatsnew/3.16.html).)

### shlex

- Добавлен параметр, передаваемый только по ключу, *force* в [`shlex.quote()`](https://python-all.ru/3.16/library/shlex.html#shlex.quote) для принудительного заключения строки в кавычки, даже если она уже безопасна для оболочки без кавычек. (Автор: Jay Berry в [gh-148846](https://python-all.ru/3.16/whatsnew/3.16.html).)

### tkinter

- Добавлено много методов [`tkinter.ttk.Treeview`](https://python-all.ru/3.16/library/tkinter.ttk.html#tkinter.ttk.Treeview), обёртывающих расширенные команды виджета `ttk::treeview` из Tk 9.1, таких как [`sort()`](https://python-all.ru/3.16/library/tkinter.ttk.html#tkinter.ttk.Treeview.sort), [`search()`](https://python-all.ru/3.16/library/tkinter.ttk.html#tkinter.ttk.Treeview.search), [`expand()`](https://python-all.ru/3.16/library/tkinter.ttk.html#tkinter.ttk.Treeview.expand), [`collapse()`](https://python-all.ru/3.16/library/tkinter.ttk.html#tkinter.ttk.Treeview.collapse), [`hide()`](https://python-all.ru/3.16/library/tkinter.ttk.html#tkinter.ttk.Treeview.hide), [`unhide()`](https://python-all.ru/3.16/library/tkinter.ttk.html#tkinter.ttk.Treeview.unhide), а также методы для фокуса ячейки, выделения и разметки. Методы `expand()` и `collapse()` (без рекурсии) также работают на Tk старше 9.1. (Автор: Serhiy Storchaka в [gh-151910](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлены новые методы `tkinter.Text`: [`edit_canundo()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.Text.edit_canundo) и [`edit_canredo()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.Text.edit_canredo), которые возвращают, возможна ли отмена (undo) или повтор (redo). (Автор: Serhiy Storchaka в [gh-151674](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлены новые методы `tkinter.Text`: [`sync()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.Text.sync) и [`pendingsync()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.Text.pendingsync), которые управляют синхронизацией отображаемого представления с базовым текстом и сообщают о ней. (Автор: Serhiy Storchaka в [gh-151675](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлен метод [`ttk.Style.theme_styles`](https://python-all.ru/3.16/library/tkinter.ttk.html#tkinter.ttk.Style.theme_styles), который возвращает список стилей, определённых в теме. (Автор: Serhiy Storchaka в [gh-151920](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлены новые методы `tkinter.Canvas`: [`rchars()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.Canvas.rchars), который заменяет текст или координаты элементов холста, и [`rotate()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.Canvas.rotate), который вращает координаты элементов холста. (Автор: Serhiy Storchaka в [gh-151876](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлен метод `validate()` в виджеты `tkinter.Entry` и `tkinter.Spinbox`, который принудительно выполняет проверочную команду. (Автор: Serhiy Storchaka в [gh-151878](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлены метод [`tkinter.Menu.postcascade()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.Menu.postcascade), а также методы [`tk_scaling()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.Misc.tk_scaling) и [`tk_inactive()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.Misc.tk_inactive), которые соответственно запрашивают или устанавливают коэффициент масштабирования экрана и сообщают время бездействия пользователя. (Автор: Serhiy Storchaka в [gh-151881](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлены новые методы управления окнами: [`winfo_isdark()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.Misc.winfo_isdark) (обнаружение тёмной темы), [`wm_iconbadge()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.Wm.wm_iconbadge) (значок приложения) и [`wm_stackorder()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.Wm.wm_stackorder) (порядок расположения окон верхнего уровня). (Автор: Serhiy Storchaka в [gh-151874](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлены методы [`tk_appname()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.Misc.tk_appname), [`tk_useinputmethods()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.Misc.tk_useinputmethods) и [`tk_caret()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.Misc.tk_caret), предоставляющие доступ к имени отправки приложения, состоянию X Input Methods и положению курсора метода ввода. (Автор: Serhiy Storchaka в [gh-151886](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлена поддержка дополнительных опций в методах `tkinter.PhotoImage`: параметр *format* в [`put()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.PhotoImage.put), параметр *metadata* в `put()`, параметры [`read()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.PhotoImage.read), [`write()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.PhotoImage.write) и [`data()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.PhotoImage.data), а также параметр *withalpha* в [`get()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.PhotoImage.get). (Автор: Serhiy Storchaka в [gh-151890](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавлен метод [`redither()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.PhotoImage.redither), который пересчитывает изображение с дизерингом, когда его данные были переданы частями. (Автор: Serhiy Storchaka в [gh-151888](https://python-all.ru/3.16/whatsnew/3.16.html).)
- [`tkinter.OptionMenu`](https://python-all.ru/3.16/library/tkinter.html#tkinter.OptionMenu) теперь принимает произвольные опции `tkinter.Menubutton` в качестве именованных аргументов, которые также могут переопределять его внешний вид по умолчанию. (Автор: Serhiy Storchaka в [gh-101284](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Диалоги [`tkinter.simpledialog`](https://python-all.ru/3.16/library/dialog.html#module-tkinter.simpledialog) были модернизированы, чтобы соответствовать внешнему виду и поведению нативных диалогов Tk. Диалоги `tkinter.simpledialog.SimpleDialog`, [`askinteger()`](https://python-all.ru/3.16/library/dialog.html#tkinter.simpledialog.askinteger), [`askfloat()`](https://python-all.ru/3.16/library/dialog.html#tkinter.simpledialog.askfloat) и [`askstring()`](https://python-all.ru/3.16/library/dialog.html#tkinter.simpledialog.askstring) теперь строятся из тематических виджетов [`tkinter.ttk`](https://python-all.ru/3.16/library/tkinter.ttk.html#module-tkinter.ttk) вместо классических виджетов [`tkinter`](https://python-all.ru/3.16/library/tkinter.html#module-tkinter); базовый класс `tkinter.simpledialog.Dialog` по-прежнему по умолчанию использует классические виджеты для совместимости. Оба класса `Dialog` и `SimpleDialog` получили параметр *use\_ttk*, который выбирает между классическими виджетами Tk и тематическими виджетами ttk. `SimpleDialog` также получил параметры *bitmap* и *detail*, рисует стандартные значки тематическими изображениями в версии ttk и принимает сопоставления параметров кнопок как записи *buttons*. (Автор: Serhiy Storchaka в [gh-59396](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Диалог `tkinter.filedialog.FileDialog` и его подклассы `tkinter.filedialog.LoadFileDialog` и `tkinter.filedialog.SaveFileDialog` теперь по умолчанию строятся из тематических виджетов [`tkinter.ttk`](https://python-all.ru/3.16/library/tkinter.ttk.html#module-tkinter.ttk) вместо классических виджетов [`tkinter`](https://python-all.ru/3.16/library/tkinter.html#module-tkinter) и получили параметр *use\_ttk* для выбора между ними. (Автор: Serhiy Storchaka в [gh-59396](https://python-all.ru/3.16/whatsnew/3.16.html).)
- [`tkinter.font.Font`](https://python-all.ru/3.16/library/tkinter.font.html#tkinter.font.Font) теперь может оборачивать описание шрифта без создания нового именованного шрифта, передавая его как *font* с помощью `exists=True` и без *name*. Это позволяет избежать потери точности в [`actual()`](https://python-all.ru/3.16/library/tkinter.font.html#tkinter.font.Font.actual), [`measure()`](https://python-all.ru/3.16/library/tkinter.font.html#tkinter.font.Font.measure) и [`metrics()`](https://python-all.ru/3.16/library/tkinter.font.html#tkinter.font.Font.metrics). (Автор: Serhiy Storchaka в [gh-143990](https://python-all.ru/3.16/whatsnew/3.16.html).)

### xml

- Добавлена поддержка множества многобайтовых кодировок в [`XML parser`](https://python-all.ru/3.16/library/pyexpat.html#module-xml.parsers.expat): «cp932», «cp949», «cp950», «Big5», «EUC-JP», «GB2312», «GBK», «johab» и «Shift\_JIS». Добавлена частичная поддержка (только символы BMP) для многобайтовых кодировок «Big5-HKSCS», «EUC\_JIS-2004», «EUC\_JISX0213», «Shift\_JIS-2004», «Shift\_JISX0213», «utf-8-sig» и нестандартных псевдонимов, таких как «UTF8» (без дефиса). Теперь парсер вызывает [`ValueError`](https://python-all.ru/3.16/library/exceptions.html#ValueError) для известных неподдерживаемых многобайтовых кодировок, таких как «ISO-2022-JP» или «raw-unicode-escape», вместо того чтобы завершаться ошибкой позже при встрече с не-ASCII данными. (Автор: Serhiy Storchaka в [gh-62259](https://python-all.ru/3.16/whatsnew/3.16.html).)

### zipfile

- Добавлены [`ZipFile.remove()`](https://python-all.ru/3.16/library/zipfile.html#zipfile.ZipFile.remove) для удаления элемента из центрального каталога архива и [`ZipFile.repack()`](https://python-all.ru/3.16/library/zipfile.html#zipfile.ZipFile.repack) для освобождения места, занятого локальными записями файлов удалённых элементов. (Автор: Danny Lin в [gh-51067](https://python-all.ru/3.16/whatsnew/3.16.html).)

## Оптимизации

### re

- Экранирования символьных классов (`\d`, `\D`, `\s`, `\S`, `\w` и `\W`) вне набора символов, а также наборы символов, содержащие одно такое экранирование (например, `[\d]` или `[^\s]`), теперь компилируются в один опкод `CATEGORY` вместо того, чтобы быть обёрнутыми в блок `IN`. Это ускоряет сопоставление таких шаблонов, как `\d+`, и уменьшает размер скомпилированного байт-кода. (Автор: Serhiy Storchaka в [gh-152033](https://python-all.ru/3.16/whatsnew/3.16.html) и Pieter Eendebak в [gh-152056](https://python-all.ru/3.16/whatsnew/3.16.html).)

### module\_name

- TODO

## Удалено

### annotationlib

- Метод `annotationlib.ForwardRef._evaluate()`, который устарел с Python 3.14. Вместо него используйте [`annotationlib.ForwardRef.evaluate()`](https://python-all.ru/3.16/library/annotationlib.html#annotationlib.ForwardRef.evaluate) или [`typing.evaluate_forward_ref()`](https://python-all.ru/3.16/library/typing.html#typing.evaluate_forward_ref).

### array

- Код формата `'u'` (`wchar_t`), устаревший в документации с Python 3.3 и во время выполнения с Python 3.13. Вместо него используйте код формата `'w'` ([`Py_UCS4`](https://python-all.ru/3.16/c-api/unicode.html#c.Py_UCS4), всегда 4 байта).

### asyncio

- `asyncio.iscoroutinefunction()`, устаревшее с Python 3.14. Вместо него используйте [`inspect.iscoroutinefunction()`](https://python-all.ru/3.16/library/inspect.html#inspect.iscoroutinefunction).
- Система политик цикла событий, включая классы `asyncio.AbstractEventLoopPolicy`, `asyncio.DefaultEventLoopPolicy`, `asyncio.WindowsSelectorEventLoopPolicy` и `asyncio.WindowsProactorEventLoopPolicy`, а также функции `asyncio.get_event_loop_policy()` и `asyncio.set_event_loop_policy()`, устарела с Python 3.14. Вместо неё используйте [`asyncio.run()`](https://python-all.ru/3.16/library/asyncio-runner.html#asyncio.run) или [`asyncio.Runner`](https://python-all.ru/3.16/library/asyncio-runner.html#asyncio.Runner) с собственной *loop\_factory*.

### functools

- Вызов реализации [`functools.reduce()`](https://python-all.ru/3.16/library/functools.html#functools.reduce) на Python с *function* или *sequence* в качестве именованных аргументов устарел начиная с Python 3.14.

### logging

- Поддержка пользовательских обработчиков журнала с аргументом *strm* устарела и будет удалена в Python 3.16. Вместо этого определяйте обработчики с аргументом *stream*.

### mimetypes

- Допустимые расширения начинаются с точки «.» или пусты для [`mimetypes.MimeTypes.add_type()`](https://python-all.ru/3.16/library/mimetypes.html#mimetypes.MimeTypes.add_type). Расширения без точки теперь вызывают [`ValueError`](https://python-all.ru/3.16/library/exceptions.html#ValueError).

### shutil

- Исключение `ExecError` устарело с Python 3.14. Оно не использовалось ни одной функцией в `shutil` начиная с Python 3.4. (Автор: Stan Ulbrych в [gh-149567](https://python-all.ru/3.16/whatsnew/3.16.html).)

### symtable

- Метод `symtable.Class.get_methods()` устарел с Python 3.14.

### sys

- Функция `_enablelegacywindowsfsencoding()` устарела с Python 3.13. Вместо неё используйте переменную окружения [`PYTHONLEGACYWINDOWSFSENCODING`](https://python-all.ru/3.16/using/cmdline.html#envvar-PYTHONLEGACYWINDOWSFSENCODING). (Автор: Stan Ulbrych в [gh-149595](https://python-all.ru/3.16/whatsnew/3.16.html).)

### sysconfig

- Функция `sysconfig.expand_makefile_vars()` устарела с Python 3.14. Вместо неё используйте аргумент `vars` функции [`sysconfig.get_paths()`](https://python-all.ru/3.16/library/sysconfig.html#sysconfig.get_paths). (Автор: Stan Ulbrych в [gh-149499](https://python-all.ru/3.16/whatsnew/3.16.html).)

### tarfile

- Недокументированный и неиспользуемый атрибут `tarfile.TarFile.tarfile` устарел начиная с Python 3.13.

## Устарело

### Новые устаревания

- [`abc`](https://python-all.ru/3.16/library/abc.html#module-abc)

  - Мягко устаревшие с Python 3.3 [`abc.abstractclassmethod`](https://python-all.ru/3.16/library/abc.html#abc.abstractclassmethod), [`abc.abstractstaticmethod`](https://python-all.ru/3.16/library/abc.html#abc.abstractstaticmethod) и [`abc.abstractproperty`](https://python-all.ru/3.16/library/abc.html#abc.abstractproperty) теперь вызывают [`DeprecationWarning`](https://python-all.ru/3.16/library/exceptions.html#DeprecationWarning). Эти классы будут удалены в Python 3.21, вместо них используйте [`abc.abstractmethod()`](https://python-all.ru/3.16/library/abc.html#abc.abstractmethod) с [`classmethod()`](https://python-all.ru/3.16/library/functions.html#classmethod), [`staticmethod()`](https://python-all.ru/3.16/library/functions.html#staticmethod) и [`property`](https://python-all.ru/3.16/library/functions.html#property) соответственно.
- [`ast`](https://python-all.ru/3.16/library/ast.html#module-ast):

  - Классы `slice`, `Index`, `ExtSlice`, `Suite`, `Param`, `AugLoad` и `AugStore`, устаревшие с Python 3.9, больше не импортируются `from ast import *` и выдают предупреждение об устаревании при использовании. Эти классы планируется удалить в Python 3.21. Данные типы не создаются парсером и не принимаются генератором кода.
  - Свойство `dims` объектов `ast.Tuple`, устаревшее с Python 3.9, теперь выдает предупреждение об устаревании при использовании. Это свойство планируется удалить в Python 3.21. Вместо него используйте `ast.Tuple.elts`.
- [`struct`](https://python-all.ru/3.16/library/struct.html#module-struct):

  - Мягкое устаревание с Python 3.15, сейчас использование кодов типов `'F'` и `'D'` устарело. Эти коды будут удалены в Python 3.21. Вместо них используйте двухбуквенные формы `'Zf'` и `'Zd'`. (Автор: Sergey B Kirpichev в [gh-121249](https://python-all.ru/3.16/whatsnew/3.16.html).)
- [`tempfile`](https://python-all.ru/3.16/library/tempfile.html#module-tempfile)

  - Приватное имя `tempfile._TemporaryFileWrapper` устарело и будет удалено в Python 3.21. Вместо него используйте новое публичное [`tempfile.TemporaryFileWrapper`](https://python-all.ru/3.16/library/tempfile.html#tempfile.TemporaryFileWrapper), которое является типом возврата [`tempfile.NamedTemporaryFile()`](https://python-all.ru/3.16/library/tempfile.html#tempfile.NamedTemporaryFile).

### Запланировано к удалению в Python 3.17

- [`datetime`](https://python-all.ru/3.16/library/datetime.html#module-datetime):

  - [`strptime()`](https://python-all.ru/3.16/library/datetime.html#datetime.datetime.strptime) вызовы со строкой формата, содержащей `%e` (день месяца) без указания года. Это объявлено устаревшим начиная с Python 3.15. (Автор: Stan Ulbrych в [gh-70647](https://python-all.ru/3.16/whatsnew/3.16.html).)
- [`collections.abc`](https://python-all.ru/3.16/library/collections.abc.html#module-collections.abc):

  - [`collections.abc.ByteString`](https://python-all.ru/3.16/library/collections.abc.html#collections.abc.ByteString) запланирован к удалению в Python 3.17.

    Используйте `isinstance(obj, collections.abc.Buffer)` для проверки, реализует ли `obj` [протокол буфера](https://python-all.ru/3.16/c-api/buffer.html#bufferobjects) во время выполнения. Для использования в аннотациях типов используйте [`Buffer`](https://python-all.ru/3.16/library/collections.abc.html#collections.abc.Buffer) или объединение, которое явно указывает типы, поддерживаемые вашим кодом (например, `bytes | bytearray | memoryview`).

    `ByteString` изначально задумывался как абстрактный класс, который должен был служить супертипом как для [`bytes`](https://python-all.ru/3.16/library/stdtypes.html#bytes), так и для [`bytearray`](https://python-all.ru/3.16/library/stdtypes.html#bytearray). Однако, поскольку у ABC никогда не было методов, знание того, что объект является экземпляром `ByteString`, никогда не давало полезной информации об объекте. Другие распространённые типы буферов, такие как [`memoryview`](https://python-all.ru/3.16/library/stdtypes.html#memoryview), также никогда не рассматривались как подтипы `ByteString` (ни во время выполнения, ни статическими проверками типов).

    См. [**PEP 688**](https://python-all.ru/3.16/whatsnew/3.16.html) для получения подробностей. (Автор: Shantanu Jain в [gh-91896](https://python-all.ru/3.16/whatsnew/3.16.html).)
- [`encodings`](https://python-all.ru/3.16/library/codecs.html#module-encodings):

  - Передача *кодировок*, не являющихся ASCII, в [`encodings.normalize_encoding()`](https://python-all.ru/3.16/library/codecs.html#encodings.normalize_encoding) объявлена устаревшей и запланирована к удалению в Python 3.17. (Автор: Stan Ulbrych в [gh-136702](https://python-all.ru/3.16/whatsnew/3.16.html).)
- [`webbrowser`](https://python-all.ru/3.16/library/webbrowser.html#module-webbrowser):

  - `webbrowser.MacOSXOSAScript` объявлен устаревшим в пользу `webbrowser.MacOS`. ([gh-137586](https://python-all.ru/3.16/whatsnew/3.16.html))
- [`typing`](https://python-all.ru/3.16/library/typing.html#module-typing):

  - До Python 3.14 старые объединения реализовывались с помощью приватного класса `typing._UnionGenericAlias`. Этот класс больше не нужен для реализации, но он сохранён для обратной совместимости, его удаление запланировано на Python 3.17. Пользователям следует использовать документированные вспомогательные средства интроспекции, такие как [`typing.get_origin()`](https://python-all.ru/3.16/library/typing.html#typing.get_origin) и [`typing.get_args()`](https://python-all.ru/3.16/library/typing.html#typing.get_args), вместо того чтобы полагаться на детали приватной реализации.
  - [`typing.ByteString`](https://python-all.ru/3.16/library/typing.html#typing.ByteString), устаревший с Python 3.9, запланирован к удалению в Python 3.17.

    Используйте `isinstance(obj, collections.abc.Buffer)` для проверки, реализует ли `obj` [протокол буфера](https://python-all.ru/3.16/c-api/buffer.html#bufferobjects) во время выполнения. Для использования в аннотациях типов используйте [`Buffer`](https://python-all.ru/3.16/library/collections.abc.html#collections.abc.Buffer) или объединение, которое явно указывает типы, поддерживаемые вашим кодом (например, `bytes | bytearray | memoryview`).

    `ByteString` изначально задумывался как абстрактный класс, который должен был служить супертипом как для [`bytes`](https://python-all.ru/3.16/library/stdtypes.html#bytes), так и для [`bytearray`](https://python-all.ru/3.16/library/stdtypes.html#bytearray). Однако, поскольку у ABC никогда не было методов, знание того, что объект является экземпляром `ByteString`, никогда не давало полезной информации об объекте. Другие распространённые типы буферов, такие как [`memoryview`](https://python-all.ru/3.16/library/stdtypes.html#memoryview), также никогда не рассматривались как подтипы `ByteString` (ни во время выполнения, ни статическими проверками типов).

    См. [**PEP 688**](https://python-all.ru/3.16/whatsnew/3.16.html) для получения подробностей. (Автор: Shantanu Jain в [gh-91896](https://python-all.ru/3.16/whatsnew/3.16.html).)
- [`tkinter`](https://python-all.ru/3.16/library/tkinter.html#module-tkinter):

  - Методы `tkinter.Variable`: `trace_variable()`, `trace()` (псевдоним `trace_variable()`), `trace_vdelete()` и `trace_vinfo()`, устаревшие с Python 3.14, запланированы к удалению в Python 3.17. Используйте `trace_add()`, `trace_remove()` и `trace_info()` вместо них. (Автор: Serhiy Storchaka в [gh-120220](https://python-all.ru/3.16/whatsnew/3.16.html).)

### Запланировано удаление в Python 3.18

- Больше не принимает логическое значение, если ожидается файловый дескриптор. (Автор: Serhiy Storchaka в [gh-82626](https://python-all.ru/3.16/whatsnew/3.16.html).)
- [`decimal`](https://python-all.ru/3.16/library/decimal.html#module-decimal):

  - Нестандартный и недокументированный [`Decimal`](https://python-all.ru/3.16/library/decimal.html#decimal.Decimal) спецификатор формата `'N'`, который поддерживается только в реализации C модуля `decimal`, устарел с Python 3.13. (Автор: Serhiy Storchaka в [gh-89902](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Устаревшие элементы, определённые [**PEP 829**](https://python-all.ru/3.16/whatsnew/3.16.html):

  - Строки `import` в файлах `name.pth` молча игнорируются.

  (Вклад: Barry Warsaw в [gh-148641](https://python-all.ru/3.16/whatsnew/3.16.html).)

### Запланировано к удалению в Python 3.19

- [`ctypes`](https://python-all.ru/3.16/library/ctypes.html#module-ctypes):

  - Неявное переключение на совместимую с MSVC структуру путём установки [`_pack_`](https://python-all.ru/3.16/library/ctypes.html#ctypes.Structure._pack_) без [`_layout_`](https://python-all.ru/3.16/library/ctypes.html#ctypes.Structure._layout_) на платформах, отличных от Windows.
- [`hashlib`](https://python-all.ru/3.16/library/hashlib.html#module-hashlib):

  - В конструкторах хеш-функций, таких как [`new()`](https://python-all.ru/3.16/library/hashlib.html#hashlib.new), или прямых конструкторах, названных по имени хеша, таких как [`md5()`](https://python-all.ru/3.16/library/hashlib.html#hashlib.md5) и [`sha256()`](https://python-all.ru/3.16/library/hashlib.html#hashlib.sha256), их необязательный параметр начальных данных мог также передаваться как именованный аргумент с именем `data=` или `string=` в различных реализациях `hashlib`.

    Поддержка имени именованного аргумента `string` теперь устарела и будет удалена в Python 3.19.

    До Python 3.13 именованный параметр `string` не поддерживался правильно в зависимости от реализации хеш-функций на стороне бэкенда. Предпочтительно передавать начальные данные как позиционный аргумент для максимальной обратной совместимости.
- [`http.cookies`](https://python-all.ru/3.16/library/http.cookies.html#module-http.cookies):

  - [`http.cookies.Morsel.js_output()`](https://python-all.ru/3.16/library/http.cookies.html#http.cookies.Morsel.js_output) устарело и будет удалено в Python 3.19.
  - [`http.cookies.BaseCookie.js_output()`](https://python-all.ru/3.16/library/http.cookies.html#http.cookies.BaseCookie.js_output) устарело и будет удалено в Python 3.19.
- [`imaplib`](https://python-all.ru/3.16/library/imaplib.html#module-imaplib):

  - Изменение [`IMAP4.file`](https://python-all.ru/3.16/library/imaplib.html#imaplib.IMAP4.file) теперь устарело и будет удалено в Python 3.19. Это свойство теперь не используется, и изменение его значения не приводит к автоматическому закрытию текущего файла.

    До Python 3.14 это свойство использовалось для реализации соответствующих методов `read()` и `readline()` для [`IMAP4`](https://python-all.ru/3.16/library/imaplib.html#imaplib.IMAP4), но с тех пор это уже не так.

### Ожидается удаление в Python 3.20

- Вызов метода `__new__()` объекта [`struct.Struct`](https://python-all.ru/3.16/library/struct.html#struct.Struct) без аргумента *format* устарел и будет удалён в Python 3.20. Вызов [`__init__()`](https://python-all.ru/3.16/reference/datamodel.html#object.__init__) метода для инициализированных объектов `Struct` устарел и будет удалён в Python 3.20.

  (Вклад: Sergey B Kirpichev и Serhiy Storchaka в [gh-143715](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Атрибуты `__version__`, `version` и `VERSION` были объявлены устаревшими в этих модулях стандартной библиотеки и будут удалены в Python 3.20. Вместо них используйте [`sys.version_info`](https://python-all.ru/3.16/library/sys.html#sys.version_info).

  - [`argparse`](https://python-all.ru/3.16/library/argparse.html#module-argparse)
  - [`csv`](https://python-all.ru/3.16/library/csv.html#module-csv)
  - [`ctypes`](https://python-all.ru/3.16/library/ctypes.html#module-ctypes)
  - `ctypes.macholib`
  - [`decimal`](https://python-all.ru/3.16/library/decimal.html#module-decimal) (используйте [`decimal.SPEC_VERSION`](https://python-all.ru/3.16/library/decimal.html#decimal.SPEC_VERSION) вместо)
  - [`http.server`](https://python-all.ru/3.16/library/http.server.html#module-http.server)
  - [`imaplib`](https://python-all.ru/3.16/library/imaplib.html#module-imaplib)
  - [`ipaddress`](https://python-all.ru/3.16/library/ipaddress.html#module-ipaddress)
  - [`json`](https://python-all.ru/3.16/library/json.html#module-json)
  - [`logging`](https://python-all.ru/3.16/library/logging.html#module-logging) (`__date__` также устарел)
  - [`optparse`](https://python-all.ru/3.16/library/optparse.html#module-optparse)
  - [`pickle`](https://python-all.ru/3.16/library/pickle.html#module-pickle)
  - [`platform`](https://python-all.ru/3.16/library/platform.html#module-platform)
  - [`re`](https://python-all.ru/3.16/library/re.html#module-re)
  - [`socketserver`](https://python-all.ru/3.16/library/socketserver.html#module-socketserver)
  - [`tabnanny`](https://python-all.ru/3.16/library/tabnanny.html#module-tabnanny)
  - [`tarfile`](https://python-all.ru/3.16/library/tarfile.html#module-tarfile)
  - [`tkinter.font`](https://python-all.ru/3.16/library/tkinter.font.html#module-tkinter.font)
  - [`tkinter.ttk`](https://python-all.ru/3.16/library/tkinter.ttk.html#module-tkinter.ttk)
  - [`wsgiref.simple_server`](https://python-all.ru/3.16/library/wsgiref.html#module-wsgiref.simple_server)
  - [`xml.etree.ElementTree`](https://python-all.ru/3.16/library/xml.etree.elementtree.html#module-xml.etree.ElementTree)
  - `xml.sax.expatreader`
  - [`xml.sax.handler`](https://python-all.ru/3.16/library/xml.sax.handler.html#module-xml.sax.handler)
  - [`zlib`](https://python-all.ru/3.16/library/zlib.html#module-zlib)

  (Вклад: Hugo van Kemenade и Stan Ulbrych в [gh-76007](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Устаревшие элементы, определённые [**PEP 829**](https://python-all.ru/3.16/whatsnew/3.16.html):

  - Предупреждения выводятся для строк `import`, найденных в `name.pth` файлах.
  - Файлы `name.pth` больше не декодируются в кодировке локали по умолчанию. Они **ДОЛЖНЫ** быть закодированы в `utf-8-sig`.

  (Вклад: Barry Warsaw в [gh-148641](https://python-all.ru/3.16/whatsnew/3.16.html).)
- [`ast`](https://python-all.ru/3.16/library/ast.html#module-ast):

  - Создание экземпляров абстрактных узлов AST (таких как [`ast.AST`](https://python-all.ru/3.16/library/ast.html#ast.AST) или `ast.expr`) устарело и будет вызывать ошибку в Python 3.20.

### Ожидается удаление в Python 3.21

- [`abc`](https://python-all.ru/3.16/library/abc.html#module-abc)

  > - Мягко устаревшие с Python 3.3 [`abc.abstractclassmethod`](https://python-all.ru/3.16/library/abc.html#abc.abstractclassmethod), [`abc.abstractstaticmethod`](https://python-all.ru/3.16/library/abc.html#abc.abstractstaticmethod) и [`abc.abstractproperty`](https://python-all.ru/3.16/library/abc.html#abc.abstractproperty) теперь вызывают [`DeprecationWarning`](https://python-all.ru/3.16/library/exceptions.html#DeprecationWarning). Эти классы будут удалены в Python 3.21, вместо них используйте [`abc.abstractmethod()`](https://python-all.ru/3.16/library/abc.html#abc.abstractmethod) с [`classmethod()`](https://python-all.ru/3.16/library/functions.html#classmethod), [`staticmethod()`](https://python-all.ru/3.16/library/functions.html#staticmethod) и [`property`](https://python-all.ru/3.16/library/functions.html#property) соответственно.
- [`ast`](https://python-all.ru/3.16/library/ast.html#module-ast):

  - Классы `slice`, `Index`, `ExtSlice`, `Suite`, `Param`, `AugLoad` и `AugStore` будут удалены в Python 3.21. Эти типы не создаются синтаксическим анализатором и не принимаются генератором кода.
  - Свойство `dims` объекта `ast.Tuple` будет удалено в Python 3.21. Используйте свойство `ast.Tuple.elts` вместо него.
- [`struct`](https://python-all.ru/3.16/library/struct.html#module-struct):

  - Мягко устаревшие с Python 3.15, коды типов `'F'` и `'D'` теперь устарели. Эти коды будут удалены в Python 3.21. Используйте вместо них двухбуквенные формы `'Zf'` и `'Zd'`.
- [`tempfile`](https://python-all.ru/3.16/library/tempfile.html#module-tempfile):

  - `tempfile._TemporaryFileWrapper` будет удалён в Python 3.21. Используйте публичный [`tempfile.TemporaryFileWrapper`](https://python-all.ru/3.16/library/tempfile.html#tempfile.TemporaryFileWrapper) вместо него.

### Будет удалено в будущих версиях

Следующие API будут удалены в будущем, хотя на данный момент нет запланированной даты их удаления.

- [`argparse`](https://python-all.ru/3.16/library/argparse.html#module-argparse):

  - Вложение групп аргументов и вложение взаимоисключающих групп устарело.
  - Передача недокументированного именованного аргумента *prefix\_chars* в [`add_argument_group()`](https://python-all.ru/3.16/library/argparse.html#argparse.ArgumentParser.add_argument_group) теперь устарела.
  - Конвертер типов [`argparse.FileType`](https://python-all.ru/3.16/library/argparse.html#argparse.FileType) устарел.
- [`builtins`](https://python-all.ru/3.16/library/builtins.html#module-builtins):

  - Генераторы: сигнатура `throw(type, exc, tb)` и `athrow(type, exc, tb)` устарела: используйте `throw(exc)` и `athrow(exc)` вместо неё, сигнатуру с одним аргументом.
  - В настоящее время Python принимает числовые литералы, за которыми сразу следуют ключевые слова, например `0in x`, `1or x`, `0if 1else 2`. Это допускает запутанные и неоднозначные выражения вроде `[0x1for x in y]` (которое может быть интерпретировано как `[0x1 for x in y]` или `[0x1f or x in y]`). Выдаётся предупреждение синтаксиса, если за числовым литералом сразу следует одно из ключевых слов [`and`](https://python-all.ru/3.16/reference/expressions.html#and), [`else`](https://python-all.ru/3.16/reference/compound_stmts.html#else), [`for`](https://python-all.ru/3.16/reference/compound_stmts.html#for), [`if`](https://python-all.ru/3.16/reference/compound_stmts.html#if), [`in`](https://python-all.ru/3.16/reference/expressions.html#in), [`is`](https://python-all.ru/3.16/reference/expressions.html#is) и [`or`](https://python-all.ru/3.16/reference/expressions.html#or). В будущем выпуске это будет изменено на синтаксическую ошибку. ([gh-87999](https://python-all.ru/3.16/whatsnew/3.16.html))
  - Поддержка методов `__index__()` и `__int__()`, возвращающих не-int тип: эти методы должны будут возвращать экземпляр строгого подкласса [`int`](https://python-all.ru/3.16/library/functions.html#int).
  - Поддержка метода `__float__()`, возвращающего строгий подкласс [`float`](https://python-all.ru/3.16/library/functions.html#float): эти методы должны будут возвращать экземпляр `float`.
  - Поддержка метода `__complex__()`, возвращающего строгий подкласс [`complex`](https://python-all.ru/3.16/library/functions.html#complex): эти методы должны будут возвращать экземпляр `complex`.
  - Передача комплексного числа в качестве аргумента *real* или *imag* в конструкторе [`complex()`](https://python-all.ru/3.16/library/functions.html#complex) теперь устарела; его следует передавать только как единственный позиционный аргумент. (Автор: Сергей Сторчака в [gh-109218](https://python-all.ru/3.16/whatsnew/3.16.html).)
- [`calendar`](https://python-all.ru/3.16/library/calendar.html#module-calendar): константы `calendar.January` и `calendar.February` устарели и заменены на [`calendar.JANUARY`](https://python-all.ru/3.16/library/calendar.html#calendar.JANUARY) и [`calendar.FEBRUARY`](https://python-all.ru/3.16/library/calendar.html#calendar.FEBRUARY). (Автор: Prince Roshan в [gh-103636](https://python-all.ru/3.16/whatsnew/3.16.html).)
- [`codecs`](https://python-all.ru/3.16/library/codecs.html#module-codecs): используйте [`open()`](https://python-all.ru/3.16/library/functions.html#open) вместо [`codecs.open()`](https://python-all.ru/3.16/library/codecs.html#codecs.open). ([gh-133038](https://python-all.ru/3.16/whatsnew/3.16.html))
- `codeobject.co_lnotab`: используйте метод [`codeobject.co_lines()`](https://python-all.ru/3.16/reference/datamodel.html#codeobject.co_lines) вместо этого.
- [`datetime`](https://python-all.ru/3.16/library/datetime.html#module-datetime):

  - [`utcnow()`](https://python-all.ru/3.16/library/datetime.html#datetime.datetime.utcnow): используйте `datetime.datetime.now(tz=datetime.UTC)`.
  - [`utcfromtimestamp()`](https://python-all.ru/3.16/library/datetime.html#datetime.datetime.utcfromtimestamp): используйте `datetime.datetime.fromtimestamp(timestamp, tz=datetime.UTC)`.
- [`gettext`](https://python-all.ru/3.16/library/gettext.html#module-gettext): значение множественного числа должно быть целым числом.
- [`importlib`](https://python-all.ru/3.16/library/importlib.html#module-importlib):

  - [`cache_from_source()`](https://python-all.ru/3.16/library/importlib.html#importlib.util.cache_from_source): параметр *debug\_override* устарел: используйте параметр *optimization* вместо него.
- [`importlib.metadata`](https://python-all.ru/3.16/library/importlib.metadata.html#module-importlib.metadata):

  - `EntryPoints`: интерфейс кортежа.
  - Неявное `None` для возвращаемых значений.
- [`logging`](https://python-all.ru/3.16/library/logging.html#module-logging): метод `warn()` устарел начиная с Python 3.3, используйте [`warning()`](https://python-all.ru/3.16/library/logging.html#logging.warning) вместо него.
- [`mailbox`](https://python-all.ru/3.16/library/mailbox.html#module-mailbox): использование StringIO в режиме ввода и текстовом режиме устарело, используйте BytesIO и двоичный режим.
- [`os`](https://python-all.ru/3.16/library/os.html#module-os): вызов [`os.register_at_fork()`](https://python-all.ru/3.16/library/os.html#os.register_at_fork) в многопоточном процессе.
- [`os.path`](https://python-all.ru/3.16/library/os.path.html#module-os.path): [`os.path.commonprefix()`](https://python-all.ru/3.16/library/os.path.html#os.path.commonprefix) устарела, используйте [`os.path.commonpath()`](https://python-all.ru/3.16/library/os.path.html#os.path.commonpath) для префиксов путей. Функция `os.path.commonprefix()` объявлена устаревшей из-за вводящего в заблуждение названия и модуля. Эта функция небезопасна для использования в качестве префиксов путей, несмотря на то что находится в модуле для работы с путями, что означает, что легко случайно внести уязвимости обхода путей в программы на Python, используя эту функцию.
- `pydoc.ErrorDuringImport`: кортежное значение для параметра *exc\_info* устарело, используйте экземпляр исключения.
- [`re`](https://python-all.ru/3.16/library/re.html#module-re): теперь применяются более строгие правила для числовых ссылок на группы и имён групп в регулярных выражениях. В качестве числовой ссылки теперь принимается только последовательность цифр ASCII. Имя группы в байтовых шаблонах и строках замены теперь может содержать только буквы ASCII, цифры и знак подчёркивания. (Автор: Сергей Сторчака в [gh-91760](https://python-all.ru/3.16/whatsnew/3.16.html).)
- [`shutil`](https://python-all.ru/3.16/library/shutil.html#module-shutil): параметр *onerror* метода [`rmtree()`](https://python-all.ru/3.16/library/shutil.html#shutil.rmtree) устарел в Python 3.12; используйте параметр *onexc* вместо него.
- [`ssl`](https://python-all.ru/3.16/library/ssl.html#module-ssl): опции и протоколы:

  - [`ssl.SSLContext`](https://python-all.ru/3.16/library/ssl.html#ssl.SSLContext) без аргумента протокол устарело.
  - [`ssl.SSLContext`](https://python-all.ru/3.16/library/ssl.html#ssl.SSLContext): [`set_npn_protocols()`](https://python-all.ru/3.16/library/ssl.html#ssl.SSLContext.set_npn_protocols) и `selected_npn_protocol()` устарели: используйте ALPN вместо них.
  - `ssl.OP_NO_SSL*`: опции
  - `ssl.OP_NO_TLS*`: опции
  - `ssl.PROTOCOL_SSLv3`
  - `ssl.PROTOCOL_TLS`
  - `ssl.PROTOCOL_TLSv1`
  - `ssl.PROTOCOL_TLSv1_1`
  - `ssl.PROTOCOL_TLSv1_2`
  - `ssl.TLSVersion.SSLv3`
  - `ssl.TLSVersion.TLSv1`
  - `ssl.TLSVersion.TLSv1_1`
- [`threading`](https://python-all.ru/3.16/library/threading.html#module-threading): методы

  - `threading.Condition.notifyAll()`: используйте [`notify_all()`](https://python-all.ru/3.16/library/threading.html#threading.Condition.notify_all).
  - `threading.Event.isSet()`: используйте [`is_set()`](https://python-all.ru/3.16/library/threading.html#threading.Event.is_set).
  - `threading.Thread.isDaemon()`, [`threading.Thread.setDaemon()`](https://python-all.ru/3.16/library/threading.html#threading.Thread.setDaemon): используйте атрибут [`threading.Thread.daemon`](https://python-all.ru/3.16/library/threading.html#threading.Thread.daemon).
  - `threading.Thread.getName()`, [`threading.Thread.setName()`](https://python-all.ru/3.16/library/threading.html#threading.Thread.setName): используйте атрибут [`threading.Thread.name`](https://python-all.ru/3.16/library/threading.html#threading.Thread.name).
  - `threading.currentThread()`: используйте [`threading.current_thread()`](https://python-all.ru/3.16/library/threading.html#threading.current_thread).
  - `threading.activeCount()`: используйте [`threading.active_count()`](https://python-all.ru/3.16/library/threading.html#threading.active_count).
- [`typing.Text`](https://python-all.ru/3.16/library/typing.html#typing.Text) ([gh-92332](https://python-all.ru/3.16/whatsnew/3.16.html)).
- Внутренний класс `typing._UnionGenericAlias` больше не используется для реализации [`typing.Union`](https://python-all.ru/3.16/library/typing.html#typing.Union). Для сохранения совместимости с пользователями, использующими этот закрытый класс, будет предоставлена прослойка совместимости как минимум до Python 3.17. (Автор: Jelle Zijlstra, [gh-105499](https://python-all.ru/3.16/whatsnew/3.16.html).)
- [`unittest.IsolatedAsyncioTestCase`](https://python-all.ru/3.16/library/unittest.html#unittest.IsolatedAsyncioTestCase): возврат значения, не являющегося `None`, из тестового примера устарел.
- [`urllib.parse`](https://python-all.ru/3.16/library/urllib.parse.html#module-urllib.parse) устаревшие функции: используйте [`urlparse()`](https://python-all.ru/3.16/library/urllib.parse.html#urllib.parse.urlparse) вместо них.

  - `splitattr()`
  - `splithost()`
  - `splitnport()`
  - `splitpasswd()`
  - `splitport()`
  - `splitquery()`
  - `splittag()`
  - `splittype()`
  - `splituser()`
  - `splitvalue()`
  - `to_bytes()`
- [`wsgiref`](https://python-all.ru/3.16/library/wsgiref.html#module-wsgiref): `SimpleHandler.stdout.write()` не должна выполнять частичную запись.
- [`xml.etree.ElementTree`](https://python-all.ru/3.16/library/xml.etree.elementtree.html#module-xml.etree.ElementTree): проверка истинностного значения [`Element`](https://python-all.ru/3.16/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element) устарела. В будущем выпуске она всегда будет возвращать `True`. Вместо этого используйте явные проверки `len(elem)` или `elem is not None`.
- [`sys._clear_type_cache()`](https://python-all.ru/3.16/library/sys.html#sys._clear_type_cache) устарело: используйте [`sys._clear_internal_caches()`](https://python-all.ru/3.16/library/sys.html#sys._clear_internal_caches) вместо него.

## Перенос на Python 3.16

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

- В [`tkinter`](https://python-all.ru/3.16/library/tkinter.html#module-tkinter) параметр *name* методов [`wait_variable()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.Misc.wait_variable), [`setvar()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.Misc.setvar) и [`getvar()`](https://python-all.ru/3.16/library/tkinter.html#tkinter.Misc.getvar), а также параметр *value* метода `setvar()` теперь обязательны. Вызов этих методов без них, которые ранее по умолчанию равнялись `'PY_VAR'` и `'1'`, теперь вызывает [`TypeError`](https://python-all.ru/3.16/library/exceptions.html#TypeError). (Автор: Serhiy Storchaka в [gh-152587](https://python-all.ru/3.16/whatsnew/3.16.html).)

## Изменения в сборке

- Удалить встроенную копию десятичной библиотеки [libmpdec](https://python-all.ru/3.16/whatsnew/3.16.html) из дерева исходного кода CPython для упрощения сопровождения и обновлений. Модуль [`decimal`](https://python-all.ru/3.16/library/decimal.html#module-decimal) теперь будет безусловно использовать системную десятичную библиотеку libmpdec. Также удаляется теперь неиспользуемый флаг `--with-system-libmpdec` **configure**. Это изменение не влияет на бинарные релизы Python, которые в последних нескольких выпусках собирались с отдельной копией libmpdec.

  (Автор: Sergey B Kirpichev в [gh-115119](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Добавить флаг конфигурации [`--with-build-details-suffix`](https://python-all.ru/3.16/using/configure.html#cmdoption-with-build-details-suffix), чтобы позволить дистрибутивам Linux, которые устанавливают несколько версий Python вместе в одном дереве, избежать конфликтов `build-details.json`.

  (Автор: Stefano Rivera в [gh-131372](https://python-all.ru/3.16/whatsnew/3.16.html).)

## Изменения C API

### Новые возможности

- TODO

### Перенос на Python 3.16

- TODO

### Устаревшие C API

- [`PyGen_New()`](https://python-all.ru/3.16/c-api/gen.html#c.PyGen_New), [`PyGen_NewWithQualName()`](https://python-all.ru/3.16/c-api/gen.html#c.PyGen_NewWithQualName), [`PyCoro_New()`](https://python-all.ru/3.16/c-api/coro.html#c.PyCoro_New), и [`PyAsyncGen_New()`](https://python-all.ru/3.16/c-api/gen.html#c.PyAsyncGen_New) устарели. Их планируется удалить в версии 3.18.

#### Запланировано удаление в Python 3.18

- Следующие закрытые функции устарели и планируются к удалению в Python 3.18:

  - `_PyBytes_Join()`: используйте [`PyBytes_Join()`](https://python-all.ru/3.16/c-api/bytes.html#c.PyBytes_Join).
  - `_PyDict_GetItemStringWithError()`: используйте [`PyDict_GetItemStringRef()`](https://python-all.ru/3.16/c-api/dict.html#c.PyDict_GetItemStringRef).
  - `_PyDict_Pop()`: используйте [`PyDict_Pop()`](https://python-all.ru/3.16/c-api/dict.html#c.PyDict_Pop).
  - `_PyLong_Sign()`: используйте [`PyLong_GetSign()`](https://python-all.ru/3.16/c-api/long.html#c.PyLong_GetSign).
  - `_PyLong_FromDigits()` и `_PyLong_New()`: используйте [`PyLongWriter_Create()`](https://python-all.ru/3.16/c-api/long.html#c.PyLongWriter_Create).
  - `_PyThreadState_UncheckedGet()`: используйте [`PyThreadState_GetUnchecked()`](https://python-all.ru/3.16/c-api/threads.html#c.PyThreadState_GetUnchecked).
  - `_PyUnicode_AsString()`: используйте [`PyUnicode_AsUTF8()`](https://python-all.ru/3.16/c-api/unicode.html#c.PyUnicode_AsUTF8).
  - `_PyUnicodeWriter_Init()`: заменить `_PyUnicodeWriter_Init(&writer)` на [`writer = PyUnicodeWriter_Create(0)`](https://python-all.ru/3.16/c-api/unicode.html#c.PyUnicodeWriter_Create).
  - `_PyUnicodeWriter_Finish()`: заменить `_PyUnicodeWriter_Finish(&writer)` на [`PyUnicodeWriter_Finish(writer)`](https://python-all.ru/3.16/c-api/unicode.html#c.PyUnicodeWriter_Finish).
  - `_PyUnicodeWriter_Dealloc()`: заменить `_PyUnicodeWriter_Dealloc(&writer)` на [`PyUnicodeWriter_Discard(writer)`](https://python-all.ru/3.16/c-api/unicode.html#c.PyUnicodeWriter_Discard).
  - `_PyUnicodeWriter_WriteChar()`: заменить `_PyUnicodeWriter_WriteChar(&writer, ch)` на [`PyUnicodeWriter_WriteChar(writer, ch)`](https://python-all.ru/3.16/c-api/unicode.html#c.PyUnicodeWriter_WriteChar).
  - `_PyUnicodeWriter_WriteStr()`: заменить `_PyUnicodeWriter_WriteStr(&writer, str)` на [`PyUnicodeWriter_WriteStr(writer, str)`](https://python-all.ru/3.16/c-api/unicode.html#c.PyUnicodeWriter_WriteStr).
  - `_PyUnicodeWriter_WriteSubstring()`: заменить `_PyUnicodeWriter_WriteSubstring(&writer, str, start, end)` на [`PyUnicodeWriter_WriteSubstring(writer, str, start, end)`](https://python-all.ru/3.16/c-api/unicode.html#c.PyUnicodeWriter_WriteSubstring).
  - `_PyUnicodeWriter_WriteASCIIString()`: заменить `_PyUnicodeWriter_WriteASCIIString(&writer, str)` на [`PyUnicodeWriter_WriteASCII(writer, str)`](https://python-all.ru/3.16/c-api/unicode.html#c.PyUnicodeWriter_WriteASCII).
  - `_PyUnicodeWriter_WriteLatin1String()`: заменить `_PyUnicodeWriter_WriteLatin1String(&writer, str)` на [`PyUnicodeWriter_WriteUTF8(writer, str)`](https://python-all.ru/3.16/c-api/unicode.html#c.PyUnicodeWriter_WriteUTF8).
  - `_PyUnicodeWriter_Prepare()`: (нет замены).
  - `_PyUnicodeWriter_PrepareKind()`: (нет замены).
  - `_Py_HashPointer()`: используйте [`Py_HashPointer()`](https://python-all.ru/3.16/c-api/hash.html#c.Py_HashPointer).
  - `_Py_fopen_obj()`: используйте [`Py_fopen()`](https://python-all.ru/3.16/c-api/sys.html#c.Py_fopen).
  - [`PyGen_New()`](https://python-all.ru/3.16/c-api/gen.html#c.PyGen_New): (нет замены).
  - [`PyGen_NewWithQualName()`](https://python-all.ru/3.16/c-api/gen.html#c.PyGen_NewWithQualName): (нет замены).
  - [`PyCoro_New()`](https://python-all.ru/3.16/c-api/coro.html#c.PyCoro_New): (нет замены).
  - [`PyAsyncGen_New()`](https://python-all.ru/3.16/c-api/gen.html#c.PyAsyncGen_New): (нет замены).

  Проект [pythoncapi-compat](https://python-all.ru/3.16/whatsnew/3.16.html) можно использовать для получения этих новых открытых функций в Python 3.13 и старше. (Предложено Виктором Стиннером в [gh-128863](https://python-all.ru/3.16/whatsnew/3.16.html).)

#### Запланировано к удалению в Python 3.19

- [**PEP 456**](https://python-all.ru/3.16/whatsnew/3.16.html) поддержка встраивающих систем для определения схемы хеширования строк.

#### Ожидается удаление в Python 3.20

- `_PyObject_CallMethodId()`, `_PyObject_GetAttrId()` и `_PyUnicode_FromId()` устарели с версии 3.15 и будут удалены в 3.20. Вместо этого используйте [`PyUnicode_InternFromString()`](https://python-all.ru/3.16/c-api/unicode.html#c.PyUnicode_InternFromString) и кешируйте результат в состоянии модуля, затем вызывайте [`PyObject_CallMethod()`](https://python-all.ru/3.16/c-api/call.html#c.PyObject_CallMethod) или [`PyObject_GetAttr()`](https://python-all.ru/3.16/c-api/object.html#c.PyObject_GetAttr). (Предложено Виктором Стиннером в [gh-141049](https://python-all.ru/3.16/whatsnew/3.16.html).)
- Поле `cval` в [`PyComplexObject`](https://python-all.ru/3.16/c-api/complex.html#c.PyComplexObject) ([gh-128813](https://python-all.ru/3.16/whatsnew/3.16.html)). Используйте [`PyComplex_AsCComplex()`](https://python-all.ru/3.16/c-api/complex.html#c.PyComplex_AsCComplex) и [`PyComplex_FromCComplex()`](https://python-all.ru/3.16/c-api/complex.html#c.PyComplex_FromCComplex) для преобразования комплексного числа Python в/из представления C [`Py_complex`](https://python-all.ru/3.16/c-api/complex.html#c.Py_complex) .
- Макросы `Py_MATH_PIl` и `Py_MATH_El`.

#### Будет удалено в будущих версиях

Следующие API устарели и будут удалены, хотя на данный момент дата их удаления не назначена.

- [`Py_TPFLAGS_HAVE_FINALIZE`](https://python-all.ru/3.16/c-api/typeobj.html#c.Py_TPFLAGS_HAVE_FINALIZE): Не требуется начиная с Python 3.8.
- [`PyErr_Fetch()`](https://python-all.ru/3.16/c-api/exceptions.html#c.PyErr_Fetch): Вместо этого используйте [`PyErr_GetRaisedException()`](https://python-all.ru/3.16/c-api/exceptions.html#c.PyErr_GetRaisedException).
- [`PyErr_NormalizeException()`](https://python-all.ru/3.16/c-api/exceptions.html#c.PyErr_NormalizeException): Вместо этого используйте [`PyErr_GetRaisedException()`](https://python-all.ru/3.16/c-api/exceptions.html#c.PyErr_GetRaisedException).
- [`PyErr_Restore()`](https://python-all.ru/3.16/c-api/exceptions.html#c.PyErr_Restore): Вместо этого используйте [`PyErr_SetRaisedException()`](https://python-all.ru/3.16/c-api/exceptions.html#c.PyErr_SetRaisedException).
- [`PyModule_GetFilename()`](https://python-all.ru/3.16/c-api/module.html#c.PyModule_GetFilename): Вместо этого используйте [`PyModule_GetFilenameObject()`](https://python-all.ru/3.16/c-api/module.html#c.PyModule_GetFilenameObject).
- [`PyOS_AfterFork()`](https://python-all.ru/3.16/c-api/sys.html#c.PyOS_AfterFork): Вместо этого используйте [`PyOS_AfterFork_Child()`](https://python-all.ru/3.16/c-api/sys.html#c.PyOS_AfterFork_Child).
- [`PySlice_GetIndicesEx()`](https://python-all.ru/3.16/c-api/slice.html#c.PySlice_GetIndicesEx): Вместо этого используйте [`PySlice_Unpack()`](https://python-all.ru/3.16/c-api/slice.html#c.PySlice_Unpack) и [`PySlice_AdjustIndices()`](https://python-all.ru/3.16/c-api/slice.html#c.PySlice_AdjustIndices).
- [`PyUnicode_READY()`](https://python-all.ru/3.16/c-api/unicode.html#c.PyUnicode_READY): Не требуется начиная с Python 3.12
- `PyErr_Display()`: Вместо этого используйте [`PyErr_DisplayException()`](https://python-all.ru/3.16/c-api/exceptions.html#c.PyErr_DisplayException).
- `_PyErr_ChainExceptions()`: Вместо этого используйте `_PyErr_ChainExceptions1()`.
- Элемент `PyBytesObject.ob_shash`: вместо этого вызывайте [`PyObject_Hash()`](https://python-all.ru/3.16/c-api/object.html#c.PyObject_Hash).
- API локального хранилища потока (TLS):

  - [`PyThread_create_key()`](https://python-all.ru/3.16/c-api/tls.html#c.PyThread_create_key): Вместо этого используйте [`PyThread_tss_alloc()`](https://python-all.ru/3.16/c-api/tls.html#c.PyThread_tss_alloc).
  - [`PyThread_delete_key()`](https://python-all.ru/3.16/c-api/tls.html#c.PyThread_delete_key): Вместо этого используйте [`PyThread_tss_free()`](https://python-all.ru/3.16/c-api/tls.html#c.PyThread_tss_free).
  - [`PyThread_set_key_value()`](https://python-all.ru/3.16/c-api/tls.html#c.PyThread_set_key_value): Вместо этого используйте [`PyThread_tss_set()`](https://python-all.ru/3.16/c-api/tls.html#c.PyThread_tss_set).
  - [`PyThread_get_key_value()`](https://python-all.ru/3.16/c-api/tls.html#c.PyThread_get_key_value): Вместо этого используйте [`PyThread_tss_get()`](https://python-all.ru/3.16/c-api/tls.html#c.PyThread_tss_get).
  - [`PyThread_delete_key_value()`](https://python-all.ru/3.16/c-api/tls.html#c.PyThread_delete_key_value): Вместо этого используйте [`PyThread_tss_delete()`](https://python-all.ru/3.16/c-api/tls.html#c.PyThread_tss_delete).
  - [`PyThread_ReInitTLS()`](https://python-all.ru/3.16/c-api/tls.html#c.PyThread_ReInitTLS): Не требуется с Python 3.7.

### Удалённые C API
