17db96d56Sopenharmony_ci:mod:`warnings` --- Warning control 27db96d56Sopenharmony_ci=================================== 37db96d56Sopenharmony_ci 47db96d56Sopenharmony_ci.. module:: warnings 57db96d56Sopenharmony_ci :synopsis: Issue warning messages and control their disposition. 67db96d56Sopenharmony_ci 77db96d56Sopenharmony_ci**Source code:** :source:`Lib/warnings.py` 87db96d56Sopenharmony_ci 97db96d56Sopenharmony_ci.. index:: single: warnings 107db96d56Sopenharmony_ci 117db96d56Sopenharmony_ci-------------- 127db96d56Sopenharmony_ci 137db96d56Sopenharmony_ciWarning messages are typically issued in situations where it is useful to alert 147db96d56Sopenharmony_cithe user of some condition in a program, where that condition (normally) doesn't 157db96d56Sopenharmony_ciwarrant raising an exception and terminating the program. For example, one 167db96d56Sopenharmony_cimight want to issue a warning when a program uses an obsolete module. 177db96d56Sopenharmony_ci 187db96d56Sopenharmony_ciPython programmers issue warnings by calling the :func:`warn` function defined 197db96d56Sopenharmony_ciin this module. (C programmers use :c:func:`PyErr_WarnEx`; see 207db96d56Sopenharmony_ci:ref:`exceptionhandling` for details). 217db96d56Sopenharmony_ci 227db96d56Sopenharmony_ciWarning messages are normally written to :data:`sys.stderr`, but their disposition 237db96d56Sopenharmony_cican be changed flexibly, from ignoring all warnings to turning them into 247db96d56Sopenharmony_ciexceptions. The disposition of warnings can vary based on the :ref:`warning category 257db96d56Sopenharmony_ci<warning-categories>`, the text of the warning message, and the source location where it 267db96d56Sopenharmony_ciis issued. Repetitions of a particular warning for the same source location are 277db96d56Sopenharmony_citypically suppressed. 287db96d56Sopenharmony_ci 297db96d56Sopenharmony_ciThere are two stages in warning control: first, each time a warning is issued, a 307db96d56Sopenharmony_cidetermination is made whether a message should be issued or not; next, if a 317db96d56Sopenharmony_cimessage is to be issued, it is formatted and printed using a user-settable hook. 327db96d56Sopenharmony_ci 337db96d56Sopenharmony_ciThe determination whether to issue a warning message is controlled by the 347db96d56Sopenharmony_ci:ref:`warning filter <warning-filter>`, which is a sequence of matching rules and actions. Rules can be 357db96d56Sopenharmony_ciadded to the filter by calling :func:`filterwarnings` and reset to its default 367db96d56Sopenharmony_cistate by calling :func:`resetwarnings`. 377db96d56Sopenharmony_ci 387db96d56Sopenharmony_ciThe printing of warning messages is done by calling :func:`showwarning`, which 397db96d56Sopenharmony_cimay be overridden; the default implementation of this function formats the 407db96d56Sopenharmony_cimessage by calling :func:`formatwarning`, which is also available for use by 417db96d56Sopenharmony_cicustom implementations. 427db96d56Sopenharmony_ci 437db96d56Sopenharmony_ci.. seealso:: 447db96d56Sopenharmony_ci :func:`logging.captureWarnings` allows you to handle all warnings with 457db96d56Sopenharmony_ci the standard logging infrastructure. 467db96d56Sopenharmony_ci 477db96d56Sopenharmony_ci 487db96d56Sopenharmony_ci.. _warning-categories: 497db96d56Sopenharmony_ci 507db96d56Sopenharmony_ciWarning Categories 517db96d56Sopenharmony_ci------------------ 527db96d56Sopenharmony_ci 537db96d56Sopenharmony_ciThere are a number of built-in exceptions that represent warning categories. 547db96d56Sopenharmony_ciThis categorization is useful to be able to filter out groups of warnings. 557db96d56Sopenharmony_ci 567db96d56Sopenharmony_ciWhile these are technically 577db96d56Sopenharmony_ci:ref:`built-in exceptions <warning-categories-as-exceptions>`, they are 587db96d56Sopenharmony_cidocumented here, because conceptually they belong to the warnings mechanism. 597db96d56Sopenharmony_ci 607db96d56Sopenharmony_ciUser code can define additional warning categories by subclassing one of the 617db96d56Sopenharmony_cistandard warning categories. A warning category must always be a subclass of 627db96d56Sopenharmony_cithe :exc:`Warning` class. 637db96d56Sopenharmony_ci 647db96d56Sopenharmony_ciThe following warnings category classes are currently defined: 657db96d56Sopenharmony_ci 667db96d56Sopenharmony_ci.. tabularcolumns:: |l|p{0.6\linewidth}| 677db96d56Sopenharmony_ci 687db96d56Sopenharmony_ci+----------------------------------+-----------------------------------------------+ 697db96d56Sopenharmony_ci| Class | Description | 707db96d56Sopenharmony_ci+==================================+===============================================+ 717db96d56Sopenharmony_ci| :exc:`Warning` | This is the base class of all warning | 727db96d56Sopenharmony_ci| | category classes. It is a subclass of | 737db96d56Sopenharmony_ci| | :exc:`Exception`. | 747db96d56Sopenharmony_ci+----------------------------------+-----------------------------------------------+ 757db96d56Sopenharmony_ci| :exc:`UserWarning` | The default category for :func:`warn`. | 767db96d56Sopenharmony_ci+----------------------------------+-----------------------------------------------+ 777db96d56Sopenharmony_ci| :exc:`DeprecationWarning` | Base category for warnings about deprecated | 787db96d56Sopenharmony_ci| | features when those warnings are intended for | 797db96d56Sopenharmony_ci| | other Python developers (ignored by default, | 807db96d56Sopenharmony_ci| | unless triggered by code in ``__main__``). | 817db96d56Sopenharmony_ci+----------------------------------+-----------------------------------------------+ 827db96d56Sopenharmony_ci| :exc:`SyntaxWarning` | Base category for warnings about dubious | 837db96d56Sopenharmony_ci| | syntactic features. | 847db96d56Sopenharmony_ci+----------------------------------+-----------------------------------------------+ 857db96d56Sopenharmony_ci| :exc:`RuntimeWarning` | Base category for warnings about dubious | 867db96d56Sopenharmony_ci| | runtime features. | 877db96d56Sopenharmony_ci+----------------------------------+-----------------------------------------------+ 887db96d56Sopenharmony_ci| :exc:`FutureWarning` | Base category for warnings about deprecated | 897db96d56Sopenharmony_ci| | features when those warnings are intended for | 907db96d56Sopenharmony_ci| | end users of applications that are written in | 917db96d56Sopenharmony_ci| | Python. | 927db96d56Sopenharmony_ci+----------------------------------+-----------------------------------------------+ 937db96d56Sopenharmony_ci| :exc:`PendingDeprecationWarning` | Base category for warnings about features | 947db96d56Sopenharmony_ci| | that will be deprecated in the future | 957db96d56Sopenharmony_ci| | (ignored by default). | 967db96d56Sopenharmony_ci+----------------------------------+-----------------------------------------------+ 977db96d56Sopenharmony_ci| :exc:`ImportWarning` | Base category for warnings triggered during | 987db96d56Sopenharmony_ci| | the process of importing a module (ignored by | 997db96d56Sopenharmony_ci| | default). | 1007db96d56Sopenharmony_ci+----------------------------------+-----------------------------------------------+ 1017db96d56Sopenharmony_ci| :exc:`UnicodeWarning` | Base category for warnings related to | 1027db96d56Sopenharmony_ci| | Unicode. | 1037db96d56Sopenharmony_ci+----------------------------------+-----------------------------------------------+ 1047db96d56Sopenharmony_ci| :exc:`BytesWarning` | Base category for warnings related to | 1057db96d56Sopenharmony_ci| | :class:`bytes` and :class:`bytearray`. | 1067db96d56Sopenharmony_ci+----------------------------------+-----------------------------------------------+ 1077db96d56Sopenharmony_ci| :exc:`ResourceWarning` | Base category for warnings related to | 1087db96d56Sopenharmony_ci| | resource usage (ignored by default). | 1097db96d56Sopenharmony_ci+----------------------------------+-----------------------------------------------+ 1107db96d56Sopenharmony_ci 1117db96d56Sopenharmony_ci.. versionchanged:: 3.7 1127db96d56Sopenharmony_ci Previously :exc:`DeprecationWarning` and :exc:`FutureWarning` were 1137db96d56Sopenharmony_ci distinguished based on whether a feature was being removed entirely or 1147db96d56Sopenharmony_ci changing its behaviour. They are now distinguished based on their 1157db96d56Sopenharmony_ci intended audience and the way they're handled by the default warnings 1167db96d56Sopenharmony_ci filters. 1177db96d56Sopenharmony_ci 1187db96d56Sopenharmony_ci 1197db96d56Sopenharmony_ci.. _warning-filter: 1207db96d56Sopenharmony_ci 1217db96d56Sopenharmony_ciThe Warnings Filter 1227db96d56Sopenharmony_ci------------------- 1237db96d56Sopenharmony_ci 1247db96d56Sopenharmony_ciThe warnings filter controls whether warnings are ignored, displayed, or turned 1257db96d56Sopenharmony_ciinto errors (raising an exception). 1267db96d56Sopenharmony_ci 1277db96d56Sopenharmony_ciConceptually, the warnings filter maintains an ordered list of filter 1287db96d56Sopenharmony_cispecifications; any specific warning is matched against each filter 1297db96d56Sopenharmony_cispecification in the list in turn until a match is found; the filter determines 1307db96d56Sopenharmony_cithe disposition of the match. Each entry is a tuple of the form (*action*, 1317db96d56Sopenharmony_ci*message*, *category*, *module*, *lineno*), where: 1327db96d56Sopenharmony_ci 1337db96d56Sopenharmony_ci* *action* is one of the following strings: 1347db96d56Sopenharmony_ci 1357db96d56Sopenharmony_ci +---------------+----------------------------------------------+ 1367db96d56Sopenharmony_ci | Value | Disposition | 1377db96d56Sopenharmony_ci +===============+==============================================+ 1387db96d56Sopenharmony_ci | ``"default"`` | print the first occurrence of matching | 1397db96d56Sopenharmony_ci | | warnings for each location (module + | 1407db96d56Sopenharmony_ci | | line number) where the warning is issued | 1417db96d56Sopenharmony_ci +---------------+----------------------------------------------+ 1427db96d56Sopenharmony_ci | ``"error"`` | turn matching warnings into exceptions | 1437db96d56Sopenharmony_ci +---------------+----------------------------------------------+ 1447db96d56Sopenharmony_ci | ``"ignore"`` | never print matching warnings | 1457db96d56Sopenharmony_ci +---------------+----------------------------------------------+ 1467db96d56Sopenharmony_ci | ``"always"`` | always print matching warnings | 1477db96d56Sopenharmony_ci +---------------+----------------------------------------------+ 1487db96d56Sopenharmony_ci | ``"module"`` | print the first occurrence of matching | 1497db96d56Sopenharmony_ci | | warnings for each module where the warning | 1507db96d56Sopenharmony_ci | | is issued (regardless of line number) | 1517db96d56Sopenharmony_ci +---------------+----------------------------------------------+ 1527db96d56Sopenharmony_ci | ``"once"`` | print only the first occurrence of matching | 1537db96d56Sopenharmony_ci | | warnings, regardless of location | 1547db96d56Sopenharmony_ci +---------------+----------------------------------------------+ 1557db96d56Sopenharmony_ci 1567db96d56Sopenharmony_ci* *message* is a string containing a regular expression that the start of 1577db96d56Sopenharmony_ci the warning message must match, case-insensitively. In :option:`-W` and 1587db96d56Sopenharmony_ci :envvar:`PYTHONWARNINGS`, *message* is a literal string that the start of the 1597db96d56Sopenharmony_ci warning message must contain (case-insensitively), ignoring any whitespace at 1607db96d56Sopenharmony_ci the start or end of *message*. 1617db96d56Sopenharmony_ci 1627db96d56Sopenharmony_ci* *category* is a class (a subclass of :exc:`Warning`) of which the warning 1637db96d56Sopenharmony_ci category must be a subclass in order to match. 1647db96d56Sopenharmony_ci 1657db96d56Sopenharmony_ci* *module* is a string containing a regular expression that the start of the 1667db96d56Sopenharmony_ci fully qualified module name must match, case-sensitively. In :option:`-W` and 1677db96d56Sopenharmony_ci :envvar:`PYTHONWARNINGS`, *module* is a literal string that the 1687db96d56Sopenharmony_ci fully qualified module name must be equal to (case-sensitively), ignoring any 1697db96d56Sopenharmony_ci whitespace at the start or end of *module*. 1707db96d56Sopenharmony_ci 1717db96d56Sopenharmony_ci* *lineno* is an integer that the line number where the warning occurred must 1727db96d56Sopenharmony_ci match, or ``0`` to match all line numbers. 1737db96d56Sopenharmony_ci 1747db96d56Sopenharmony_ciSince the :exc:`Warning` class is derived from the built-in :exc:`Exception` 1757db96d56Sopenharmony_ciclass, to turn a warning into an error we simply raise ``category(message)``. 1767db96d56Sopenharmony_ci 1777db96d56Sopenharmony_ciIf a warning is reported and doesn't match any registered filter then the 1787db96d56Sopenharmony_ci"default" action is applied (hence its name). 1797db96d56Sopenharmony_ci 1807db96d56Sopenharmony_ci 1817db96d56Sopenharmony_ci.. _describing-warning-filters: 1827db96d56Sopenharmony_ci 1837db96d56Sopenharmony_ciDescribing Warning Filters 1847db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~~~~~~ 1857db96d56Sopenharmony_ci 1867db96d56Sopenharmony_ciThe warnings filter is initialized by :option:`-W` options passed to the Python 1877db96d56Sopenharmony_ciinterpreter command line and the :envvar:`PYTHONWARNINGS` environment variable. 1887db96d56Sopenharmony_ciThe interpreter saves the arguments for all supplied entries without 1897db96d56Sopenharmony_ciinterpretation in :data:`sys.warnoptions`; the :mod:`warnings` module parses these 1907db96d56Sopenharmony_ciwhen it is first imported (invalid options are ignored, after printing a 1917db96d56Sopenharmony_cimessage to :data:`sys.stderr`). 1927db96d56Sopenharmony_ci 1937db96d56Sopenharmony_ciIndividual warnings filters are specified as a sequence of fields separated by 1947db96d56Sopenharmony_cicolons:: 1957db96d56Sopenharmony_ci 1967db96d56Sopenharmony_ci action:message:category:module:line 1977db96d56Sopenharmony_ci 1987db96d56Sopenharmony_ciThe meaning of each of these fields is as described in :ref:`warning-filter`. 1997db96d56Sopenharmony_ciWhen listing multiple filters on a single line (as for 2007db96d56Sopenharmony_ci:envvar:`PYTHONWARNINGS`), the individual filters are separated by commas and 2017db96d56Sopenharmony_cithe filters listed later take precedence over those listed before them (as 2027db96d56Sopenharmony_cithey're applied left-to-right, and the most recently applied filters take 2037db96d56Sopenharmony_ciprecedence over earlier ones). 2047db96d56Sopenharmony_ci 2057db96d56Sopenharmony_ciCommonly used warning filters apply to either all warnings, warnings in a 2067db96d56Sopenharmony_ciparticular category, or warnings raised by particular modules or packages. 2077db96d56Sopenharmony_ciSome examples:: 2087db96d56Sopenharmony_ci 2097db96d56Sopenharmony_ci default # Show all warnings (even those ignored by default) 2107db96d56Sopenharmony_ci ignore # Ignore all warnings 2117db96d56Sopenharmony_ci error # Convert all warnings to errors 2127db96d56Sopenharmony_ci error::ResourceWarning # Treat ResourceWarning messages as errors 2137db96d56Sopenharmony_ci default::DeprecationWarning # Show DeprecationWarning messages 2147db96d56Sopenharmony_ci ignore,default:::mymodule # Only report warnings triggered by "mymodule" 2157db96d56Sopenharmony_ci error:::mymodule # Convert warnings to errors in "mymodule" 2167db96d56Sopenharmony_ci 2177db96d56Sopenharmony_ci 2187db96d56Sopenharmony_ci.. _default-warning-filter: 2197db96d56Sopenharmony_ci 2207db96d56Sopenharmony_ciDefault Warning Filter 2217db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~~ 2227db96d56Sopenharmony_ci 2237db96d56Sopenharmony_ciBy default, Python installs several warning filters, which can be overridden by 2247db96d56Sopenharmony_cithe :option:`-W` command-line option, the :envvar:`PYTHONWARNINGS` environment 2257db96d56Sopenharmony_civariable and calls to :func:`filterwarnings`. 2267db96d56Sopenharmony_ci 2277db96d56Sopenharmony_ciIn regular release builds, the default warning filter has the following entries 2287db96d56Sopenharmony_ci(in order of precedence):: 2297db96d56Sopenharmony_ci 2307db96d56Sopenharmony_ci default::DeprecationWarning:__main__ 2317db96d56Sopenharmony_ci ignore::DeprecationWarning 2327db96d56Sopenharmony_ci ignore::PendingDeprecationWarning 2337db96d56Sopenharmony_ci ignore::ImportWarning 2347db96d56Sopenharmony_ci ignore::ResourceWarning 2357db96d56Sopenharmony_ci 2367db96d56Sopenharmony_ciIn a :ref:`debug build <debug-build>`, the list of default warning filters is empty. 2377db96d56Sopenharmony_ci 2387db96d56Sopenharmony_ci.. versionchanged:: 3.2 2397db96d56Sopenharmony_ci :exc:`DeprecationWarning` is now ignored by default in addition to 2407db96d56Sopenharmony_ci :exc:`PendingDeprecationWarning`. 2417db96d56Sopenharmony_ci 2427db96d56Sopenharmony_ci.. versionchanged:: 3.7 2437db96d56Sopenharmony_ci :exc:`DeprecationWarning` is once again shown by default when triggered 2447db96d56Sopenharmony_ci directly by code in ``__main__``. 2457db96d56Sopenharmony_ci 2467db96d56Sopenharmony_ci.. versionchanged:: 3.7 2477db96d56Sopenharmony_ci :exc:`BytesWarning` no longer appears in the default filter list and is 2487db96d56Sopenharmony_ci instead configured via :data:`sys.warnoptions` when :option:`-b` is specified 2497db96d56Sopenharmony_ci twice. 2507db96d56Sopenharmony_ci 2517db96d56Sopenharmony_ci 2527db96d56Sopenharmony_ci.. _warning-disable: 2537db96d56Sopenharmony_ci 2547db96d56Sopenharmony_ciOverriding the default filter 2557db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 2567db96d56Sopenharmony_ci 2577db96d56Sopenharmony_ciDevelopers of applications written in Python may wish to hide *all* Python level 2587db96d56Sopenharmony_ciwarnings from their users by default, and only display them when running tests 2597db96d56Sopenharmony_cior otherwise working on the application. The :data:`sys.warnoptions` attribute 2607db96d56Sopenharmony_ciused to pass filter configurations to the interpreter can be used as a marker to 2617db96d56Sopenharmony_ciindicate whether or not warnings should be disabled:: 2627db96d56Sopenharmony_ci 2637db96d56Sopenharmony_ci import sys 2647db96d56Sopenharmony_ci 2657db96d56Sopenharmony_ci if not sys.warnoptions: 2667db96d56Sopenharmony_ci import warnings 2677db96d56Sopenharmony_ci warnings.simplefilter("ignore") 2687db96d56Sopenharmony_ci 2697db96d56Sopenharmony_ciDevelopers of test runners for Python code are advised to instead ensure that 2707db96d56Sopenharmony_ci*all* warnings are displayed by default for the code under test, using code 2717db96d56Sopenharmony_cilike:: 2727db96d56Sopenharmony_ci 2737db96d56Sopenharmony_ci import sys 2747db96d56Sopenharmony_ci 2757db96d56Sopenharmony_ci if not sys.warnoptions: 2767db96d56Sopenharmony_ci import os, warnings 2777db96d56Sopenharmony_ci warnings.simplefilter("default") # Change the filter in this process 2787db96d56Sopenharmony_ci os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses 2797db96d56Sopenharmony_ci 2807db96d56Sopenharmony_ciFinally, developers of interactive shells that run user code in a namespace 2817db96d56Sopenharmony_ciother than ``__main__`` are advised to ensure that :exc:`DeprecationWarning` 2827db96d56Sopenharmony_cimessages are made visible by default, using code like the following (where 2837db96d56Sopenharmony_ci``user_ns`` is the module used to execute code entered interactively):: 2847db96d56Sopenharmony_ci 2857db96d56Sopenharmony_ci import warnings 2867db96d56Sopenharmony_ci warnings.filterwarnings("default", category=DeprecationWarning, 2877db96d56Sopenharmony_ci module=user_ns.get("__name__")) 2887db96d56Sopenharmony_ci 2897db96d56Sopenharmony_ci 2907db96d56Sopenharmony_ci.. _warning-suppress: 2917db96d56Sopenharmony_ci 2927db96d56Sopenharmony_ciTemporarily Suppressing Warnings 2937db96d56Sopenharmony_ci-------------------------------- 2947db96d56Sopenharmony_ci 2957db96d56Sopenharmony_ciIf you are using code that you know will raise a warning, such as a deprecated 2967db96d56Sopenharmony_cifunction, but do not want to see the warning (even when warnings have been 2977db96d56Sopenharmony_ciexplicitly configured via the command line), then it is possible to suppress 2987db96d56Sopenharmony_cithe warning using the :class:`catch_warnings` context manager:: 2997db96d56Sopenharmony_ci 3007db96d56Sopenharmony_ci import warnings 3017db96d56Sopenharmony_ci 3027db96d56Sopenharmony_ci def fxn(): 3037db96d56Sopenharmony_ci warnings.warn("deprecated", DeprecationWarning) 3047db96d56Sopenharmony_ci 3057db96d56Sopenharmony_ci with warnings.catch_warnings(): 3067db96d56Sopenharmony_ci warnings.simplefilter("ignore") 3077db96d56Sopenharmony_ci fxn() 3087db96d56Sopenharmony_ci 3097db96d56Sopenharmony_ciWhile within the context manager all warnings will simply be ignored. This 3107db96d56Sopenharmony_ciallows you to use known-deprecated code without having to see the warning while 3117db96d56Sopenharmony_cinot suppressing the warning for other code that might not be aware of its use 3127db96d56Sopenharmony_ciof deprecated code. Note: this can only be guaranteed in a single-threaded 3137db96d56Sopenharmony_ciapplication. If two or more threads use the :class:`catch_warnings` context 3147db96d56Sopenharmony_cimanager at the same time, the behavior is undefined. 3157db96d56Sopenharmony_ci 3167db96d56Sopenharmony_ci 3177db96d56Sopenharmony_ci 3187db96d56Sopenharmony_ci.. _warning-testing: 3197db96d56Sopenharmony_ci 3207db96d56Sopenharmony_ciTesting Warnings 3217db96d56Sopenharmony_ci---------------- 3227db96d56Sopenharmony_ci 3237db96d56Sopenharmony_ciTo test warnings raised by code, use the :class:`catch_warnings` context 3247db96d56Sopenharmony_cimanager. With it you can temporarily mutate the warnings filter to facilitate 3257db96d56Sopenharmony_ciyour testing. For instance, do the following to capture all raised warnings to 3267db96d56Sopenharmony_cicheck:: 3277db96d56Sopenharmony_ci 3287db96d56Sopenharmony_ci import warnings 3297db96d56Sopenharmony_ci 3307db96d56Sopenharmony_ci def fxn(): 3317db96d56Sopenharmony_ci warnings.warn("deprecated", DeprecationWarning) 3327db96d56Sopenharmony_ci 3337db96d56Sopenharmony_ci with warnings.catch_warnings(record=True) as w: 3347db96d56Sopenharmony_ci # Cause all warnings to always be triggered. 3357db96d56Sopenharmony_ci warnings.simplefilter("always") 3367db96d56Sopenharmony_ci # Trigger a warning. 3377db96d56Sopenharmony_ci fxn() 3387db96d56Sopenharmony_ci # Verify some things 3397db96d56Sopenharmony_ci assert len(w) == 1 3407db96d56Sopenharmony_ci assert issubclass(w[-1].category, DeprecationWarning) 3417db96d56Sopenharmony_ci assert "deprecated" in str(w[-1].message) 3427db96d56Sopenharmony_ci 3437db96d56Sopenharmony_ciOne can also cause all warnings to be exceptions by using ``error`` instead of 3447db96d56Sopenharmony_ci``always``. One thing to be aware of is that if a warning has already been 3457db96d56Sopenharmony_ciraised because of a ``once``/``default`` rule, then no matter what filters are 3467db96d56Sopenharmony_ciset the warning will not be seen again unless the warnings registry related to 3477db96d56Sopenharmony_cithe warning has been cleared. 3487db96d56Sopenharmony_ci 3497db96d56Sopenharmony_ciOnce the context manager exits, the warnings filter is restored to its state 3507db96d56Sopenharmony_ciwhen the context was entered. This prevents tests from changing the warnings 3517db96d56Sopenharmony_cifilter in unexpected ways between tests and leading to indeterminate test 3527db96d56Sopenharmony_ciresults. The :func:`showwarning` function in the module is also restored to 3537db96d56Sopenharmony_ciits original value. Note: this can only be guaranteed in a single-threaded 3547db96d56Sopenharmony_ciapplication. If two or more threads use the :class:`catch_warnings` context 3557db96d56Sopenharmony_cimanager at the same time, the behavior is undefined. 3567db96d56Sopenharmony_ci 3577db96d56Sopenharmony_ciWhen testing multiple operations that raise the same kind of warning, it 3587db96d56Sopenharmony_ciis important to test them in a manner that confirms each operation is raising 3597db96d56Sopenharmony_cia new warning (e.g. set warnings to be raised as exceptions and check the 3607db96d56Sopenharmony_cioperations raise exceptions, check that the length of the warning list 3617db96d56Sopenharmony_cicontinues to increase after each operation, or else delete the previous 3627db96d56Sopenharmony_cientries from the warnings list before each new operation). 3637db96d56Sopenharmony_ci 3647db96d56Sopenharmony_ci 3657db96d56Sopenharmony_ci.. _warning-ignored: 3667db96d56Sopenharmony_ci 3677db96d56Sopenharmony_ciUpdating Code For New Versions of Dependencies 3687db96d56Sopenharmony_ci---------------------------------------------- 3697db96d56Sopenharmony_ci 3707db96d56Sopenharmony_ciWarning categories that are primarily of interest to Python developers (rather 3717db96d56Sopenharmony_cithan end users of applications written in Python) are ignored by default. 3727db96d56Sopenharmony_ci 3737db96d56Sopenharmony_ciNotably, this "ignored by default" list includes :exc:`DeprecationWarning` 3747db96d56Sopenharmony_ci(for every module except ``__main__``), which means developers should make sure 3757db96d56Sopenharmony_cito test their code with typically ignored warnings made visible in order to 3767db96d56Sopenharmony_cireceive timely notifications of future breaking API changes (whether in the 3777db96d56Sopenharmony_cistandard library or third party packages). 3787db96d56Sopenharmony_ci 3797db96d56Sopenharmony_ciIn the ideal case, the code will have a suitable test suite, and the test runner 3807db96d56Sopenharmony_ciwill take care of implicitly enabling all warnings when running tests 3817db96d56Sopenharmony_ci(the test runner provided by the :mod:`unittest` module does this). 3827db96d56Sopenharmony_ci 3837db96d56Sopenharmony_ciIn less ideal cases, applications can be checked for use of deprecated 3847db96d56Sopenharmony_ciinterfaces by passing :option:`-Wd <-W>` to the Python interpreter (this is 3857db96d56Sopenharmony_cishorthand for :option:`!-W default`) or setting ``PYTHONWARNINGS=default`` in 3867db96d56Sopenharmony_cithe environment. This enables default handling for all warnings, including those 3877db96d56Sopenharmony_cithat are ignored by default. To change what action is taken for encountered 3887db96d56Sopenharmony_ciwarnings you can change what argument is passed to :option:`-W` (e.g. 3897db96d56Sopenharmony_ci:option:`!-W error`). See the :option:`-W` flag for more details on what is 3907db96d56Sopenharmony_cipossible. 3917db96d56Sopenharmony_ci 3927db96d56Sopenharmony_ci 3937db96d56Sopenharmony_ci.. _warning-functions: 3947db96d56Sopenharmony_ci 3957db96d56Sopenharmony_ciAvailable Functions 3967db96d56Sopenharmony_ci------------------- 3977db96d56Sopenharmony_ci 3987db96d56Sopenharmony_ci 3997db96d56Sopenharmony_ci.. function:: warn(message, category=None, stacklevel=1, source=None) 4007db96d56Sopenharmony_ci 4017db96d56Sopenharmony_ci Issue a warning, or maybe ignore it or raise an exception. The *category* 4027db96d56Sopenharmony_ci argument, if given, must be a :ref:`warning category class <warning-categories>`; it 4037db96d56Sopenharmony_ci defaults to :exc:`UserWarning`. Alternatively, *message* can be a :exc:`Warning` instance, 4047db96d56Sopenharmony_ci in which case *category* will be ignored and ``message.__class__`` will be used. 4057db96d56Sopenharmony_ci In this case, the message text will be ``str(message)``. This function raises an 4067db96d56Sopenharmony_ci exception if the particular warning issued is changed into an error by the 4077db96d56Sopenharmony_ci :ref:`warnings filter <warning-filter>`. The *stacklevel* argument can be used by wrapper 4087db96d56Sopenharmony_ci functions written in Python, like this:: 4097db96d56Sopenharmony_ci 4107db96d56Sopenharmony_ci def deprecation(message): 4117db96d56Sopenharmony_ci warnings.warn(message, DeprecationWarning, stacklevel=2) 4127db96d56Sopenharmony_ci 4137db96d56Sopenharmony_ci This makes the warning refer to :func:`deprecation`'s caller, rather than to the 4147db96d56Sopenharmony_ci source of :func:`deprecation` itself (since the latter would defeat the purpose 4157db96d56Sopenharmony_ci of the warning message). 4167db96d56Sopenharmony_ci 4177db96d56Sopenharmony_ci *source*, if supplied, is the destroyed object which emitted a 4187db96d56Sopenharmony_ci :exc:`ResourceWarning`. 4197db96d56Sopenharmony_ci 4207db96d56Sopenharmony_ci .. versionchanged:: 3.6 4217db96d56Sopenharmony_ci Added *source* parameter. 4227db96d56Sopenharmony_ci 4237db96d56Sopenharmony_ci 4247db96d56Sopenharmony_ci.. function:: warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None, source=None) 4257db96d56Sopenharmony_ci 4267db96d56Sopenharmony_ci This is a low-level interface to the functionality of :func:`warn`, passing in 4277db96d56Sopenharmony_ci explicitly the message, category, filename and line number, and optionally the 4287db96d56Sopenharmony_ci module name and the registry (which should be the ``__warningregistry__`` 4297db96d56Sopenharmony_ci dictionary of the module). The module name defaults to the filename with 4307db96d56Sopenharmony_ci ``.py`` stripped; if no registry is passed, the warning is never suppressed. 4317db96d56Sopenharmony_ci *message* must be a string and *category* a subclass of :exc:`Warning` or 4327db96d56Sopenharmony_ci *message* may be a :exc:`Warning` instance, in which case *category* will be 4337db96d56Sopenharmony_ci ignored. 4347db96d56Sopenharmony_ci 4357db96d56Sopenharmony_ci *module_globals*, if supplied, should be the global namespace in use by the code 4367db96d56Sopenharmony_ci for which the warning is issued. (This argument is used to support displaying 4377db96d56Sopenharmony_ci source for modules found in zipfiles or other non-filesystem import 4387db96d56Sopenharmony_ci sources). 4397db96d56Sopenharmony_ci 4407db96d56Sopenharmony_ci *source*, if supplied, is the destroyed object which emitted a 4417db96d56Sopenharmony_ci :exc:`ResourceWarning`. 4427db96d56Sopenharmony_ci 4437db96d56Sopenharmony_ci .. versionchanged:: 3.6 4447db96d56Sopenharmony_ci Add the *source* parameter. 4457db96d56Sopenharmony_ci 4467db96d56Sopenharmony_ci 4477db96d56Sopenharmony_ci.. function:: showwarning(message, category, filename, lineno, file=None, line=None) 4487db96d56Sopenharmony_ci 4497db96d56Sopenharmony_ci Write a warning to a file. The default implementation calls 4507db96d56Sopenharmony_ci ``formatwarning(message, category, filename, lineno, line)`` and writes the 4517db96d56Sopenharmony_ci resulting string to *file*, which defaults to :data:`sys.stderr`. You may replace 4527db96d56Sopenharmony_ci this function with any callable by assigning to ``warnings.showwarning``. 4537db96d56Sopenharmony_ci *line* is a line of source code to be included in the warning 4547db96d56Sopenharmony_ci message; if *line* is not supplied, :func:`showwarning` will 4557db96d56Sopenharmony_ci try to read the line specified by *filename* and *lineno*. 4567db96d56Sopenharmony_ci 4577db96d56Sopenharmony_ci 4587db96d56Sopenharmony_ci.. function:: formatwarning(message, category, filename, lineno, line=None) 4597db96d56Sopenharmony_ci 4607db96d56Sopenharmony_ci Format a warning the standard way. This returns a string which may contain 4617db96d56Sopenharmony_ci embedded newlines and ends in a newline. *line* is a line of source code to 4627db96d56Sopenharmony_ci be included in the warning message; if *line* is not supplied, 4637db96d56Sopenharmony_ci :func:`formatwarning` will try to read the line specified by *filename* and 4647db96d56Sopenharmony_ci *lineno*. 4657db96d56Sopenharmony_ci 4667db96d56Sopenharmony_ci 4677db96d56Sopenharmony_ci.. function:: filterwarnings(action, message='', category=Warning, module='', lineno=0, append=False) 4687db96d56Sopenharmony_ci 4697db96d56Sopenharmony_ci Insert an entry into the list of :ref:`warnings filter specifications 4707db96d56Sopenharmony_ci <warning-filter>`. The entry is inserted at the front by default; if 4717db96d56Sopenharmony_ci *append* is true, it is inserted at the end. This checks the types of the 4727db96d56Sopenharmony_ci arguments, compiles the *message* and *module* regular expressions, and 4737db96d56Sopenharmony_ci inserts them as a tuple in the list of warnings filters. Entries closer to 4747db96d56Sopenharmony_ci the front of the list override entries later in the list, if both match a 4757db96d56Sopenharmony_ci particular warning. Omitted arguments default to a value that matches 4767db96d56Sopenharmony_ci everything. 4777db96d56Sopenharmony_ci 4787db96d56Sopenharmony_ci 4797db96d56Sopenharmony_ci.. function:: simplefilter(action, category=Warning, lineno=0, append=False) 4807db96d56Sopenharmony_ci 4817db96d56Sopenharmony_ci Insert a simple entry into the list of :ref:`warnings filter specifications 4827db96d56Sopenharmony_ci <warning-filter>`. The meaning of the function parameters is as for 4837db96d56Sopenharmony_ci :func:`filterwarnings`, but regular expressions are not needed as the filter 4847db96d56Sopenharmony_ci inserted always matches any message in any module as long as the category and 4857db96d56Sopenharmony_ci line number match. 4867db96d56Sopenharmony_ci 4877db96d56Sopenharmony_ci 4887db96d56Sopenharmony_ci.. function:: resetwarnings() 4897db96d56Sopenharmony_ci 4907db96d56Sopenharmony_ci Reset the warnings filter. This discards the effect of all previous calls to 4917db96d56Sopenharmony_ci :func:`filterwarnings`, including that of the :option:`-W` command line options 4927db96d56Sopenharmony_ci and calls to :func:`simplefilter`. 4937db96d56Sopenharmony_ci 4947db96d56Sopenharmony_ci 4957db96d56Sopenharmony_ciAvailable Context Managers 4967db96d56Sopenharmony_ci-------------------------- 4977db96d56Sopenharmony_ci 4987db96d56Sopenharmony_ci.. class:: catch_warnings(*, record=False, module=None, action=None, category=Warning, lineno=0, append=False) 4997db96d56Sopenharmony_ci 5007db96d56Sopenharmony_ci A context manager that copies and, upon exit, restores the warnings filter 5017db96d56Sopenharmony_ci and the :func:`showwarning` function. 5027db96d56Sopenharmony_ci If the *record* argument is :const:`False` (the default) the context manager 5037db96d56Sopenharmony_ci returns :class:`None` on entry. If *record* is :const:`True`, a list is 5047db96d56Sopenharmony_ci returned that is progressively populated with objects as seen by a custom 5057db96d56Sopenharmony_ci :func:`showwarning` function (which also suppresses output to ``sys.stdout``). 5067db96d56Sopenharmony_ci Each object in the list has attributes with the same names as the arguments to 5077db96d56Sopenharmony_ci :func:`showwarning`. 5087db96d56Sopenharmony_ci 5097db96d56Sopenharmony_ci The *module* argument takes a module that will be used instead of the 5107db96d56Sopenharmony_ci module returned when you import :mod:`warnings` whose filter will be 5117db96d56Sopenharmony_ci protected. This argument exists primarily for testing the :mod:`warnings` 5127db96d56Sopenharmony_ci module itself. 5137db96d56Sopenharmony_ci 5147db96d56Sopenharmony_ci If the *action* argument is not ``None``, the remaining arguments are 5157db96d56Sopenharmony_ci passed to :func:`simplefilter` as if it were called immediately on 5167db96d56Sopenharmony_ci entering the context. 5177db96d56Sopenharmony_ci 5187db96d56Sopenharmony_ci .. note:: 5197db96d56Sopenharmony_ci 5207db96d56Sopenharmony_ci The :class:`catch_warnings` manager works by replacing and 5217db96d56Sopenharmony_ci then later restoring the module's 5227db96d56Sopenharmony_ci :func:`showwarning` function and internal list of filter 5237db96d56Sopenharmony_ci specifications. This means the context manager is modifying 5247db96d56Sopenharmony_ci global state and therefore is not thread-safe. 5257db96d56Sopenharmony_ci 5267db96d56Sopenharmony_ci .. versionchanged:: 3.11 5277db96d56Sopenharmony_ci 5287db96d56Sopenharmony_ci Added the *action*, *category*, *lineno*, and *append* parameters. 529