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

development.md

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

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