1:mod:`warnings` --- Warning control 2=================================== 3 4.. module:: warnings 5 :synopsis: Issue warning messages and control their disposition. 6 7**Source code:** :source:`Lib/warnings.py` 8 9.. index:: single: warnings 10 11-------------- 12 13Warning messages are typically issued in situations where it is useful to alert 14the user of some condition in a program, where that condition (normally) doesn't 15warrant raising an exception and terminating the program. For example, one 16might want to issue a warning when a program uses an obsolete module. 17 18Python programmers issue warnings by calling the :func:`warn` function defined 19in this module. (C programmers use :c:func:`PyErr_WarnEx`; see 20:ref:`exceptionhandling` for details). 21 22Warning messages are normally written to :data:`sys.stderr`, but their disposition 23can be changed flexibly, from ignoring all warnings to turning them into 24exceptions. The disposition of warnings can vary based on the :ref:`warning category 25<warning-categories>`, the text of the warning message, and the source location where it 26is issued. Repetitions of a particular warning for the same source location are 27typically suppressed. 28 29There are two stages in warning control: first, each time a warning is issued, a 30determination is made whether a message should be issued or not; next, if a 31message is to be issued, it is formatted and printed using a user-settable hook. 32 33The determination whether to issue a warning message is controlled by the 34:ref:`warning filter <warning-filter>`, which is a sequence of matching rules and actions. Rules can be 35added to the filter by calling :func:`filterwarnings` and reset to its default 36state by calling :func:`resetwarnings`. 37 38The printing of warning messages is done by calling :func:`showwarning`, which 39may be overridden; the default implementation of this function formats the 40message by calling :func:`formatwarning`, which is also available for use by 41custom implementations. 42 43.. seealso:: 44 :func:`logging.captureWarnings` allows you to handle all warnings with 45 the standard logging infrastructure. 46 47 48.. _warning-categories: 49 50Warning Categories 51------------------ 52 53There are a number of built-in exceptions that represent warning categories. 54This categorization is useful to be able to filter out groups of warnings. 55 56While these are technically 57:ref:`built-in exceptions <warning-categories-as-exceptions>`, they are 58documented here, because conceptually they belong to the warnings mechanism. 59 60User code can define additional warning categories by subclassing one of the 61standard warning categories. A warning category must always be a subclass of 62the :exc:`Warning` class. 63 64The following warnings category classes are currently defined: 65 66.. tabularcolumns:: |l|p{0.6\linewidth}| 67 68+----------------------------------+-----------------------------------------------+ 69| Class | Description | 70+==================================+===============================================+ 71| :exc:`Warning` | This is the base class of all warning | 72| | category classes. It is a subclass of | 73| | :exc:`Exception`. | 74+----------------------------------+-----------------------------------------------+ 75| :exc:`UserWarning` | The default category for :func:`warn`. | 76+----------------------------------+-----------------------------------------------+ 77| :exc:`DeprecationWarning` | Base category for warnings about deprecated | 78| | features when those warnings are intended for | 79| | other Python developers (ignored by default, | 80| | unless triggered by code in ``__main__``). | 81+----------------------------------+-----------------------------------------------+ 82| :exc:`SyntaxWarning` | Base category for warnings about dubious | 83| | syntactic features. | 84+----------------------------------+-----------------------------------------------+ 85| :exc:`RuntimeWarning` | Base category for warnings about dubious | 86| | runtime features. | 87+----------------------------------+-----------------------------------------------+ 88| :exc:`FutureWarning` | Base category for warnings about deprecated | 89| | features when those warnings are intended for | 90| | end users of applications that are written in | 91| | Python. | 92+----------------------------------+-----------------------------------------------+ 93| :exc:`PendingDeprecationWarning` | Base category for warnings about features | 94| | that will be deprecated in the future | 95| | (ignored by default). | 96+----------------------------------+-----------------------------------------------+ 97| :exc:`ImportWarning` | Base category for warnings triggered during | 98| | the process of importing a module (ignored by | 99| | default). | 100+----------------------------------+-----------------------------------------------+ 101| :exc:`UnicodeWarning` | Base category for warnings related to | 102| | Unicode. | 103+----------------------------------+-----------------------------------------------+ 104| :exc:`BytesWarning` | Base category for warnings related to | 105| | :class:`bytes` and :class:`bytearray`. | 106+----------------------------------+-----------------------------------------------+ 107| :exc:`ResourceWarning` | Base category for warnings related to | 108| | resource usage (ignored by default). | 109+----------------------------------+-----------------------------------------------+ 110 111.. versionchanged:: 3.7 112 Previously :exc:`DeprecationWarning` and :exc:`FutureWarning` were 113 distinguished based on whether a feature was being removed entirely or 114 changing its behaviour. They are now distinguished based on their 115 intended audience and the way they're handled by the default warnings 116 filters. 117 118 119.. _warning-filter: 120 121The Warnings Filter 122------------------- 123 124The warnings filter controls whether warnings are ignored, displayed, or turned 125into errors (raising an exception). 126 127Conceptually, the warnings filter maintains an ordered list of filter 128specifications; any specific warning is matched against each filter 129specification in the list in turn until a match is found; the filter determines 130the disposition of the match. Each entry is a tuple of the form (*action*, 131*message*, *category*, *module*, *lineno*), where: 132 133* *action* is one of the following strings: 134 135 +---------------+----------------------------------------------+ 136 | Value | Disposition | 137 +===============+==============================================+ 138 | ``"default"`` | print the first occurrence of matching | 139 | | warnings for each location (module + | 140 | | line number) where the warning is issued | 141 +---------------+----------------------------------------------+ 142 | ``"error"`` | turn matching warnings into exceptions | 143 +---------------+----------------------------------------------+ 144 | ``"ignore"`` | never print matching warnings | 145 +---------------+----------------------------------------------+ 146 | ``"always"`` | always print matching warnings | 147 +---------------+----------------------------------------------+ 148 | ``"module"`` | print the first occurrence of matching | 149 | | warnings for each module where the warning | 150 | | is issued (regardless of line number) | 151 +---------------+----------------------------------------------+ 152 | ``"once"`` | print only the first occurrence of matching | 153 | | warnings, regardless of location | 154 +---------------+----------------------------------------------+ 155 156* *message* is a string containing a regular expression that the start of 157 the warning message must match, case-insensitively. In :option:`-W` and 158 :envvar:`PYTHONWARNINGS`, *message* is a literal string that the start of the 159 warning message must contain (case-insensitively), ignoring any whitespace at 160 the start or end of *message*. 161 162* *category* is a class (a subclass of :exc:`Warning`) of which the warning 163 category must be a subclass in order to match. 164 165* *module* is a string containing a regular expression that the start of the 166 fully qualified module name must match, case-sensitively. In :option:`-W` and 167 :envvar:`PYTHONWARNINGS`, *module* is a literal string that the 168 fully qualified module name must be equal to (case-sensitively), ignoring any 169 whitespace at the start or end of *module*. 170 171* *lineno* is an integer that the line number where the warning occurred must 172 match, or ``0`` to match all line numbers. 173 174Since the :exc:`Warning` class is derived from the built-in :exc:`Exception` 175class, to turn a warning into an error we simply raise ``category(message)``. 176 177If a warning is reported and doesn't match any registered filter then the 178"default" action is applied (hence its name). 179 180 181.. _describing-warning-filters: 182 183Describing Warning Filters 184~~~~~~~~~~~~~~~~~~~~~~~~~~ 185 186The warnings filter is initialized by :option:`-W` options passed to the Python 187interpreter command line and the :envvar:`PYTHONWARNINGS` environment variable. 188The interpreter saves the arguments for all supplied entries without 189interpretation in :data:`sys.warnoptions`; the :mod:`warnings` module parses these 190when it is first imported (invalid options are ignored, after printing a 191message to :data:`sys.stderr`). 192 193Individual warnings filters are specified as a sequence of fields separated by 194colons:: 195 196 action:message:category:module:line 197 198The meaning of each of these fields is as described in :ref:`warning-filter`. 199When listing multiple filters on a single line (as for 200:envvar:`PYTHONWARNINGS`), the individual filters are separated by commas and 201the filters listed later take precedence over those listed before them (as 202they're applied left-to-right, and the most recently applied filters take 203precedence over earlier ones). 204 205Commonly used warning filters apply to either all warnings, warnings in a 206particular category, or warnings raised by particular modules or packages. 207Some examples:: 208 209 default # Show all warnings (even those ignored by default) 210 ignore # Ignore all warnings 211 error # Convert all warnings to errors 212 error::ResourceWarning # Treat ResourceWarning messages as errors 213 default::DeprecationWarning # Show DeprecationWarning messages 214 ignore,default:::mymodule # Only report warnings triggered by "mymodule" 215 error:::mymodule # Convert warnings to errors in "mymodule" 216 217 218.. _default-warning-filter: 219 220Default Warning Filter 221~~~~~~~~~~~~~~~~~~~~~~ 222 223By default, Python installs several warning filters, which can be overridden by 224the :option:`-W` command-line option, the :envvar:`PYTHONWARNINGS` environment 225variable and calls to :func:`filterwarnings`. 226 227In regular release builds, the default warning filter has the following entries 228(in order of precedence):: 229 230 default::DeprecationWarning:__main__ 231 ignore::DeprecationWarning 232 ignore::PendingDeprecationWarning 233 ignore::ImportWarning 234 ignore::ResourceWarning 235 236In a :ref:`debug build <debug-build>`, the list of default warning filters is empty. 237 238.. versionchanged:: 3.2 239 :exc:`DeprecationWarning` is now ignored by default in addition to 240 :exc:`PendingDeprecationWarning`. 241 242.. versionchanged:: 3.7 243 :exc:`DeprecationWarning` is once again shown by default when triggered 244 directly by code in ``__main__``. 245 246.. versionchanged:: 3.7 247 :exc:`BytesWarning` no longer appears in the default filter list and is 248 instead configured via :data:`sys.warnoptions` when :option:`-b` is specified 249 twice. 250 251 252.. _warning-disable: 253 254Overriding the default filter 255~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 256 257Developers of applications written in Python may wish to hide *all* Python level 258warnings from their users by default, and only display them when running tests 259or otherwise working on the application. The :data:`sys.warnoptions` attribute 260used to pass filter configurations to the interpreter can be used as a marker to 261indicate whether or not warnings should be disabled:: 262 263 import sys 264 265 if not sys.warnoptions: 266 import warnings 267 warnings.simplefilter("ignore") 268 269Developers of test runners for Python code are advised to instead ensure that 270*all* warnings are displayed by default for the code under test, using code 271like:: 272 273 import sys 274 275 if not sys.warnoptions: 276 import os, warnings 277 warnings.simplefilter("default") # Change the filter in this process 278 os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses 279 280Finally, developers of interactive shells that run user code in a namespace 281other than ``__main__`` are advised to ensure that :exc:`DeprecationWarning` 282messages are made visible by default, using code like the following (where 283``user_ns`` is the module used to execute code entered interactively):: 284 285 import warnings 286 warnings.filterwarnings("default", category=DeprecationWarning, 287 module=user_ns.get("__name__")) 288 289 290.. _warning-suppress: 291 292Temporarily Suppressing Warnings 293-------------------------------- 294 295If you are using code that you know will raise a warning, such as a deprecated 296function, but do not want to see the warning (even when warnings have been 297explicitly configured via the command line), then it is possible to suppress 298the warning using the :class:`catch_warnings` context manager:: 299 300 import warnings 301 302 def fxn(): 303 warnings.warn("deprecated", DeprecationWarning) 304 305 with warnings.catch_warnings(): 306 warnings.simplefilter("ignore") 307 fxn() 308 309While within the context manager all warnings will simply be ignored. This 310allows you to use known-deprecated code without having to see the warning while 311not suppressing the warning for other code that might not be aware of its use 312of deprecated code. Note: this can only be guaranteed in a single-threaded 313application. If two or more threads use the :class:`catch_warnings` context 314manager at the same time, the behavior is undefined. 315 316 317 318.. _warning-testing: 319 320Testing Warnings 321---------------- 322 323To test warnings raised by code, use the :class:`catch_warnings` context 324manager. With it you can temporarily mutate the warnings filter to facilitate 325your testing. For instance, do the following to capture all raised warnings to 326check:: 327 328 import warnings 329 330 def fxn(): 331 warnings.warn("deprecated", DeprecationWarning) 332 333 with warnings.catch_warnings(record=True) as w: 334 # Cause all warnings to always be triggered. 335 warnings.simplefilter("always") 336 # Trigger a warning. 337 fxn() 338 # Verify some things 339 assert len(w) == 1 340 assert issubclass(w[-1].category, DeprecationWarning) 341 assert "deprecated" in str(w[-1].message) 342 343One can also cause all warnings to be exceptions by using ``error`` instead of 344``always``. One thing to be aware of is that if a warning has already been 345raised because of a ``once``/``default`` rule, then no matter what filters are 346set the warning will not be seen again unless the warnings registry related to 347the warning has been cleared. 348 349Once the context manager exits, the warnings filter is restored to its state 350when the context was entered. This prevents tests from changing the warnings 351filter in unexpected ways between tests and leading to indeterminate test 352results. The :func:`showwarning` function in the module is also restored to 353its original value. Note: this can only be guaranteed in a single-threaded 354application. If two or more threads use the :class:`catch_warnings` context 355manager at the same time, the behavior is undefined. 356 357When testing multiple operations that raise the same kind of warning, it 358is important to test them in a manner that confirms each operation is raising 359a new warning (e.g. set warnings to be raised as exceptions and check the 360operations raise exceptions, check that the length of the warning list 361continues to increase after each operation, or else delete the previous 362entries from the warnings list before each new operation). 363 364 365.. _warning-ignored: 366 367Updating Code For New Versions of Dependencies 368---------------------------------------------- 369 370Warning categories that are primarily of interest to Python developers (rather 371than end users of applications written in Python) are ignored by default. 372 373Notably, this "ignored by default" list includes :exc:`DeprecationWarning` 374(for every module except ``__main__``), which means developers should make sure 375to test their code with typically ignored warnings made visible in order to 376receive timely notifications of future breaking API changes (whether in the 377standard library or third party packages). 378 379In the ideal case, the code will have a suitable test suite, and the test runner 380will take care of implicitly enabling all warnings when running tests 381(the test runner provided by the :mod:`unittest` module does this). 382 383In less ideal cases, applications can be checked for use of deprecated 384interfaces by passing :option:`-Wd <-W>` to the Python interpreter (this is 385shorthand for :option:`!-W default`) or setting ``PYTHONWARNINGS=default`` in 386the environment. This enables default handling for all warnings, including those 387that are ignored by default. To change what action is taken for encountered 388warnings you can change what argument is passed to :option:`-W` (e.g. 389:option:`!-W error`). See the :option:`-W` flag for more details on what is 390possible. 391 392 393.. _warning-functions: 394 395Available Functions 396------------------- 397 398 399.. function:: warn(message, category=None, stacklevel=1, source=None) 400 401 Issue a warning, or maybe ignore it or raise an exception. The *category* 402 argument, if given, must be a :ref:`warning category class <warning-categories>`; it 403 defaults to :exc:`UserWarning`. Alternatively, *message* can be a :exc:`Warning` instance, 404 in which case *category* will be ignored and ``message.__class__`` will be used. 405 In this case, the message text will be ``str(message)``. This function raises an 406 exception if the particular warning issued is changed into an error by the 407 :ref:`warnings filter <warning-filter>`. The *stacklevel* argument can be used by wrapper 408 functions written in Python, like this:: 409 410 def deprecation(message): 411 warnings.warn(message, DeprecationWarning, stacklevel=2) 412 413 This makes the warning refer to :func:`deprecation`'s caller, rather than to the 414 source of :func:`deprecation` itself (since the latter would defeat the purpose 415 of the warning message). 416 417 *source*, if supplied, is the destroyed object which emitted a 418 :exc:`ResourceWarning`. 419 420 .. versionchanged:: 3.6 421 Added *source* parameter. 422 423 424.. function:: warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None, source=None) 425 426 This is a low-level interface to the functionality of :func:`warn`, passing in 427 explicitly the message, category, filename and line number, and optionally the 428 module name and the registry (which should be the ``__warningregistry__`` 429 dictionary of the module). The module name defaults to the filename with 430 ``.py`` stripped; if no registry is passed, the warning is never suppressed. 431 *message* must be a string and *category* a subclass of :exc:`Warning` or 432 *message* may be a :exc:`Warning` instance, in which case *category* will be 433 ignored. 434 435 *module_globals*, if supplied, should be the global namespace in use by the code 436 for which the warning is issued. (This argument is used to support displaying 437 source for modules found in zipfiles or other non-filesystem import 438 sources). 439 440 *source*, if supplied, is the destroyed object which emitted a 441 :exc:`ResourceWarning`. 442 443 .. versionchanged:: 3.6 444 Add the *source* parameter. 445 446 447.. function:: showwarning(message, category, filename, lineno, file=None, line=None) 448 449 Write a warning to a file. The default implementation calls 450 ``formatwarning(message, category, filename, lineno, line)`` and writes the 451 resulting string to *file*, which defaults to :data:`sys.stderr`. You may replace 452 this function with any callable by assigning to ``warnings.showwarning``. 453 *line* is a line of source code to be included in the warning 454 message; if *line* is not supplied, :func:`showwarning` will 455 try to read the line specified by *filename* and *lineno*. 456 457 458.. function:: formatwarning(message, category, filename, lineno, line=None) 459 460 Format a warning the standard way. This returns a string which may contain 461 embedded newlines and ends in a newline. *line* is a line of source code to 462 be included in the warning message; if *line* is not supplied, 463 :func:`formatwarning` will try to read the line specified by *filename* and 464 *lineno*. 465 466 467.. function:: filterwarnings(action, message='', category=Warning, module='', lineno=0, append=False) 468 469 Insert an entry into the list of :ref:`warnings filter specifications 470 <warning-filter>`. The entry is inserted at the front by default; if 471 *append* is true, it is inserted at the end. This checks the types of the 472 arguments, compiles the *message* and *module* regular expressions, and 473 inserts them as a tuple in the list of warnings filters. Entries closer to 474 the front of the list override entries later in the list, if both match a 475 particular warning. Omitted arguments default to a value that matches 476 everything. 477 478 479.. function:: simplefilter(action, category=Warning, lineno=0, append=False) 480 481 Insert a simple entry into the list of :ref:`warnings filter specifications 482 <warning-filter>`. The meaning of the function parameters is as for 483 :func:`filterwarnings`, but regular expressions are not needed as the filter 484 inserted always matches any message in any module as long as the category and 485 line number match. 486 487 488.. function:: resetwarnings() 489 490 Reset the warnings filter. This discards the effect of all previous calls to 491 :func:`filterwarnings`, including that of the :option:`-W` command line options 492 and calls to :func:`simplefilter`. 493 494 495Available Context Managers 496-------------------------- 497 498.. class:: catch_warnings(*, record=False, module=None, action=None, category=Warning, lineno=0, append=False) 499 500 A context manager that copies and, upon exit, restores the warnings filter 501 and the :func:`showwarning` function. 502 If the *record* argument is :const:`False` (the default) the context manager 503 returns :class:`None` on entry. If *record* is :const:`True`, a list is 504 returned that is progressively populated with objects as seen by a custom 505 :func:`showwarning` function (which also suppresses output to ``sys.stdout``). 506 Each object in the list has attributes with the same names as the arguments to 507 :func:`showwarning`. 508 509 The *module* argument takes a module that will be used instead of the 510 module returned when you import :mod:`warnings` whose filter will be 511 protected. This argument exists primarily for testing the :mod:`warnings` 512 module itself. 513 514 If the *action* argument is not ``None``, the remaining arguments are 515 passed to :func:`simplefilter` as if it were called immediately on 516 entering the context. 517 518 .. note:: 519 520 The :class:`catch_warnings` manager works by replacing and 521 then later restoring the module's 522 :func:`showwarning` function and internal list of filter 523 specifications. This means the context manager is modifying 524 global state and therefore is not thread-safe. 525 526 .. versionchanged:: 3.11 527 528 Added the *action*, *category*, *lineno*, and *append* parameters. 529