warnings — Управление предупреждениями¶
Предупреждающие сообщения обычно выдаются в ситуациях, когда полезно предупредить пользователя о каком-либо условии в программе, когда условие (обычно) не требует создания исключения и завершения программы. Например, кто- то может захотеть увидеть предупреждение, когда программа использует устаревший модуль.
Программисты Python выдают предупреждения, вызывая функцию warn() , определенную в этом модуле. (Программисты на C используют PyErr_WarnEx() ; подробности см. в Обработка исключений ).
Предупреждающие сообщения обычно записываются в sys.stderr , но их расположение можно гибко менять, от игнорирования всех предупреждений до превращения их в исключения. Расположение предупреждений может варьироваться в зависимости от категории предупреждения , текста предупреждающего сообщения и исходного местоположения, в котором оно выпущено. Повторения конкретного предупреждения для одного и того же источника обычно подавляются.
Управление предупреждениями состоит из двух этапов: во-первых, каждый раз, когда выдается предупреждение, определяется, следует ли выдавать сообщение; затем, если сообщение должно быть выпущено, оно форматируется и печатается с использованием настраиваемой пользователем хука (hook).
Решение о том, выдавать ли предупреждающее сообщение, контролируется фильтром предупреждений , который представляет собой последовательность правил и действий сопоставления. Правила можно добавить в фильтр, вызвав filterwarnings() , и сбросить до состояния по умолчанию, вызвав resetwarnings() .
Распечатка предупреждающих сообщений выполняется путём вызова showwarning() , которую можно отменить; реализация по умолчанию данной функции форматирует сообщение, вызывая formatwarning() , которая также доступна для использования в пользовательских реализациях.
logging.captureWarnings() позволяет обрабатывать все предупреждения с помощью стандартной инфраструктуры логирования.
Категории предупреждений¶
Существует ряд встроенных исключений, которые представляют категории предупреждений. Категоризация нужна для возможности фильтрации группы предупреждений.
Хотя технически это встроенные исключения , они задокументированы здесь, поскольку концептуально относятся к механизму предупреждений.
Пользовательский код может определять дополнительные категории предупреждений, создавая подклассы одной из стандартных категорий предупреждений. Категория предупреждения всегда должна быть подклассом класса Warning .
В настоящее время определены следующие классы категорий предупреждений:
Класс | Описание |
---|---|
Warning | Базовый класс всех классов категории предупреждения. Подкласс Exception . |
UserWarning | Категория по умолчанию для warn() . |
DeprecationWarning | Базовая категория для предупреждений об устаревших функциях, когда эти предупреждения предназначены для других разработчиков Python (игнорируются по умолчанию, если не вызвано кодом в __main__ ). |
SyntaxWarning | Базовая категория для предупреждений о сомнительных синтаксических особенностях. |
RuntimeWarning | Базовая категория для предупреждений о сомнительных функциях среды выполнения. |
FutureWarning | Базовая категория для предупреждений об устаревших функциях, если эти предупреждения предназначены для конечных пользователей приложений, написанных в Python. |
PendingDeprecationWarning | Базовая категория для предупреждений о функциях, которые будут устаревшими в будущем (игнорируется по умолчанию). |
ImportWarning | Базовая категория для предупреждений, запускаемых в процессе импорта модуля (игнорируется по умолчанию). |
UnicodeWarning | Базовая категория для предупреждений, связанных с Юникодом. |
BytesWarning | Базовая категория для предупреждений, связанных с bytes и bytearray . |
ResourceWarning | Базовая категория для предупреждений, связанных с использованием ресурсов. |
Изменено в версии 3.7: Ранее DeprecationWarning и FutureWarning различались в зависимости от того, удалялась ли функция полностью или изменялось ли её поведение. Теперь они различаются по целевой аудитории и способу обработки с помощью фильтров предупреждений по умолчанию.
Фильтр предупреждений¶
Фильтр предупреждений определяет, будут ли предупреждения игнорироваться, отображаться или превращаться в ошибки (вызывая исключение).
По сути, фильтр предупреждений поддерживает упорядоченный список спецификаций фильтра; любое конкретное предупреждение сопоставляется с каждой спецификацией фильтра в списке по очереди, пока не будет найдено совпадение; фильтр определяет расположение совпадения. Каждая запись представляет собой кортеж вида (action, message, category, module, lineno), где:
action — одна из следующих строк:
message — строка, содержащая регулярное выражение, которому должно соответствовать начало предупреждающего сообщения. Выражение всегда учитывает регистр.
category — класс (подкласс Warning ), для которого категория предупреждения должна быть подклассом.
module — строка, содержащая регулярное выражение, которому должно соответствовать имя модуля. Выражение составлено с учётом регистра.
lineno — целое число, которому должен соответствовать номер строки, в которой возникло предупреждение, или 0 , чтобы соответствовать всем номерам строк.
Поскольку класс Warning является производным от встроенного класса Exception , чтобы превратить предупреждение в ошибку, мы просто поднимаем category(message) .
Если выдаётся предупреждение и не соответствует ни одному зарегистрированному фильтру, применяется действие «по умолчанию» (отсюда и его название).
Описание фильтров предупреждений¶
Фильтр предупреждений инициализируется параметрами -W , переданными в командную строку интерпретатора Python и переменной среды PYTHONWARNINGS . Интерпретатор сохраняет аргументы для всех предоставленных записей без интерпретации в sys.warnoptions ; модуль warnings анализирует их при первом импорте (недопустимые параметры игнорируются после вывода сообщения в sys.stderr ).
Индивидуальные фильтры предупреждений задаются как последовательность полей, разделенных двоеточиями:
Значение каждого из этих полей описано в Фильтр предупреждений . При перечислении нескольких фильтров в одной строке (как для PYTHONWARNINGS ) отдельные фильтры разделяются запятыми, а фильтры перечисленные позже, приоритетнее тех, которые перечислены перед ними (поскольку они применяются слева направо и последние применённые фильтры приоритетнее более ранних).
Обычно используемые фильтры предупреждений применяются ко всем предупреждениям, предупреждениям в определенной категории или предупреждениям, создаваемым определенными модулями или пакетами. Несколько примеров:
Фильтр предупреждений по умолчанию¶
По умолчанию Python устанавливает несколько фильтров предупреждений, которые можно переопределить параметром командной строки -W , переменной среды PYTHONWARNINGS и вызовами filterwarnings() .
В сборках обычного релиза у фильтра предупреждений по умолчанию следующие записи (в порядке приоритета):
В отладочных сборках список фильтров предупреждений по умолчанию пуст.
Изменено в версии 3.2: DeprecationWarning теперь по умолчанию игнорируется в дополнение к PendingDeprecationWarning .
Изменено в версии 3.7: DeprecationWarning снова отображается по умолчанию, когда запускается непосредственно кодом в __main__ .
Изменено в версии 3.7: BytesWarning больше не отображается в списке фильтров по умолчанию и вместо этого настраивается через sys.warnoptions , когда -b указывается дважды.
Отмена фильтра по умолчанию¶
Разработчики приложений, написанных на Python, могут пожелать скрыть предупреждения всех уровней Python от своих пользователей по умолчанию и отображать их только при выполнении тестов или другой работе с приложением. Атрибут sys.warnoptions , используемый для передачи конфигураций фильтров интерпретатору, может использоваться в качестве маркера, указывающего, следует ли отключать предупреждения:
Разработчикам средств запуска тестов для кода Python рекомендуется вместо этого обеспечить отображение всех предупреждений по умолчанию для тестируемого кода, используя такой код, как:
Наконец, разработчикам интерактивных оболочек, которые запускают пользовательский код в пространстве имён, отличном от __main__ , рекомендуется обеспечить отображение сообщений DeprecationWarning по умолчанию, используя следующий код (где user_ns — модуль, используемый для выполнения кода, набранного в интерактивном режиме):
Временное подавление предупреждений¶
Если вы используете код, который, как вы знаете, вызовет предупреждение, например устаревшую функцию, но не хотите видеть предупреждение (даже если предупреждения были явно настроены через командную строку), то можно подавить предупреждение, используя менеджер контекста catch_warnings :
В менеджере контекста все предупреждения просто игнорируются. Это позволяет использовать заведомо устаревший код без необходимости видеть предупреждение, не подавляя при этом предупреждение для другого кода, который может не знать об использовании устаревшего кода. Примечание: гарантируется только в однопоточном приложении. Если два или более потока используют менеджер контекста catch_warnings одновременно, поведение не определено.
Предупреждения при тестировании¶
Чтобы проверить предупреждения, вызванные кодом, используйте менеджер контекста catch_warnings . С его помощью вы можете временно изменить фильтр предупреждений, чтобы облегчить тестирование. Например, сделайте следующее, чтобы зафиксировать все возникшие предупреждения и проверить их:
Можно также сделать все предупреждения исключениями, используя error вместо always . Следует помнить, что если предупреждение уже было выдано из-за правила once / default , то независимо от того, какие фильтры установлены, предупреждение не будет отображаться снова, если реестр предупреждений, связанный с предупреждением, не будет очищен.
После выхода из менеджера контекста фильтр предупреждений восстанавливается до состояния, в котором был вход в контекст. Это предотвращает непредвиденное изменение фильтра предупреждений в тестах между тестами и получение неопределённых результатов. Функция showwarning() в модуле также восстанавливается до исходного значения. Примечание: гарантируется только в однопоточном приложении. Если два или более потока одновременно используют менеджер контекста catch_warnings , поведение не определено.
При тестировании нескольких операций, которые вызывают одно и то же предупреждение, важно протестировать их таким образом, чтобы подтвердить, что каждая операция вызывает новое предупреждение (например, установить предупреждения, которые будут выдаваться как исключения, и проверить, что операции вызывают исключения, убедитесь, что длина списка предупреждений продолжает увеличиваться после каждой операции или удалять предыдущие записи из списка предупреждений перед каждой новой операцией).
Обновление кода для новых версий зависимостей¶
Категории предупреждений, которые в первую очередь представляют интерес для разработчиков Python (а не для конечных пользователей приложений, написанных на Python), по умолчанию игнорируются.
Примечательно, что этот список «игнорируется по умолчанию» включает DeprecationWarning (для каждого модуля, кроме __main__ ), что означает, что разработчики должны обязательно тестировать свой код с обычно игнорируемыми предупреждениями, сделанными видимыми, чтобы своевременно получать уведомления о будущих критических изменениях API (будь то в стандартной библиотеке или сторонних пакетах).
В идеальном случае у кода будет подходящее множество тестов, и средство выполнения тестов позаботится о неявном включении всех предупреждений при запуске тестов (это делает средство запуска тестов, предоставляемое модулем unittest ).
В менее идеальных случаях приложения можно проверить на использование устаревших интерфейсов, передав -Wd интерпретатору Python (сокращение для -W default ) или установив PYTHONWARNINGS=default в среде. Это включает обработку по умолчанию для всех предупреждений, включая те, которые по умолчанию игнорируются. Чтобы изменить действие, выполняемое для обнаруженных предупреждений, вы можете изменить аргумент, передаваемый в -W (например, -W error ). Познакомьтесь с флагом -W для получения более подробной информации о том, что возможно.
Доступные функции¶
Выдать предупреждение, игнорировать его или вызвать исключение. Аргумент category, если он задан, должен быть классом категории предупреждения ; по умолчанию — UserWarning . В качестве альтернативы message может быть экземпляром Warning , и в этом случае category будет проигнорирован и будет использоваться message.__class__ . В этом случае текст сообщения будет str(message) . Эта функция вызывает исключение, если фильтр предупреждений преобразовывает конкретное выданное предупреждение в ошибку. Аргумент stacklevel может использоваться функциями-обёртками, написанными на Python, например:
Заставляет предупреждение относиться к вызывающему deprecation() , а не к источнику самого deprecation() (поскольку последний нарушит цель предупреждающего сообщения).
source, если он указан — уничтоженный объект, который поднял ResourceWarning .
Изменено в версии 3.6: Добавлен параметр source.
Низкоуровневый интерфейс функциональности warn() , явно передающий сообщение, категорию, имя файла и номер строки, а также, необязательно, имя модуля и реестр (который должен быть словарём модуля __warningregistry__ ). По умолчанию в качестве имени модуля используется имя файла с удаленным .py ; если реестр не передан, предупреждение никогда не подавляется. message — строка, а category подкласс Warning или message может быть экземпляром Warning , и в этом случае category будет проигнорирован.
module_globals, если он указан, должен быть глобальным пространством имён, используемым кодом, для которого выдается предупреждение. (Аргумент используется для поддержки отображения источника для модулей, найденных в zip-файлах или других источниках импорта, не относящихся к файловой системе).
source, если он указан, — уничтоженный объект, который поднял ResourceWarning .
Изменено в версии 3.6: Добавлен параметр source.
Записать предупреждение в файл. Реализация по умолчанию вызывает formatwarning(message, category, filename, lineno, line) и записывает полученную строку в file, который по умолчанию равен sys.stderr . Вы можете заменить эту функцию на любую вызываемую, присвоив warnings.showwarning . line — строка исходного кода, которая должна присутствовать в предупреждающем сообщении; если line не указан, showwarning() попытается прочитать строку, указанную filename и lineno.
warnings. formatwarning ( message, category, filename, lineno, line=None ) ¶
Отформатировать предупреждение стандартным способом. Возвращает строку, которая может содержать встроенные символы новой строки и оканчивается новой строкой. line — строка исходного кода, которая должна добавляться в предупреждающее сообщение; если line не указан, formatwarning() попытается прочитать строку, указанную filename и lineno.
warnings. filterwarnings ( action, message=», category=Warning, module=», lineno=0, append=False ) ¶
Вставить запись в список спецификаций фильтра предупреждений . По умолчанию запись вставляется спереди; если append — истина, он вставляется в конец. Она проверяет типы аргументов, компилирует регулярные выражения message и module и вставляет их в виде кортежа в список фильтров предупреждений. Записи, расположенные ближе к началу списка, переопределяют записи, расположенные ниже в списке, если обе соответствуют конкретному предупреждению. У пропущенных аргументов значение по умолчанию, соответствует всему.
warnings. simplefilter ( action, category=Warning, lineno=0, append=False ) ¶
Вставить простую запись в список спецификаций фильтра предупреждений . Значение параметров функции такое же, как для filterwarnings() , но регулярные выражения не нужны, поскольку вставленный фильтр всегда соответствует любому сообщению в любом модуле, если совпадают категория и номер строки.
Сбросить фильтр предупреждений. Отменяет действие всех предыдущих вызовов filterwarnings() , в том числе параметров командной строки -W и вызовов simplefilter() .
Доступные менеджеры контекста¶
Менеджер контекста, который копирует и при выходе восстанавливает фильтр предупреждений и функцию showwarning() . Если аргумент record — False (по умолчанию), менеджер контекста возвращает None при входе. Если record — True , возвращается список, который постепенно заполняется объектами, как это видно с помощью настраиваемой функции showwarning() (которая также подавляет вывод в sys.stdout ). У каждого объекта в списке есть атрибуты с теми же именами, что и аргументы showwarning() .
Аргумент module принимает модуль, который будет использоваться вместо модуля, возвращаемого при импорте warnings , фильтр которого будет защищён. Аргумент существует прежде всего для тестирования самого модуля warnings .
Менеджер catch_warnings работает путём замены и последующего восстановления функции модуля showwarning() и внутреннего списка спецификаций фильтра. Это означает, что менеджер контекста изменяет глобальное состояние и, следовательно, не является потокобезопасным.
29.5. warnings — Warning control¶
Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program, where that condition (normally) doesn’t warrant raising an exception and terminating the program. For example, one might want to issue a warning when a program uses an obsolete module.
Python programmers issue warnings by calling the warn() function defined in this module. (C programmers use PyErr_WarnEx() ; see Exception Handling for details).
Warning messages are normally written to sys.stderr , but their disposition can be changed flexibly, from ignoring all warnings to turning them into exceptions. The disposition of warnings can vary based on the warning category (see below), the text of the warning message, and the source location where it is issued. Repetitions of a particular warning for the same source location are typically suppressed.
There are two stages in warning control: first, each time a warning is issued, a determination is made whether a message should be issued or not; next, if a message is to be issued, it is formatted and printed using a user-settable hook.
The determination whether to issue a warning message is controlled by the warning filter, which is a sequence of matching rules and actions. Rules can be added to the filter by calling filterwarnings() and reset to its default state by calling resetwarnings() .
The printing of warning messages is done by calling showwarning() , which may be overridden; the default implementation of this function formats the message by calling formatwarning() , which is also available for use by custom implementations.
logging.captureWarnings() allows you to handle all warnings with the standard logging infrastructure.
29.5.1. Warning Categories¶
There are a number of built-in exceptions that represent warning categories. This categorization is useful to be able to filter out groups of warnings. The following warnings category classes are currently defined:
Class | Description |
---|---|
Warning | This is the base class of all warning category classes. It is a subclass of Exception . |
UserWarning | The default category for warn() . |
DeprecationWarning | Base category for warnings about deprecated features (ignored by default). |
SyntaxWarning | Base category for warnings about dubious syntactic features. |
RuntimeWarning | Base category for warnings about dubious runtime features. |
FutureWarning | Base category for warnings about constructs that will change semantically in the future. |
PendingDeprecationWarning | Base category for warnings about features that will be deprecated in the future (ignored by default). |
ImportWarning | Base category for warnings triggered during the process of importing a module (ignored by default). |
UnicodeWarning | Base category for warnings related to Unicode. |
BytesWarning | Base category for warnings related to bytes and bytearray . |
ResourceWarning | Base category for warnings related to resource usage. |
While these are technically built-in exceptions, they are documented here, because conceptually they belong to the warnings mechanism.
User code can define additional warning categories by subclassing one of the standard warning categories. A warning category must always be a subclass of the Warning class.
29.5.2. The Warnings Filter¶
The warnings filter controls whether warnings are ignored, displayed, or turned into errors (raising an exception).
Conceptually, the warnings filter maintains an ordered list of filter specifications; any specific warning is matched against each filter specification in the list in turn until a match is found; the match determines the disposition of the match. Each entry is a tuple of the form (action, message, category, module, lineno), where:
action is one of the following strings:
message is a string containing a regular expression that the start of the warning message must match. The expression is compiled to always be case-insensitive.
category is a class (a subclass of Warning ) of which the warning category must be a subclass in order to match.
module is a string containing a regular expression that the module name must match. The expression is compiled to be case-sensitive.
lineno is an integer that the line number where the warning occurred must match, or 0 to match all line numbers.
Since the Warning class is derived from the built-in Exception class, to turn a warning into an error we simply raise category(message) .
The warnings filter is initialized by -W options passed to the Python interpreter command line. The interpreter saves the arguments for all -W options without interpretation in sys.warnoptions ; the warnings module parses these when it is first imported (invalid options are ignored, after printing a message to sys.stderr ).
29.5.2.1. Default Warning Filters¶
By default, Python installs several warning filters, which can be overridden by the command-line options passed to -W and calls to filterwarnings() .
- and PendingDeprecationWarning , and ImportWarning are ignored. is ignored unless the -b option is given once or twice; in this case this warning is either printed ( -b ) or turned into an exception ( -bb ). is ignored unless Python was built in debug mode.
Changed in version 3.2: DeprecationWarning is now ignored by default in addition to PendingDeprecationWarning .
29.5.3. Temporarily Suppressing Warnings¶
If you are using code that you know will raise a warning, such as a deprecated function, but do not want to see the warning, then it is possible to suppress the warning using the catch_warnings context manager:
While within the context manager all warnings will simply be ignored. This allows you to use known-deprecated code without having to see the warning while not suppressing the warning for other code that might not be aware of its use of deprecated code. Note: this can only be guaranteed in a single-threaded application. If two or more threads use the catch_warnings context manager at the same time, the behavior is undefined.
29.5.4. Testing Warnings¶
To test warnings raised by code, use the catch_warnings context manager. With it you can temporarily mutate the warnings filter to facilitate your testing. For instance, do the following to capture all raised warnings to check:
One can also cause all warnings to be exceptions by using error instead of always . One thing to be aware of is that if a warning has already been raised because of a once / default rule, then no matter what filters are set the warning will not be seen again unless the warnings registry related to the warning has been cleared.
Once the context manager exits, the warnings filter is restored to its state when the context was entered. This prevents tests from changing the warnings filter in unexpected ways between tests and leading to indeterminate test results. The showwarning() function in the module is also restored to its original value. Note: this can only be guaranteed in a single-threaded application. If two or more threads use the catch_warnings context manager at the same time, the behavior is undefined.
When testing multiple operations that raise the same kind of warning, it is important to test them in a manner that confirms each operation is raising a new warning (e.g. set warnings to be raised as exceptions and check the operations raise exceptions, check that the length of the warning list continues to increase after each operation, or else delete the previous entries from the warnings list before each new operation).
29.5.5. Updating Code For New Versions of Python¶
Warnings that are only of interest to the developer are ignored by default. As such you should make sure to test your code with typically ignored warnings made visible. You can do this from the command-line by passing -Wd to the interpreter (this is shorthand for -W default ). This enables default handling for all warnings, including those that are ignored by default. To change what action is taken for encountered warnings you simply change what argument is passed to -W , e.g. -W error . See the -W flag for more details on what is possible.
To programmatically do the same as -Wd , use:
Make sure to execute this code as soon as possible. This prevents the registering of what warnings have been raised from unexpectedly influencing how future warnings are treated.
Having certain warnings ignored by default is done to prevent a user from seeing warnings that are only of interest to the developer. As you do not necessarily have control over what interpreter a user uses to run their code, it is possible that a new version of Python will be released between your release cycles. The new interpreter release could trigger new warnings in your code that were not there in an older interpreter, e.g. DeprecationWarning for a module that you are using. While you as a developer want to be notified that your code is using a deprecated module, to a user this information is essentially noise and provides no benefit to them.
The unittest module has been also updated to use the ‘default’ filter while running tests.
29.5.6. Available Functions¶
Issue a warning, or maybe ignore it or raise an exception. The category argument, if given, must be a warning category class (see above); it defaults to UserWarning . Alternatively message can be a Warning instance, in which case category will be ignored and message.__class__ will be used. In this case the message text will be str(message) . This function raises an exception if the particular warning issued is changed into an error by the warnings filter see above. The stacklevel argument can be used by wrapper functions written in Python, like this:
This makes the warning refer to deprecation() ‘s caller, rather than to the source of deprecation() itself (since the latter would defeat the purpose of the warning message).
source, if supplied, is the destroyed object which emitted a ResourceWarning .
Changed in version 3.6: Added source parameter.
This is a low-level interface to the functionality of warn() , passing in explicitly the message, category, filename and line number, and optionally the module name and the registry (which should be the __warningregistry__ dictionary of the module). The module name defaults to the filename with .py stripped; if no registry is passed, the warning is never suppressed. message must be a string and category a subclass of Warning or message may be a Warning instance, in which case category will be ignored.
module_globals, if supplied, should be the global namespace in use by the code for which the warning is issued. (This argument is used to support displaying source for modules found in zipfiles or other non-filesystem import sources).
source, if supplied, is the destroyed object which emitted a ResourceWarning .
Changed in version 3.6: Add the source parameter.
Write a warning to a file. The default implementation calls formatwarning(message, category, filename, lineno, line) and writes the resulting string to file, which defaults to sys.stderr . You may replace this function with any callable by assigning to warnings.showwarning . line is a line of source code to be included in the warning message; if line is not supplied, showwarning() will try to read the line specified by filename and lineno.
warnings. formatwarning ( message, category, filename, lineno, line=None ) ¶
Format a warning the standard way. This returns a string which may contain embedded newlines and ends in a newline. line is a line of source code to be included in the warning message; if line is not supplied, formatwarning() will try to read the line specified by filename and lineno.
warnings. filterwarnings ( action, message=», category=Warning, module=», lineno=0, append=False ) ¶
Insert an entry into the list of warnings filter specifications . The entry is inserted at the front by default; if append is true, it is inserted at the end. This checks the types of the arguments, compiles the message and module regular expressions, and inserts them as a tuple in the list of warnings filters. Entries closer to the front of the list override entries later in the list, if both match a particular warning. Omitted arguments default to a value that matches everything.
warnings. simplefilter ( action, category=Warning, lineno=0, append=False ) ¶
Insert a simple entry into the list of warnings filter specifications . The meaning of the function parameters is as for filterwarnings() , but regular expressions are not needed as the filter inserted always matches any message in any module as long as the category and line number match.
Reset the warnings filter. This discards the effect of all previous calls to filterwarnings() , including that of the -W command line options and calls to simplefilter() .
29.5.7. Available Context Managers¶
A context manager that copies and, upon exit, restores the warnings filter and the showwarning() function. If the record argument is False (the default) the context manager returns None on entry. If record is True , a list is returned that is progressively populated with objects as seen by a custom showwarning() function (which also suppresses output to sys.stdout ). Each object in the list has attributes with the same names as the arguments to showwarning() .
The module argument takes a module that will be used instead of the module returned when you import warnings whose filter will be protected. This argument exists primarily for testing the warnings module itself.
The catch_warnings manager works by replacing and then later restoring the module’s showwarning() function and internal list of filter specifications. This means the context manager is modifying global state and therefore is not thread-safe.
warnings — Simple Guide to Handle Warnings Messages in Python¶
Warnings messages are generally raised when the situation is not that worse that the program should be terminated. It’s generally raised to alert programmers. For example, a programmer might call some function whose signature is changing in the future or method is going to be deprecated. Python provides a module named warnings which lets us works with warnings. It lets us raise warnings, filter warnings, format warnings, etc. It even let us change warnings into errors when the situation arises like making a program fail which is still using some old obsolete version of code that must be changed now. The warnings module by default directs all warnings messages to sys.stderr. It provides methods that can let us direct warnings messages to other mediums as well. The warnings module also provides us with filters that let us filter warnings messages and prevent them from printing repeatedly. It provides very fine-grained control over warnings. All the warnings available by default are a subclass of Warning class which itself is a subclass of Exception class. Even though warnings are subclasses of Exception, it does not halt the program until explicitly asked to do so. As a part of this tutorial, we’ll explore the API of the warnings module with simple examples to make it easy to grasp.
We have below-highlighted methods available with the module that we’ll explain with examples. We have grouped methods according to their usage.
- Methods to Create Warnings — These methods are used to raise warnings.
- warn()
- warn_explicit()
- showwarning()
- formatwarning()
- filterwarnings()
- simplefilter()
- resetwarnings()
- catch_warnings()
We’ll now explain the usage of these methods with simple examples one by one.
Example 1: Raise Deprecation Warning Using warn() ¶
As a part of this example, we’ll explain how we can use warn() method to raise warning messages. We have created simple script which calls 2 functions (addition() and add()) to add numbers. The function addition() can accept only two numbers to be added and obsolete whereas add() function can add as many numbers given as an argument to it. We have raised a deprecation warning from addition() function with the message that the function is deprecated and should not be used going forward as it’ll be removing in future releases from the code.
warn() Parameters¶
Below are important parameters of the warn() method which needs to be set in order for the method to work properly.
- message — It accepts a string message that will be printed when this warning is raised.
- category — This parameter accepts any of the Warning category (a subclass of Warning) from the list of available warnings with python. If not provided warning of type Warning will be raised.
- stacklevel — It accepts an integer argument that specifies which method should be printed in the warning message. The default value is 1. It’ll print method named in which it’s called. If we give the value of 2 then it’ll go one level up and print the caller of the method.
A full list of warning categories is available here
warnings_example_1.py¶
OUTPUT
Below we have again written script with only one minor change that we have included stacklevel argument with a value of 2 in our code. We can see that now the output is including a line of our code where the method is getting called.
warnings_example_1.py¶
OUTPUT
Example 2: Raise Deprecation Warning Using warn_explicit() ¶
As a part of our second example, we’ll explain the usage of warn_explicit() method. It works almost like warn() method but provides more control over warning. It let us specify the filename, line number, and module of the warnings.
warn_explicit() Parameters¶
Below we have provides important parameters of warn_explicit() method.
- message — It accepts a string message that will be printed when this warning is raised.
- category — This parameter accepts any of the Warning category (a subclass of Warning) from the list of available warnings with python. If not provided warning of type Warning will be raised.
- filename — It accepts filename where a warning has occurred.
- lineno — It accepts the line number of the method which has a warning.
- module — It accepts the module name of the code that has a warning.
Our second example code is almost the same as the first example with the only difference being that we have used warn_explicit() to raise warning instead of warn(). We have specified filename as name so that it takes filename directly and line no as 3 because method addition starts at 3rd line.
warnings_example_2.py¶
OUTPUT
Example 3: Print Deprecation Warning Using showwarning() ¶
As a part of our third example, we’ll demonstrate how we can use showwarning() method to direct warnings to sys.stdout instead of default sys.stderr. This method also lets us direct warning messages to a file if needed.
In this example, we have used code same as our previous examples with minor changes. We’ll be using the same example with changes for all examples of our tutorial. We have moved the code for method addition() and add() to a file named addition.py. We have kept our remaining original code in a file named warnings_example_3.py. We are calling addition() and add() method to be importing the addition module. We have kept code for showwarning() in addition() method.
showwarning() Parameters¶
Below is a list of important parameters of showwarning() method which can be changed as per requirements.
- message — It accepts a string message that will be printed when this warning is raised.
- category — This parameter accepts any of the Warning category (a subclass of Warning) from the list of available warnings with python. If not provided warning of type Warning will be raised.
- filename — It accepts filename where a warning has occurred.
- lineno — It accepts the line number of the method which has a warning. This line text will be printed in a warning message if we have not explicitly provided line parameter.
- file — It accepts file name where warning messages will be directed. It can even accept sys.stdout and will direct messages to standard output. By default this parameter has None value and messages will be directed to sys.stderr.
- line — This parameter accepts a string which is the line that will be printed along with the error message. This parameter is None by default and code at line lineno in file filename will be included in the message.
We can see from the output below that we have not provided line parameter value hence it’s printing line number 4 of addition.py in the warning message. We have directed a warning message to sys.stdout.
addition.py¶
warnings_example_3.py¶
OUTPUT
Below we have modified our code of addition.py a little but where we have provided string for line parameter. We can notice from the output that the warning message has now a string from that parameter and not retrieved from a combination of filename and lineno parameters like earlier.
addition.py¶
OUTPUT
Example 4: Print Deprecation Warning Using formatwarning() ¶
As a part of our sixth example, we’ll demonstrate usage of formatwarning() method. This method has the same format and usage as that of showwarning()but it returns a warning message as a string instead of printing it. This can be useful if we don’t want to print a warning message at that time and have a different plan of handling it.
We have kept code for addition() and add() methods in a different file named addition_modified.py like earlier. We are calling formatwarning() in addition() method and storing its output in a variable named warning_result. We are then printing warning_result. Our rest of the code which calls these two methods is kept in warnings_example_4.py file.
addition_modified.py¶
warnings_example_4.py¶
OUTPUT
Example 5: Filter All Warnings Using simplefilter() ¶
As a part of our fifth example, we’ll demonstrate the usage of simplefilter() method which can be used to filter and remove some of the warning messages from all that will be printed. If our code is repeatedly calling some method that is obsolete then the output will be flooded with warning messages. We want to prevent this and want a warning message to be raised once. This can be done using simplefilter() method. This method lets us filter all warning messages rather than filtering warning messages of a particular module or file.
The filter is defined as a tuple of five values in warnings. When a warning is raised, it’s matched with conditions of filters one by one from the list of filters until a match is found. If we found a match with a filter then that warning will be suppressed else the default action is applied as explained below in filter values. We can access the list of filters which currently set at any point by calling filters attribute of the warnings module and it’ll return a list of filters where individual entry is a tuple of 5 values explaining that filter.
Warning Filter Values Explanation¶
Each filer has the below mentioned five values.
- action — It holds one of the following string specifying how to filter warning messages. Below is a list of possible string values for action.
- default — It prints the first matching occurrence of warning (module + line no). It warning raised for the combination of module and line number will be printed only once.
- error — It’ll convert warning into error and halt program execution. This can be useful if we want to stop programmers from using a particular code. The failure will force them to switch from it.
- ignore — This will ignore all warnings which match this filter’s conditions.
- always — This will print all warnings which match this filter’s conditions.
- module — This will print the first occurrence of warning for each module and line number.
- once — This will print the first occurrence of warning only regardless of the line number.
Our code below has same methods addition() and add() like earlier where addition() method raises future warning. Our code first loops through a list of filters and prints them. It then calls addition() method and adds a new filter that filters all future warnings from all modules. We are then printing all filters again and calling addition() method again to check whether the warning raised by it is suppressed after adding the filter.
simplefilter() Parameters¶
Below we have included an explanation of the parameters of method simplefilter().
- action — We specify one of the strings mentioned above in action filter values for this parameter.
- category — This parameter accepts any of the Warning category (a subclass of Warning) from the list of available warnings with python. It has the default value Warning.
- lineno — It accepts integer value specifying line number where warning must match. If we specify 0 then all lines of a file are considered and filtered else only warning occurred from the line number mentioned is filtered.
- append — This parameter accepts boolean value specifying whether the filter created by this method should be appended at the end of the list of filters or not. By default simplefilter() method inserts a filter at the beginning of the list.
We can see from the output when we run the script below that after we have introduced a new future warning filter, a list of filters has an entry for it, and a warning raised by addition() method is suppressed as well.
warnings_example_5.py¶
OUTPUT
Example 6: Filter Warning at Particular Line Number Using simplefilter() ¶
As a part of our sixth example, we are again demonstrating usage of simplefilter() method. The code is almost the same as the last example with minor changes. First, we have changed the value of lineno parameter from 0 to 4 in method simplefilter(). This change will add a filter that will only filter FutureWarning which occurs at line number 4 from any module.
We have created two version of addition() method (addition1() and addition2()). Both raise a future warning message. We are calling both methods for calculating the addition of two numbers before the introduction of the filter and after. We are also printing a list of filters before and after the addition of filters for verification purposes.
We can see from the output that it is a filtering warning message raised by addition1() method only and not the one raised by addition2() after the introduction of the filter.
warnings_example_6.py¶
OUTPUT
Example 7: FIlter Warnings Of Particular Module Using filterwarnings() ¶
As a part of our seventh example, we’ll demonstrate usage of filterwarnings() method. This method also like the simplefilter() is used to add a new filter to the list of filters. The MAJOR difference between this method and simplefilter() is that this method provides finer control on filtering warning messages that let us filter warning of particular module whereas simplefilter() works on all modules. It even let us match warning message with a regular expression for filtering.
filterwarnings() Parameters¶
Below we have mentioned a list of parameters of filterwarnings().
- action — Same meaning as simplefilter().
- category — Same meaning as simplefilter().
- lineno — Same meaning as simplefilter().
- append — Same meaning as simplefilter().
- message — This parameter accepts a string and all warning messages which has this string will be filtered.
- module — This parameter accepts a string and warning messages raised from all modules which have this string in its name will be suppressed.
We have created 3 files to explain the usage of filterwarnings() method.
- addition1.py — It has definition of method addition1() and add(). The addition1() method raised future warning.
- addition2.py — It has the definition of addition2() method which raises a future warning.
- warnings_example_7.py — It has code that first prints a list of existing filters. It then calls addition1() and addition2() methods. After that, it creates a filter using filterwarnings() and prints a list of filters again. At last, it calls addition1() and addition2() methods again.
When we run script warnings_example_7.py, we can notice from the output that the warning raised by addition1() method is suppressed. Please make a note that warning is mentioned at line number 4 in both addition1.py and addition2.py file but only the warning raised by addition1.py file is filtered. The reason for this is because we have set the module parameter of filterwarnings() to string addition1.
addition1.py¶
addition2.py¶
warnings_example_7.py¶
OUTPUT
Example 8: Reset Warnings Using resetwarnings() ¶
As a part of our eight example, we’ll demonstrate how to use resetwarnings() method. This method clears all filters which are set by default and by the program.
Below we have created a simple script to explain the usage of resetwarnings() method. We are printing a list of filters at the beginning of the script. Then we are adding few filters using simplefilter() & filterwarnings() methods and printing a list of filters to check all filters are added properly. At last, we are calling resetwarnings() method and printing the list of filters again.
We can notice from the output that all filters are cleared by resetwarnings() method.
Please make a note that we have appended the last 2 filters of our 4 filters at the end of the list of filters by setting append parameter to True.
warnings_example_8.py¶
OUTPUT
Example 9: Turn Warning into Error using Filter¶
As a part of our ninth example, we are demonstrating how we can convert a warning to an error by setting the action parameter to error in simplefilter() method. Our code for this example is exactly the same as our fifth example with the only difference that we have set action in simplefilter() method to error instead of ignore. This will instruct the interpreter to raise errors when this warning happens.
Please make a note that we can perform the same functionality using filterwarnings() method as well.
warnings_example_9.py¶
OUTPUT
Example 10: Using Context Manager to Test and Catch Warnings¶
As a part of our tenth and last example, we’ll demonstrate how we can use context manager using catch_warnings() method to test a particular part of our code. The catch_warnings() provides a context manager that can wrap code without changing filters set outside of it. We can test code inside the context manager by introducing new filters and removing filters but it won’t change the filter list outside of the context manager. We can also record warnings raised during context manager by setting record parameter of catch_warnings() method to True.
We have created a simple example below to explain the usage of context manager created using catch_warnings(). We have created a method named addition1() which adds two numbers and raises FutureWarning. We have created another method named addition2() which also adds two numbers and raises DeprecationWarning. Our main code first prints a list of filters and calls addition1() and addition2() methods. It then adds filters to ignore future warnings occurring at line number 4 to the list of filters. We then go on to create a context manager using catch_warnings(). Inside the context manager, we first clear all filters using resetwarnings() method, add the filter to ignore deprecation warnings occurring anywhere in code, and print a list of filters. Then we call addition1() and addition2() methods. At last, we use the context manager instance to print warnings raised. Once we are outside of the context manager, we again print a list of filters and call addition1() and addition2() methods.
We can notice from the output that when we first call addition1() and addition2() methods, both warning messages are printed. When we call both methods inside of context manager, only a warning message of addition1() is raised because inside context manager, we have created a deprecation warning suppress filter. Once we are out of context manager, we have again called both methods and we can see that warning message for method addition2() is printed because we have created a filter to ignore future warning occurring at line number 4 in the code.
warnings_example_10.py¶
OUTPUT
This ends our small tutorial explaining the usage of warnings API with simple examples. Please feel free to let us know your views in the comments section.
Sunny Solanki
Intro: Software Developer | Bonsai Enthusiast
About: Sunny Solanki holds a bachelor’s degree in Information Technology (2006-2010) from L.D. College of Engineering. Post completion of his graduation, he has 8.5+ years of experience (2011-2019) in the IT Industry (TCS). His IT experience involves working on Python & Java Projects with US/Canada banking clients. Since 2019, he’s primarily concentrating on growing CoderzColumn.
His main areas of interest are AI, Machine Learning, Data Visualization, and Concurrent Programming. He has good hands-on with Python and its ecosystem libraries.
Apart from his tech life, he prefers reading biographies and autobiographies. And yes, he spends his leisure time taking care of his plants and a few pre-Bonsai trees.
Contact: sunny.2309@yahoo.in
Stuck Somewhere? Need Help with Coding? Have Doubts About the Topic/Code?
When going through coding examples, it’s quite common to have doubts and errors.
If you have doubts about some code examples or are stuck somewhere when trying our code, send us an email at coderzcolumn07@gmail.com. We’ll help you or point you in the direction where you can find a solution to your problem.
You can even send us a mail if you are trying something new and need guidance regarding coding. We’ll try to respond as soon as possible.
Want to Share Your Views? Have Any Suggestions?
- provide some suggestions on topic
- share your views
- include some details in tutorial
- suggest some new topics on which we should create tutorials/blogs
warnings
Suppress Warnings In Python: All You Need To Know
If you are a python programmer or have worked with coding on Python, you definitely would have faced warnings and errors when compiling or running the code. Therefore in this article, we are going to discuss How to suppress warnings in Python.
In some cases, when you want to suppress or ignore warnings in Python, you need to use some specific filter function of the warnings module. We will discuss the usage of those functions in this article. Thus, you can learn to ignore or suppress warnings when needed.
Warnings And Its Types
A warning in Python is a message that programmer issues when it is necessary to alert a user of some condition in their code. Although this condition normally doesn’t lead to raising an exception and terminating the program. Let’s understand the types of warnings.
The table given above shows different warning classes and their description.
Class Description BytesWarning Base category for warnings related to bytes and bytearray. DeprecationWarning Base category for warnings about deprecated features when those warnings are intended for other Python developers (ignored by default, unless triggered by code in main). FutureWarning Base category for warnings about deprecated features when those warnings are intended for end users of applications written in Python. ImportWarning Base category for warnings triggered during the process of importing a module (ignored by default). PendingDeprecationWarning Base category for warnings about features that will be deprecated in the future (ignored by default). ResourceWarning Base category for warnings related to resource usage (ignored by default). RuntimeWarning Base category for warnings about dubious runtime features. SyntaxWarning Base category for warnings about dubious syntactic features. UnicodeWarning Base category for warnings related to Unicode. UserWarning The default category for warn(). Warning This is the base class of all warning category classes. It is a subclass of Exception. Table 1.1
Suppress All Warnings In Python
Just like everything in Python is an object, similar warnings are also objects in Python. You can program them too. You have to use the ‘warnings’ package to ignore warnings. Firstly we will see how you can ignore all warnings in python step by step:
- Import ‘warnings’ module
- Use the ‘filterwarnings()’ function to ignore all warnings by setting ‘ignore’ as a parameter.
Suppress Specific Warnings In Python
Further, let’s see how to suppress specific warnings in Python using the warnings package. For stopping particular signs, we will need to add another parameter in the ‘filterwarnings()’ function, i.e., category.
- import warnings
- Use the ‘filterwarnings()’ function to ignore all warnings by setting ‘ignore’ as a parameter. In addition to that, add a parameter ‘category’ and specify the type of warning.
Similarly, you can add any category you desire and suppress those warnings.
Suppressing Pandas warnings
You can even suppress pandas warnings in order to do that. You have to write a code to suppress warnings before importing pandas.
Suppressing Warnings In Tensorflow
Further, you can even ignore tensorflow warnings if you want. The way to ignore warnings in tensorflow is a bit different. Let’s understand step by step:
- For TF 2.x, you can use the following code
- For TF 1.x, you can use the following code
The codes mentioned above are used to remove logging information. Therefore any messages will not be printed. Further, if you want to remove deprecated warnings or future warnings in TF 1. x, you can use:
To suppress futurewarnings along with current deprecated warnings, use:
Suppress Warnings in Python IDE (Pycharm)
When you use an IDE like Pycharm, you can disable inspections, so no warnings are raised. Moreover, you can also suppress a warning for a particular line of code.
- Disable warnings for a particular line of code.
By commenting ‘noqa,’ you can suppress warnings for that single line of code. In addition to that, if you want to suppress all warnings, you can follow these given steps:
- Go to Settings dialog ( Ctrl+Alt+S ) and select Editor/Inspections.
- And then go to the inspection you want to disable, further uncheck the checkbox next to it.
- Apply the changes and close the dialog box.
Suppress Pylint Warnings
To disable pylint warnings, you can also use the symbolic identities of warnings rather than memorize all the code numbers, for example:
You can use this comment to disable any warnings for that line, and it will apply to the code that is coming after it. Similarly, it can be used after an end of a line for which it is meant.
Disable Warnings In Jupyter Notebook
You can suppress all warnings in the jupyter notebook by using the warnings module and using functions like ‘simplefilter()’ and ‘filterwarnings()’.
Further, to suppress warnings for a particular line of codes, you can use :
Disable Warning While Ansible Execution
You can disable all the warnings when using ansible by making the deprecation_warnings = ‘false’ in defaults section of your effective configuration file i.e.(/etc/ansible/ansible.cfg,
Suppress Matplotlib Warnings
To suppress the matplotlib library , first import all required modules in addition to that import warnings module. Further use the’ filterwarnings()’ function to disable the warnings.
Then finish writing your remaining code, you will see no warnings pop up, and the code will be executed.
Disable SSL Warnings Python Requests
Further, let’s see how you can disable security certificate checks for requests in Python.
When we use the requests module, we pass ‘verify = False’ along with the URL, which disables the security checks.
Bypassing the ‘verify=False,’ you can make the program execute without errors.
FAQs on Suppress Warnings Python
You can use the ‘filterwarnings()’ function from the warnings module to ignore warnings in Python.
You can use the syntax ‘np.seterr(all=”ignore”)’ to ignore all warnings.
You can use the ‘filterwarnings()’ function from the warnings module and set ‘default’ as a parameter to re-enable warnings.
Conclusion
In this article, we have seen how we can suppress warnings when needed, although warnings are essential as they can signify a problem you might leave unseen. Therefore it is advised to code with warnings enabled. Only disable them when it is of utmost importance to ignore them.