Документация Python неофициальный перевод

development.md

190 строк · 21.4 КБ · обычная страница · сырой текст · скачать

1> **Источник:** https://python-all.ru/3.11/library/development.html2>3> «Документация Python на русском» – неофициальный перевод официальной документации Python: версии от 2.6 до 3.16, полнотекстовый поиск, английский оригинал рядом с переводом. Эта Markdown-версия страницы предназначена для работы с LLM: вставьте её в ChatGPT, Claude или Cursor.45---67# Инструменты разработки89Модули, описанные в этой главе, помогают писать программное обеспечение. Например, модуль [`pydoc`](https://python-all.ru/3.11/library/pydoc.html#module-pydoc) принимает модуль и генерирует документацию на основе его содержимого. Модули [`doctest`](https://python-all.ru/3.11/library/doctest.html#module-doctest) и [`unittest`](https://python-all.ru/3.11/library/unittest.html#module-unittest) содержат фреймворки для написания модульных тестов, которые автоматически выполняют код и проверяют, что вывод соответствует ожидаемому. **2to3** может переводить исходный код Python 2.x в корректный код Python 3.x.1011Список модулей, описанных в этой главе:1213- [`typing` – Поддержка аннотаций типов](https://python-all.ru/3.11/library/typing.html)1415  - [Соответствующие PEPs](https://python-all.ru/3.11/library/typing.html#relevant-peps)16  - [Псевдонимы типов](https://python-all.ru/3.11/library/typing.html#type-aliases)17  - [NewType](https://python-all.ru/3.11/library/typing.html#newtype)18  - [Аннотирование вызываемых объектов](https://python-all.ru/3.11/library/typing.html#annotating-callable-objects)19  - [Обобщённые типы](https://python-all.ru/3.11/library/typing.html#generics)20  - [Аннотирование кортежей](https://python-all.ru/3.11/library/typing.html#annotating-tuples)21  - [Тип объектов классов](https://python-all.ru/3.11/library/typing.html#the-type-of-class-objects)22  - [Пользовательские обобщённые типы](https://python-all.ru/3.11/library/typing.html#user-defined-generic-types)23  - [Тип `Any`](https://python-all.ru/3.11/library/typing.html#the-any-type)24  - [Номинальное и структурное подтипирование](https://python-all.ru/3.11/library/typing.html#nominal-vs-structural-subtyping)25  - [Содержание модуля](https://python-all.ru/3.11/library/typing.html#module-contents)2627    - [Специальные примитивы типизации](https://python-all.ru/3.11/library/typing.html#special-typing-primitives)2829      - [Специальные типы](https://python-all.ru/3.11/library/typing.html#special-types)30      - [Специальные формы](https://python-all.ru/3.11/library/typing.html#special-forms)31      - [Построение обобщённых типов](https://python-all.ru/3.11/library/typing.html#building-generic-types)32      - [Другие специальные директивы](https://python-all.ru/3.11/library/typing.html#other-special-directives)33    - [Протоколы](https://python-all.ru/3.11/library/typing.html#protocols)34    - [ABC для работы с вводом-выводом](https://python-all.ru/3.11/library/typing.html#abcs-for-working-with-io)35    - [Функции и декораторы](https://python-all.ru/3.11/library/typing.html#functions-and-decorators)36    - [Вспомогательные функции интроспекции](https://python-all.ru/3.11/library/typing.html#introspection-helpers)37    - [Константа](https://python-all.ru/3.11/library/typing.html#constant)38    - [Устаревшие псевдонимы](https://python-all.ru/3.11/library/typing.html#deprecated-aliases)3940      - [Псевдонимы для встроенных типов](https://python-all.ru/3.11/library/typing.html#aliases-to-built-in-types)41      - [Псевдонимы для типов в `collections`](https://python-all.ru/3.11/library/typing.html#aliases-to-types-in-collections)42      - [Псевдонимы для других конкретных типов](https://python-all.ru/3.11/library/typing.html#aliases-to-other-concrete-types)43      - [Псевдонимы для ABC-контейнеров в `collections.abc`](https://python-all.ru/3.11/library/typing.html#aliases-to-container-abcs-in-collections-abc)44      - [Псевдонимы для асинхронных ABC в `collections.abc`](https://python-all.ru/3.11/library/typing.html#aliases-to-asynchronous-abcs-in-collections-abc)45      - [Псевдонимы для других ABC в `collections.abc`](https://python-all.ru/3.11/library/typing.html#aliases-to-other-abcs-in-collections-abc)46      - [Псевдонимы для `contextlib`-ABC](https://python-all.ru/3.11/library/typing.html#aliases-to-contextlib-abcs)47  - [График устаревания основных возможностей](https://python-all.ru/3.11/library/typing.html#deprecation-timeline-of-major-features)48- [`pydoc` – генератор документации и система интерактивной справки](https://python-all.ru/3.11/library/pydoc.html)49- [Режим разработки Python](https://python-all.ru/3.11/library/devmode.html)5051  - [Эффекты режима разработки Python](https://python-all.ru/3.11/library/devmode.html#effects-of-the-python-development-mode)52  - [Пример ResourceWarning](https://python-all.ru/3.11/library/devmode.html#resourcewarning-example)53  - [Пример ошибки с некорректным файловым дескриптором](https://python-all.ru/3.11/library/devmode.html#bad-file-descriptor-error-example)54- [`doctest` – тестирование интерактивных примеров Python](https://python-all.ru/3.11/library/doctest.html)5556  - [Простое использование: проверка примеров в строках документации](https://python-all.ru/3.11/library/doctest.html#simple-usage-checking-examples-in-docstrings)57  - [Простое использование: проверка примеров в текстовом файле](https://python-all.ru/3.11/library/doctest.html#simple-usage-checking-examples-in-a-text-file)58  - [Как это работает](https://python-all.ru/3.11/library/doctest.html#how-it-works)5960    - [Какие строки документации проверяются?](https://python-all.ru/3.11/library/doctest.html#which-docstrings-are-examined)61    - [Как распознаются примеры в строках документации?](https://python-all.ru/3.11/library/doctest.html#how-are-docstring-examples-recognized)62    - [Каков контекст выполнения?](https://python-all.ru/3.11/library/doctest.html#what-s-the-execution-context)63    - [А как насчёт исключений?](https://python-all.ru/3.11/library/doctest.html#what-about-exceptions)64    - [Флаги опций](https://python-all.ru/3.11/library/doctest.html#option-flags)65    - [Директивы](https://python-all.ru/3.11/library/doctest.html#directives)66    - [Предупреждения](https://python-all.ru/3.11/library/doctest.html#warnings)67  - [Базовый API](https://python-all.ru/3.11/library/doctest.html#basic-api)68  - [API unittest](https://python-all.ru/3.11/library/doctest.html#unittest-api)69  - [Расширенный API](https://python-all.ru/3.11/library/doctest.html#advanced-api)7071    - [Объекты DocTest](https://python-all.ru/3.11/library/doctest.html#doctest-objects)72    - [Объекты Example](https://python-all.ru/3.11/library/doctest.html#example-objects)73    - [Объекты DocTestFinder](https://python-all.ru/3.11/library/doctest.html#doctestfinder-objects)74    - [Объекты DocTestParser](https://python-all.ru/3.11/library/doctest.html#doctestparser-objects)75    - [Объекты DocTestRunner](https://python-all.ru/3.11/library/doctest.html#doctestrunner-objects)76    - [Объекты OutputChecker](https://python-all.ru/3.11/library/doctest.html#outputchecker-objects)77  - [Отладка](https://python-all.ru/3.11/library/doctest.html#debugging)78  - [Трибуна](https://python-all.ru/3.11/library/doctest.html#soapbox)79- [`unittest` – фреймворк для модульного тестирования](https://python-all.ru/3.11/library/unittest.html)8081  - [Простой пример](https://python-all.ru/3.11/library/unittest.html#basic-example)82  - [Интерфейс командной строки](https://python-all.ru/3.11/library/unittest.html#command-line-interface)8384    - [Параметры командной строки](https://python-all.ru/3.11/library/unittest.html#command-line-options)85  - [Обнаружение тестов](https://python-all.ru/3.11/library/unittest.html#test-discovery)86  - [Организация тестового кода](https://python-all.ru/3.11/library/unittest.html#organizing-test-code)87  - [Повторное использование старого тестового кода](https://python-all.ru/3.11/library/unittest.html#re-using-old-test-code)88  - [Пропуск тестов и ожидаемые сбои](https://python-all.ru/3.11/library/unittest.html#skipping-tests-and-expected-failures)89  - [Различение итераций теста с помощью подтестов](https://python-all.ru/3.11/library/unittest.html#distinguishing-test-iterations-using-subtests)90  - [Классы и функции](https://python-all.ru/3.11/library/unittest.html#classes-and-functions)9192    - [Тестовые случаи](https://python-all.ru/3.11/library/unittest.html#test-cases)9394      - [Устаревшие псевдонимы](https://python-all.ru/3.11/library/unittest.html#deprecated-aliases)95    - [Группировка тестов](https://python-all.ru/3.11/library/unittest.html#grouping-tests)96    - [Загрузка и запуск тестов](https://python-all.ru/3.11/library/unittest.html#loading-and-running-tests)9798      - [Протокол load\_tests](https://python-all.ru/3.11/library/unittest.html#load-tests-protocol)99  - [Фикстуры классов и модулей](https://python-all.ru/3.11/library/unittest.html#class-and-module-fixtures)100101    - [setUpClass и tearDownClass](https://python-all.ru/3.11/library/unittest.html#setupclass-and-teardownclass)102    - [setUpModule и tearDownModule](https://python-all.ru/3.11/library/unittest.html#setupmodule-and-teardownmodule)103  - [Обработка сигналов](https://python-all.ru/3.11/library/unittest.html#signal-handling)104- [`unittest.mock` – библиотека mock-объектов](https://python-all.ru/3.11/library/unittest.mock.html)105106  - [Краткое руководство](https://python-all.ru/3.11/library/unittest.mock.html#quick-guide)107  - [Класс Mock](https://python-all.ru/3.11/library/unittest.mock.html#the-mock-class)108109    - [Вызов](https://python-all.ru/3.11/library/unittest.mock.html#calling)110    - [Удаление атрибутов](https://python-all.ru/3.11/library/unittest.mock.html#deleting-attributes)111    - [Имена Mock и атрибут name](https://python-all.ru/3.11/library/unittest.mock.html#mock-names-and-the-name-attribute)112    - [Прикрепление моков в качестве атрибутов](https://python-all.ru/3.11/library/unittest.mock.html#attaching-mocks-as-attributes)113  - [Патчеры](https://python-all.ru/3.11/library/unittest.mock.html#the-patchers)114115    - [patch](https://python-all.ru/3.11/library/unittest.mock.html#patch)116    - [patch.object](https://python-all.ru/3.11/library/unittest.mock.html#patch-object)117    - [patch.dict](https://python-all.ru/3.11/library/unittest.mock.html#patch-dict)118    - [patch.multiple](https://python-all.ru/3.11/library/unittest.mock.html#patch-multiple)119    - [Методы patch: start и stop](https://python-all.ru/3.11/library/unittest.mock.html#patch-methods-start-and-stop)120    - [patch встроенных объектов](https://python-all.ru/3.11/library/unittest.mock.html#patch-builtins)121    - [TEST\_PREFIX](https://python-all.ru/3.11/library/unittest.mock.html#test-prefix)122    - [Вложение декораторов patch](https://python-all.ru/3.11/library/unittest.mock.html#nesting-patch-decorators)123    - [Где применять patch](https://python-all.ru/3.11/library/unittest.mock.html#where-to-patch)124    - [Подмена дескрипторов и прокси-объектов](https://python-all.ru/3.11/library/unittest.mock.html#patching-descriptors-and-proxy-objects)125  - [MagicMock и поддержка магических методов](https://python-all.ru/3.11/library/unittest.mock.html#magicmock-and-magic-method-support)126127    - [Мокирование магических методов](https://python-all.ru/3.11/library/unittest.mock.html#mocking-magic-methods)128    - [Магический макет](https://python-all.ru/3.11/library/unittest.mock.html#magic-mock)129  - [Вспомогательные средства](https://python-all.ru/3.11/library/unittest.mock.html#helpers)130131    - [sentinel](https://python-all.ru/3.11/library/unittest.mock.html#sentinel)132    - [DEFAULT](https://python-all.ru/3.11/library/unittest.mock.html#default)133    - [вызов](https://python-all.ru/3.11/library/unittest.mock.html#call)134    - [create\_autospec](https://python-all.ru/3.11/library/unittest.mock.html#create-autospec)135    - [ANY](https://python-all.ru/3.11/library/unittest.mock.html#any)136    - [FILTER\_DIR](https://python-all.ru/3.11/library/unittest.mock.html#filter-dir)137    - [mock\_open](https://python-all.ru/3.11/library/unittest.mock.html#mock-open)138    - [Автоспецификация](https://python-all.ru/3.11/library/unittest.mock.html#autospeccing)139    - [Запечатывание моков](https://python-all.ru/3.11/library/unittest.mock.html#sealing-mocks)140  - [Порядок приоритета `side_effect`, `return_value` и *wraps*](https://python-all.ru/3.11/library/unittest.mock.html#order-of-precedence-of-side-effect-return-value-and-wraps)141- [`unittest.mock` – начало работы](https://python-all.ru/3.11/library/unittest.mock-examples.html)142143  - [Использование Mock](https://python-all.ru/3.11/library/unittest.mock-examples.html#using-mock)144145    - [Методы подмены моков](https://python-all.ru/3.11/library/unittest.mock-examples.html#mock-patching-methods)146    - [Mock для вызовов методов объекта](https://python-all.ru/3.11/library/unittest.mock-examples.html#mock-for-method-calls-on-an-object)147    - [Создание моков для классов](https://python-all.ru/3.11/library/unittest.mock-examples.html#mocking-classes)148    - [Именование моков](https://python-all.ru/3.11/library/unittest.mock-examples.html#naming-your-mocks)149    - [Отслеживание всех вызовов](https://python-all.ru/3.11/library/unittest.mock-examples.html#tracking-all-calls)150    - [Установка возвращаемых значений и атрибутов](https://python-all.ru/3.11/library/unittest.mock-examples.html#setting-return-values-and-attributes)151    - [Возбуждение исключений с помощью моков](https://python-all.ru/3.11/library/unittest.mock-examples.html#raising-exceptions-with-mocks)152    - [Функции побочного эффекта и итерируемые объекты](https://python-all.ru/3.11/library/unittest.mock-examples.html#side-effect-functions-and-iterables)153    - [Мокирование асинхронных итераторов](https://python-all.ru/3.11/library/unittest.mock-examples.html#mocking-asynchronous-iterators)154    - [Мокирование асинхронного контекстного менеджера](https://python-all.ru/3.11/library/unittest.mock-examples.html#mocking-asynchronous-context-manager)155    - [Создание мока на основе существующего объекта](https://python-all.ru/3.11/library/unittest.mock-examples.html#creating-a-mock-from-an-existing-object)156    - [Использование side\_effect для возврата содержимого каждого файла](https://python-all.ru/3.11/library/unittest.mock-examples.html#using-side-effect-to-return-per-file-content)157  - [Декораторы patch](https://python-all.ru/3.11/library/unittest.mock-examples.html#patch-decorators)158  - [Дополнительные примеры](https://python-all.ru/3.11/library/unittest.mock-examples.html#further-examples)159160    - [Мокирование цепочек вызовов](https://python-all.ru/3.11/library/unittest.mock-examples.html#mocking-chained-calls)161    - [Частичное мокирование](https://python-all.ru/3.11/library/unittest.mock-examples.html#partial-mocking)162    - [Создание мока для метода-генератора](https://python-all.ru/3.11/library/unittest.mock-examples.html#mocking-a-generator-method)163    - [Применение одного и того же patch к каждому тестовому методу](https://python-all.ru/3.11/library/unittest.mock-examples.html#applying-the-same-patch-to-every-test-method)164    - [Создание моков для несвязанных методов](https://python-all.ru/3.11/library/unittest.mock-examples.html#mocking-unbound-methods)165    - [Проверка множественных вызовов с помощью mock](https://python-all.ru/3.11/library/unittest.mock-examples.html#checking-multiple-calls-with-mock)166    - [Работа с изменяемыми аргументами](https://python-all.ru/3.11/library/unittest.mock-examples.html#coping-with-mutable-arguments)167    - [Вложенные подмены](https://python-all.ru/3.11/library/unittest.mock-examples.html#nesting-patches)168    - [Мокирование словаря с помощью MagicMock](https://python-all.ru/3.11/library/unittest.mock-examples.html#mocking-a-dictionary-with-magicmock)169    - [Подклассы Mock и их атрибуты](https://python-all.ru/3.11/library/unittest.mock-examples.html#mock-subclasses-and-their-attributes)170    - [Мокирование импортов с помощью patch.dict](https://python-all.ru/3.11/library/unittest.mock-examples.html#mocking-imports-with-patch-dict)171    - [Отслеживание порядка вызовов и менее многословные утверждения о вызовах](https://python-all.ru/3.11/library/unittest.mock-examples.html#tracking-order-of-calls-and-less-verbose-call-assertions)172    - [Более сложное сопоставление аргументов](https://python-all.ru/3.11/library/unittest.mock-examples.html#more-complex-argument-matching)173- [2to3 – автоматическое преобразование кода Python 2 в 3](https://python-all.ru/3.11/library/2to3.html)174175  - [Использование 2to3](https://python-all.ru/3.11/library/2to3.html#using-2to3)176  - [Фиксы](https://python-all.ru/3.11/library/2to3.html#fixers)177  - [`lib2to3` – библиотека 2to3](https://python-all.ru/3.11/library/2to3.html#module-lib2to3)178- [`test` – Пакет регрессионных тестов для Python](https://python-all.ru/3.11/library/test.html)179180  - [Написание модульных тестов для пакета `test`](https://python-all.ru/3.11/library/test.html#writing-unit-tests-for-the-test-package)181  - [Запуск тестов с помощью интерфейса командной строки](https://python-all.ru/3.11/library/test.html#module-test.regrtest)182- [`test.support` – Утилиты для набора тестов Python](https://python-all.ru/3.11/library/test.html#module-test.support)183- [`test.support.socket_helper` – Утилиты для тестирования сокетов](https://python-all.ru/3.11/library/test.html#module-test.support.socket_helper)184- [`test.support.script_helper` – Утилиты для тестов выполнения Python](https://python-all.ru/3.11/library/test.html#module-test.support.script_helper)185- [`test.support.bytecode_helper` – Вспомогательные инструменты для тестирования корректной генерации байт-кода](https://python-all.ru/3.11/library/test.html#module-test.support.bytecode_helper)186- [`test.support.threading_helper` – Утилиты для тестирования потоков](https://python-all.ru/3.11/library/test.html#module-test.support.threading_helper)187- [`test.support.os_helper` – Утилиты для тестирования ОС](https://python-all.ru/3.11/library/test.html#module-test.support.os_helper)188- [`test.support.import_helper` – утилиты для тестирования импорта](https://python-all.ru/3.11/library/test.html#module-test.support.import_helper)189- [`test.support.warnings_helper` – утилиты для тестирования предупреждений](https://python-all.ru/3.11/library/test.html#module-test.support.warnings_helper)190