Как отключить все предупреждения в IPython
Работа в IPython может иногда сопровождаться появлением различных предупреждений, которые генерируются с помощью вызовов warnings.warn из разных пакетов.
Алексей Кодов
Автор статьи
7 июля 2023 в 18:24
Работа в IPython может иногда сопровождаться появлением различных предупреждений, которые генерируются с помощью вызовов warnings.warn из разных пакетов. Это может быть нежелательно в некоторых ситуациях, например, при создании обучающего видео, где такие предупреждения могут сбивать с толку зрителей.
Пример
Рассмотрим простой пример кода на Python, который использует библиотеку numpy:
import numpy as np A = np.array([1, 2, 3]) B = np.array([2, 2, 2]) C = A / B
В приведенном примере предупреждения не будет, но если в массиве B будет хотя бы один ноль, то при попытке деления на ноль появится предупреждение.
Решение
Отключить все предупреждения в IPython можно с помощью модуля warnings . Для этого можно использовать функцию filterwarnings с аргументом ‘ignore’ , который означает, что все предупреждения нужно игнорировать.
import warnings warnings.filterwarnings('ignore')
Этот код нужно выполнить перед запуском основной части программы, которая может генерировать предупреждения. После его выполнения все последующие предупреждения будут игнорироваться.
Хотя это может быть полезно в некоторых случаях, стоит помнить, что предупреждения предназначены для того, чтобы сообщить о потенциальных проблемах в коде. Игнорирование всех предупреждений может привести к тому, что некоторые ошибки не будут замечены вовремя.
Временное подавление предупреждений Python
Если вы используете код, который вызывает предупреждение, например из за устаревшей функции, но не хотите видеть эти предупреждения, даже если предупреждения были явно сконфигурированы через командную строку, то можно отключить предупреждение с помощью контекстного менеджера warnings.catch_warnings() :
import warnings def fxn(): warnings.warn("deprecated", DeprecationWarning) with warnings.catch_warnings(): warnings.simplefilter("ignore") fxn()
В менеджере контекста все предупреждения будут просто игнорироваться. Это позволяет использовать устаревший код без получения предупреждений, не подавляя предупреждение для другого кода.
Примечание: такое поведение может быть гарантировано только в однопоточном приложении. Если два или более потоков используют менеджер контекста warnings.catch_warnings() одновременно, поведение не протестировано.
- КРАТКИЙ ОБЗОР МАТЕРИАЛА.
- Категории предупреждений модуля warnings
- Фильтр предупреждений модуля warnings
- Переопределение фильтров предупреждений warnings
- Подавление предупреждений warning
- Тестирование предупреждений warnings
- Функция warn() модуля warnings
- Функция warn_explicit() модуля warnings
- Функция showwarning() модуля warnings
- Функция formatwarning() модуля warnings
- Функция filterwarnings() модуля warnings
- Функция simplefilter() модуля warnings
- Функция resetwarnings() модуля warnings
- Класс catch_warnings() модуля warnings
How to ignore warnings in Python
In Python, you can use the warnings module from the standard library to control warnings, such as ignoring (suppressing) warnings or turning matching warnings into exceptions.
- Examples of warnings
- SyntaxWarning by comparing literals with is
- SettingWithCopyWarning in pandas
- Ignore all warnings
- Specify warning categories to ignore
Although the warnings module provides a warn() function to issue warnings, this article will not cover it. Please refer to the official documentation if you want to issue warnings in your own functions.
All sample code in this article assumes that the following modules have been imported. The pandas.DataFrame is only used as an example of a warning; its specific contents aren’t our focus here.
import warnings import pandas as pd df = pd.DataFrame([[0, 1, 2], [3, 4, 5]])Examples of warnings
SyntaxWarning by comparing literals with is
Comparing string or numeric literals with is will trigger a SyntaxWarning .
print(100 is 100) # True # # <>:1: SyntaxWarning: "is" with a literal. Did you mean "= c1"># <>:1: SyntaxWarning: "is" with a literal. Did you mean "= c1"># /var/folders/rf/b7l8_vgj5mdgvghn_326rn_c0000gn/T/ipykernel_60077/3973932639.py:1: SyntaxWarning: "is" with a literal. Did you mean "= c1"># print(100 is 100)SettingWithCopyWarning in pandas
A SettingWithCopyWarning is issued for chained assignments in pandas.
df.iloc[:1][0] = 0 # /var/folders/rf/b7l8_vgj5mdgvghn_326rn_c0000gn/T/ipykernel_60077/1345802814.py:1: SettingWithCopyWarning: # A value is trying to be set on a copy of a slice from a DataFrame. # Try using .loc[row_indexer,col_indexer] = value instead # # See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy # df.iloc[:1][0] = 0Ignore warnings
Use warnings.simplefilter() to change the handling of warnings and warnings.resetwarnings() to reset.
- warnings.simplefilter() — Warning control — Python 3.11.4 documentation
- warnings.resetwarnings() — Warning control — Python 3.11.4 documentation
Ignore all warnings
All warnings are ignored by setting the first argument action of warnings.simplefilter() to ‘ignore’ .
warnings.simplefilter('ignore') print(100 is 100) # True df.iloc[:1][0] = 0Besides ‘ignore’ , for the action argument, you can specify ‘once’ , which issues a warning only the first time it occurs. See the official documentation for other options available for action .
Specify warning categories to ignore
You can specify a warning category for the second argument category of warnings.simplefilter() . Warning categories include FutureWarning , DeprecationWarning , SyntaxWarning , RuntimeWarning , etc.
By default, category is set to Warning , the base class for all warning category classes. As in the example above, this means all warnings are covered.
Warning categories are described in the warning message. As mentioned above, is comparison for literals issues a SyntaxWarning and chained assignment issues a SettingWithCopyWarning .
For example, if category=SyntaxWarning , warnings for is comparison for literals are disabled, but warnings for chained assignments are still issued.
warnings.resetwarnings() warnings.simplefilter('ignore', SyntaxWarning) print(100 is 100) # True df.iloc[:1][0] = 0 # /var/folders/rf/b7l8_vgj5mdgvghn_326rn_c0000gn/T/ipykernel_60077/1345802814.py:1: SettingWithCopyWarning: # A value is trying to be set on a copy of a slice from a DataFrame. # Try using .loc[row_indexer,col_indexer] = value instead # # See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy # df.iloc[:1][0] = 0The warning category for chained assignments, SettingWithCopyWarning , is defined in pandas. You need to specify it as pd.core.common.SettingWithCopyWarning , not merely SettingWithCopyWarning .
warnings.resetwarnings() # warnings.simplefilter('ignore', SettingWithCopyWarning) # NameError: name 'SettingWithCopyWarning' is not defined warnings.simplefilter('ignore', pd.errors.SettingWithCopyWarning) print(100 is 100) # True # # <>:1: SyntaxWarning: "is" with a literal. Did you mean "= c1"># <>:1: SyntaxWarning: "is" with a literal. Did you mean "= c1"># /var/folders/rf/b7l8_vgj5mdgvghn_326rn_c0000gn/T/ipykernel_60077/3973932639.py:1: SyntaxWarning: "is" with a literal. Did you mean "= c1"># print(100 is 100) df.iloc[:1][0] = 0Treat warnings as exceptions
Unlike exceptions, the process continues to run, even if a warning is issued.
If you want to stop the process for warnings like exceptions, set action of warnings.simplefilter() to ‘error’ .
warnings.resetwarnings() warnings.simplefilter('error') # print(100 is 100) # SyntaxError: "is" with a literal. Did you mean "= source">source: warnings_basic.py