| 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 |
|
| 13 |
Warning messages are typically issued in situations where it is useful to alert |
| 14 |
the user of some condition in a program, where that condition (normally) doesn't |
| 15 |
warrant raising an exception and terminating the program. For example, one |
| 16 |
might want to issue a warning when a program uses an obsolete module. |
| 17 |
|
| 18 |
Python programmers issue warnings by calling the :func:`warn` function defined |
| 19 |
in this module. (C programmers use :c:func:`PyErr_WarnEx`; see |
| 20 |
:ref:`exceptionhandling` for details). |
| 21 |
|
| 22 |
Warning messages are normally written to :data:`sys.stderr`, but their disposition |
| 23 |
can be changed flexibly, from ignoring all warnings to turning them into |
| 24 |
exceptions. 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 |
| 26 |
is issued. Repetitions of a particular warning for the same source location are |
| 27 |
typically suppressed. |
| 28 |
|
| 29 |
There are two stages in warning control: first, each time a warning is issued, a |
| 30 |
determination is made whether a message should be issued or not; next, if a |
| 31 |
message is to be issued, it is formatted and printed using a user-settable hook. |
| 32 |
|
| 33 |
The 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 |
| 35 |
added to the filter by calling :func:`filterwarnings` and reset to its default |
| 36 |
state by calling :func:`resetwarnings`. |
| 37 |
|
| 38 |
The printing of warning messages is done by calling :func:`showwarning`, which |
| 39 |
may be overridden; the default implementation of this function formats the |
| 40 |
message by calling :func:`formatwarning`, which is also available for use by |
| 41 |
custom 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 |
|
| 50 |
Warning Categories |
| 51 |
------------------ |
| 52 |
|
| 53 |
There are a number of built-in exceptions that represent warning categories. |
| 54 |
This categorization is useful to be able to filter out groups of warnings. |
| 55 |
|
| 56 |
While these are technically |
| 57 |
:ref:`built-in exceptions <warning-categories-as-exceptions>`, they are |
| 58 |
documented here, because conceptually they belong to the warnings mechanism. |
| 59 |
|
| 60 |
User code can define additional warning categories by subclassing one of the |
| 61 |
standard warning categories. A warning category must always be a subclass of |
| 62 |
the :exc:`Warning` class. |
| 63 |
|
| 64 |
The 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 (typically emitted when | |
| 84 |
| | compiling Python source code, and hence | |
| 85 |
| | may not be suppressed by runtime filters) | |
| 86 |
+----------------------------------+-----------------------------------------------+ |
| 87 |
| :exc:`RuntimeWarning` | Base category for warnings about dubious | |
| 88 |
| | runtime features. | |
| 89 |
+----------------------------------+-----------------------------------------------+ |
| 90 |
| :exc:`FutureWarning` | Base category for warnings about deprecated | |
| 91 |
| | features when those warnings are intended for | |
| 92 |
| | end users of applications that are written in | |
| 93 |
| | Python. | |
| 94 |
+----------------------------------+-----------------------------------------------+ |
| 95 |
| :exc:`PendingDeprecationWarning` | Base category for warnings about features | |
| 96 |
| | that will be deprecated in the future | |
| 97 |
| | (ignored by default). | |
| 98 |
+----------------------------------+-----------------------------------------------+ |
| 99 |
| :exc:`ImportWarning` | Base category for warnings triggered during | |
| 100 |
| | the process of importing a module (ignored by | |
| 101 |
| | default). | |
| 102 |
+----------------------------------+-----------------------------------------------+ |
| 103 |
| :exc:`UnicodeWarning` | Base category for warnings related to | |
| 104 |
| | Unicode. | |
| 105 |
+----------------------------------+-----------------------------------------------+ |
| 106 |
| :exc:`BytesWarning` | Base category for warnings related to | |
| 107 |
| | :class:`bytes` and :class:`bytearray`. | |
| 108 |
+----------------------------------+-----------------------------------------------+ |
| 109 |
| :exc:`ResourceWarning` | Base category for warnings related to | |
| 110 |
| | resource usage (ignored by default). | |
| 111 |
+----------------------------------+-----------------------------------------------+ |
| 112 |
|
| 113 |
.. versionchanged:: 3.7 |
| 114 |
Previously :exc:`DeprecationWarning` and :exc:`FutureWarning` were |
| 115 |
distinguished based on whether a feature was being removed entirely or |
| 116 |
changing its behaviour. They are now distinguished based on their |
| 117 |
intended audience and the way they're handled by the default warnings |
| 118 |
filters. |
| 119 |
|
| 120 |
|
| 121 |
.. _warning-filter: |
| 122 |
|
| 123 |
The Warnings Filter |
| 124 |
------------------- |
| 125 |
|
| 126 |
The warnings filter controls whether warnings are ignored, displayed, or turned |
| 127 |
into errors (raising an exception). |
| 128 |
|
| 129 |
Conceptually, the warnings filter maintains an ordered list of filter |
| 130 |
specifications; any specific warning is matched against each filter |
| 131 |
specification in the list in turn until a match is found; the filter determines |
| 132 |
the disposition of the match. Each entry is a tuple of the form (*action*, |
| 133 |
*message*, *category*, *module*, *lineno*), where: |
| 134 |
|
| 135 |
* *action* is one of the following strings: |
| 136 |
|
| 137 |
+---------------+----------------------------------------------+ |
| 138 |
| Value | Disposition | |
| 139 |
+===============+==============================================+ |
| 140 |
| ``"default"`` | print the first occurrence of matching | |
| 141 |
| | warnings for each location (module + | |
| 142 |
| | line number) where the warning is issued | |
| 143 |
+---------------+----------------------------------------------+ |
| 144 |
| ``"error"`` | turn matching warnings into exceptions | |
| 145 |
+---------------+----------------------------------------------+ |
| 146 |
| ``"ignore"`` | never print matching warnings | |
| 147 |
+---------------+----------------------------------------------+ |
| 148 |
| ``"always"`` | always print matching warnings | |
| 149 |
+---------------+----------------------------------------------+ |
| 150 |
| ``"all"`` | alias to "always" | |
| 151 |
+---------------+----------------------------------------------+ |
| 152 |
| ``"module"`` | print the first occurrence of matching | |
| 153 |
| | warnings for each module where the warning | |
| 154 |
| | is issued (regardless of line number) | |
| 155 |
+---------------+----------------------------------------------+ |
| 156 |
| ``"once"`` | print only the first occurrence of matching | |
| 157 |
| | warnings, regardless of location | |
| 158 |
+---------------+----------------------------------------------+ |
| 159 |
|
| 160 |
* *message* is a string containing a regular expression that the start of |
| 161 |
the warning message must match, case-insensitively. In :option:`-W` and |
| 162 |
:envvar:`PYTHONWARNINGS`, *message* is a literal string that the start of the |
| 163 |
warning message must contain (case-insensitively), ignoring any whitespace at |
| 164 |
the start or end of *message*. |
| 165 |
|
| 166 |
* *category* is a class (a subclass of :exc:`Warning`) of which the warning |
| 167 |
category must be a subclass in order to match. |
| 168 |
|
| 169 |
* *module* is a string containing a regular expression that the start of the |
| 170 |
fully qualified module name must match, case-sensitively. In :option:`-W` and |
| 171 |
:envvar:`PYTHONWARNINGS`, *module* is a literal string that the |
| 172 |
fully qualified module name must be equal to (case-sensitively), ignoring any |
| 173 |
whitespace at the start or end of *module*. |
| 174 |
|
| 175 |
* *lineno* is an integer that the line number where the warning occurred must |
| 176 |
match, or ``0`` to match all line numbers. |
| 177 |
|
| 178 |
Since the :exc:`Warning` class is derived from the built-in :exc:`Exception` |
| 179 |
class, to turn a warning into an error we simply raise ``category(message)``. |
| 180 |
|
| 181 |
If a warning is reported and doesn't match any registered filter then the |
| 182 |
"default" action is applied (hence its name). |
| 183 |
|
| 184 |
|
| 185 |
|
| 186 |
.. _repeated-warning-suppression-criteria: |
| 187 |
|
| 188 |
Repeated Warning Suppression Criteria |
| 189 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 190 |
|
| 191 |
The filters that suppress repeated warnings apply the following criteria to determine if a warning is considered a repeat: |
| 192 |
|
| 193 |
- ``"default"``: A warning is considered a repeat only if the (*message*, *category*, *module*, *lineno*) are all the same. |
| 194 |
- ``"module"``: A warning is considered a repeat if the (*message*, *category*, *module*) are the same, ignoring the line number. |
| 195 |
- ``"once"``: A warning is considered a repeat if the (*message*, *category*) are the same, ignoring the module and line number. |
| 196 |
|
| 197 |
|
| 198 |
.. _describing-warning-filters: |
| 199 |
|
| 200 |
Describing Warning Filters |
| 201 |
~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 202 |
|
| 203 |
The warnings filter is initialized by :option:`-W` options passed to the Python |
| 204 |
interpreter command line and the :envvar:`PYTHONWARNINGS` environment variable. |
| 205 |
The interpreter saves the arguments for all supplied entries without |
| 206 |
interpretation in :data:`sys.warnoptions`; the :mod:`!warnings` module parses these |
| 207 |
when it is first imported (invalid options are ignored, after printing a |
| 208 |
message to :data:`sys.stderr`). |
| 209 |
|
| 210 |
Individual warnings filters are specified as a sequence of fields separated by |
| 211 |
colons:: |
| 212 |
|
| 213 |
action:message:category:module:line |
| 214 |
|
| 215 |
The meaning of each of these fields is as described in :ref:`warning-filter`. |
| 216 |
When listing multiple filters on a single line (as for |
| 217 |
:envvar:`PYTHONWARNINGS`), the individual filters are separated by commas and |
| 218 |
the filters listed later take precedence over those listed before them (as |
| 219 |
they're applied left-to-right, and the most recently applied filters take |
| 220 |
precedence over earlier ones). |
| 221 |
|
| 222 |
Commonly used warning filters apply to either all warnings, warnings in a |
| 223 |
particular category, or warnings raised by particular modules or packages. |
| 224 |
Some examples:: |
| 225 |
|
| 226 |
default # Show all warnings (even those ignored by default) |
| 227 |
ignore # Ignore all warnings |
| 228 |
error # Convert all warnings to errors |
| 229 |
error::ResourceWarning # Treat ResourceWarning messages as errors |
| 230 |
default::DeprecationWarning # Show DeprecationWarning messages |
| 231 |
ignore,default:::mymodule # Only report warnings triggered by "mymodule" |
| 232 |
error:::mymodule # Convert warnings to errors in "mymodule" |
| 233 |
|
| 234 |
|
| 235 |
.. _default-warning-filter: |
| 236 |
|
| 237 |
Default Warning Filter |
| 238 |
~~~~~~~~~~~~~~~~~~~~~~ |
| 239 |
|
| 240 |
By default, Python installs several warning filters, which can be overridden by |
| 241 |
the :option:`-W` command-line option, the :envvar:`PYTHONWARNINGS` environment |
| 242 |
variable and calls to :func:`filterwarnings`. |
| 243 |
|
| 244 |
In regular release builds, the default warning filter has the following entries |
| 245 |
(in order of precedence):: |
| 246 |
|
| 247 |
default::DeprecationWarning:__main__ |
| 248 |
ignore::DeprecationWarning |
| 249 |
ignore::PendingDeprecationWarning |
| 250 |
ignore::ImportWarning |
| 251 |
ignore::ResourceWarning |
| 252 |
|
| 253 |
In a :ref:`debug build <debug-build>`, the list of default warning filters is empty. |
| 254 |
|
| 255 |
.. versionchanged:: 3.2 |
| 256 |
:exc:`DeprecationWarning` is now ignored by default in addition to |
| 257 |
:exc:`PendingDeprecationWarning`. |
| 258 |
|
| 259 |
.. versionchanged:: 3.7 |
| 260 |
:exc:`DeprecationWarning` is once again shown by default when triggered |
| 261 |
directly by code in ``__main__``. |
| 262 |
|
| 263 |
.. versionchanged:: 3.7 |
| 264 |
:exc:`BytesWarning` no longer appears in the default filter list and is |
| 265 |
instead configured via :data:`sys.warnoptions` when :option:`-b` is specified |
| 266 |
twice. |
| 267 |
|
| 268 |
|
| 269 |
.. _warning-disable: |
| 270 |
|
| 271 |
Overriding the default filter |
| 272 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 273 |
|
| 274 |
Developers of applications written in Python may wish to hide *all* Python level |
| 275 |
warnings from their users by default, and only display them when running tests |
| 276 |
or otherwise working on the application. The :data:`sys.warnoptions` attribute |
| 277 |
used to pass filter configurations to the interpreter can be used as a marker to |
| 278 |
indicate whether or not warnings should be disabled:: |
| 279 |
|
| 280 |
import sys |
| 281 |
|
| 282 |
if not sys.warnoptions: |
| 283 |
import warnings |
| 284 |
warnings.simplefilter("ignore") |
| 285 |
|
| 286 |
Developers of test runners for Python code are advised to instead ensure that |
| 287 |
*all* warnings are displayed by default for the code under test, using code |
| 288 |
like:: |
| 289 |
|
| 290 |
import sys |
| 291 |
|
| 292 |
if not sys.warnoptions: |
| 293 |
import os, warnings |
| 294 |
warnings.simplefilter("default") # Change the filter in this process |
| 295 |
os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses |
| 296 |
|
| 297 |
Finally, developers of interactive shells that run user code in a namespace |
| 298 |
other than ``__main__`` are advised to ensure that :exc:`DeprecationWarning` |
| 299 |
messages are made visible by default, using code like the following (where |
| 300 |
``user_ns`` is the module used to execute code entered interactively):: |
| 301 |
|
| 302 |
import warnings |
| 303 |
warnings.filterwarnings("default", category=DeprecationWarning, |
| 304 |
module=user_ns.get("__name__")) |
| 305 |
|
| 306 |
|
| 307 |
.. _warning-suppress: |
| 308 |
|
| 309 |
Temporarily Suppressing Warnings |
| 310 |
-------------------------------- |
| 311 |
|
| 312 |
If you are using code that you know will raise a warning, such as a deprecated |
| 313 |
function, but do not want to see the warning (even when warnings have been |
| 314 |
explicitly configured via the command line), then it is possible to suppress |
| 315 |
the warning using the :class:`catch_warnings` context manager:: |
| 316 |
|
| 317 |
import warnings |
| 318 |
|
| 319 |
def fxn(): |
| 320 |
warnings.warn("deprecated", DeprecationWarning) |
| 321 |
|
| 322 |
with warnings.catch_warnings(): |
| 323 |
warnings.simplefilter("ignore") |
| 324 |
fxn() |
| 325 |
|
| 326 |
While within the context manager all warnings will simply be ignored. This |
| 327 |
allows you to use known-deprecated code without having to see the warning while |
| 328 |
not suppressing the warning for other code that might not be aware of its use |
| 329 |
of deprecated code. |
| 330 |
|
| 331 |
.. note:: |
| 332 |
|
| 333 |
See :ref:`warning-concurrent-safe` for details on the |
| 334 |
concurrency-safety of the :class:`catch_warnings` context manager when |
| 335 |
used in programs using multiple threads or async functions. |
| 336 |
|
| 337 |
.. _warning-testing: |
| 338 |
|
| 339 |
Testing Warnings |
| 340 |
---------------- |
| 341 |
|
| 342 |
To test warnings raised by code, use the :class:`catch_warnings` context |
| 343 |
manager. With it you can temporarily mutate the warnings filter to facilitate |
| 344 |
your testing. For instance, do the following to capture all raised warnings to |
| 345 |
check:: |
| 346 |
|
| 347 |
import warnings |
| 348 |
|
| 349 |
def fxn(): |
| 350 |
warnings.warn("deprecated", DeprecationWarning) |
| 351 |
|
| 352 |
with warnings.catch_warnings(record=True) as w: |
| 353 |
# Cause all warnings to always be triggered. |
| 354 |
warnings.simplefilter("always") |
| 355 |
# Trigger a warning. |
| 356 |
fxn() |
| 357 |
# Verify some things |
| 358 |
assert len(w) == 1 |
| 359 |
assert issubclass(w[-1].category, DeprecationWarning) |
| 360 |
assert "deprecated" in str(w[-1].message) |
| 361 |
|
| 362 |
One can also cause all warnings to be exceptions by using ``error`` instead of |
| 363 |
``always``. One thing to be aware of is that if a warning has already been |
| 364 |
raised because of a ``once``/``default`` rule, then no matter what filters are |
| 365 |
set the warning will not be seen again unless the warnings registry related to |
| 366 |
the warning has been cleared. |
| 367 |
|
| 368 |
Once the context manager exits, the warnings filter is restored to its state |
| 369 |
when the context was entered. This prevents tests from changing the warnings |
| 370 |
filter in unexpected ways between tests and leading to indeterminate test |
| 371 |
results. |
| 372 |
|
| 373 |
.. note:: |
| 374 |
|
| 375 |
See :ref:`warning-concurrent-safe` for details on the |
| 376 |
concurrency-safety of the :class:`catch_warnings` context manager when |
| 377 |
used in programs using multiple threads or async functions. |
| 378 |
|
| 379 |
When testing multiple operations that raise the same kind of warning, it |
| 380 |
is important to test them in a manner that confirms each operation is raising |
| 381 |
a new warning (e.g. set warnings to be raised as exceptions and check the |
| 382 |
operations raise exceptions, check that the length of the warning list |
| 383 |
continues to increase after each operation, or else delete the previous |
| 384 |
entries from the warnings list before each new operation). |
| 385 |
|
| 386 |
|
| 387 |
.. _warning-ignored: |
| 388 |
|
| 389 |
Updating Code For New Versions of Dependencies |
| 390 |
---------------------------------------------- |
| 391 |
|
| 392 |
Warning categories that are primarily of interest to Python developers (rather |
| 393 |
than end users of applications written in Python) are ignored by default. |
| 394 |
|
| 395 |
Notably, this "ignored by default" list includes :exc:`DeprecationWarning` |
| 396 |
(for every module except ``__main__``), which means developers should make sure |
| 397 |
to test their code with typically ignored warnings made visible in order to |
| 398 |
receive timely notifications of future breaking API changes (whether in the |
| 399 |
standard library or third party packages). |
| 400 |
|
| 401 |
In the ideal case, the code will have a suitable test suite, and the test runner |
| 402 |
will take care of implicitly enabling all warnings when running tests |
| 403 |
(the test runner provided by the :mod:`unittest` module does this). |
| 404 |
|
| 405 |
In less ideal cases, applications can be checked for use of deprecated |
| 406 |
interfaces by passing :option:`-Wd <-W>` to the Python interpreter (this is |
| 407 |
shorthand for :option:`!-W default`) or setting ``PYTHONWARNINGS=default`` in |
| 408 |
the environment. This enables default handling for all warnings, including those |
| 409 |
that are ignored by default. To change what action is taken for encountered |
| 410 |
warnings you can change what argument is passed to :option:`-W` (e.g. |
| 411 |
:option:`!-W error`). See the :option:`-W` flag for more details on what is |
| 412 |
possible. |
| 413 |
|
| 414 |
|
| 415 |
.. _warning-functions: |
| 416 |
|
| 417 |
Available Functions |
| 418 |
------------------- |
| 419 |
|
| 420 |
|
| 421 |
.. function:: warn(message, category=None, stacklevel=1, source=None, *, skip_file_prefixes=()) |
| 422 |
|
| 423 |
Issue a warning, or maybe ignore it or raise an exception. The *category* |
| 424 |
argument, if given, must be a :ref:`warning category class <warning-categories>`; it |
| 425 |
defaults to :exc:`UserWarning`. Alternatively, *message* can be a :exc:`Warning` instance, |
| 426 |
in which case *category* will be ignored and ``message.__class__`` will be used. |
| 427 |
In this case, the message text will be ``str(message)``. This function raises an |
| 428 |
exception if the particular warning issued is changed into an error by the |
| 429 |
:ref:`warnings filter <warning-filter>`. The *stacklevel* argument can be used by wrapper |
| 430 |
functions written in Python, like this:: |
| 431 |
|
| 432 |
def deprecated_api(message): |
| 433 |
warnings.warn(message, DeprecationWarning, stacklevel=2) |
| 434 |
|
| 435 |
This makes the warning refer to ``deprecated_api``'s caller, rather than to |
| 436 |
the source of ``deprecated_api`` itself (since the latter would defeat the |
| 437 |
purpose of the warning message). |
| 438 |
|
| 439 |
The *skip_file_prefixes* keyword argument can be used to indicate which |
| 440 |
stack frames are ignored when counting stack levels. This can be useful when |
| 441 |
you want the warning to always appear at call sites outside of a package |
| 442 |
when a constant *stacklevel* does not fit all call paths or is otherwise |
| 443 |
challenging to maintain. If supplied, it must be a tuple of strings. When |
| 444 |
prefixes are supplied, stacklevel is implicitly overridden to be ``max(2, |
| 445 |
stacklevel)``. To cause a warning to be attributed to the caller from |
| 446 |
outside of the current package you might write:: |
| 447 |
|
| 448 |
# example/lower.py |
| 449 |
_warn_skips = (os.path.dirname(__file__),) |
| 450 |
|
| 451 |
def one_way(r_luxury_yacht=None, t_wobbler_mangrove=None): |
| 452 |
if r_luxury_yacht: |
| 453 |
warnings.warn("Please migrate to t_wobbler_mangrove=.", |
| 454 |
skip_file_prefixes=_warn_skips) |
| 455 |
|
| 456 |
# example/higher.py |
| 457 |
from . import lower |
| 458 |
|
| 459 |
def another_way(**kw): |
| 460 |
lower.one_way(**kw) |
| 461 |
|
| 462 |
This makes the warning refer to both the ``example.lower.one_way()`` and |
| 463 |
``example.higher.another_way()`` call sites only from calling code living |
| 464 |
outside of ``example`` package. |
| 465 |
|
| 466 |
*source*, if supplied, is the destroyed object which emitted a |
| 467 |
:exc:`ResourceWarning`. |
| 468 |
|
| 469 |
.. versionchanged:: 3.6 |
| 470 |
Added *source* parameter. |
| 471 |
|
| 472 |
.. versionchanged:: 3.12 |
| 473 |
Added *skip_file_prefixes*. |
| 474 |
|
| 475 |
|
| 476 |
.. function:: warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None, source=None) |
| 477 |
|
| 478 |
This is a low-level interface to the functionality of :func:`warn`, passing in |
| 479 |
explicitly the message, category, filename and line number, and optionally |
| 480 |
other arguments. |
| 481 |
*message* must be a string and *category* a subclass of :exc:`Warning` or |
| 482 |
*message* may be a :exc:`Warning` instance, in which case *category* will be |
| 483 |
ignored. |
| 484 |
|
| 485 |
*module*, if supplied, should be the module name. |
| 486 |
If no module is passed, the filename with ``.py`` stripped is used. |
| 487 |
|
| 488 |
*registry*, if supplied, should be the ``__warningregistry__`` dictionary |
| 489 |
of the module. |
| 490 |
If no registry is passed, each warning is treated as the first occurrence, |
| 491 |
that is, filter actions ``"default"``, ``"module"`` and ``"once"`` are |
| 492 |
handled as ``"always"``. |
| 493 |
|
| 494 |
*module_globals*, if supplied, should be the global namespace in use by the code |
| 495 |
for which the warning is issued. (This argument is used to support displaying |
| 496 |
source for modules found in zipfiles or other non-filesystem import |
| 497 |
sources). |
| 498 |
|
| 499 |
*source*, if supplied, is the destroyed object which emitted a |
| 500 |
:exc:`ResourceWarning`. |
| 501 |
|
| 502 |
.. versionchanged:: 3.6 |
| 503 |
Add the *source* parameter. |
| 504 |
|
| 505 |
|
| 506 |
.. function:: showwarning(message, category, filename, lineno, file=None, line=None) |
| 507 |
|
| 508 |
Write a warning to a file. The default implementation calls |
| 509 |
``formatwarning(message, category, filename, lineno, line)`` and writes the |
| 510 |
resulting string to *file*, which defaults to :data:`sys.stderr`. You may replace |
| 511 |
this function with any callable by assigning to ``warnings.showwarning``. |
| 512 |
*line* is a line of source code to be included in the warning |
| 513 |
message; if *line* is not supplied, :func:`showwarning` will |
| 514 |
try to read the line specified by *filename* and *lineno*. |
| 515 |
|
| 516 |
|
| 517 |
.. function:: formatwarning(message, category, filename, lineno, line=None) |
| 518 |
|
| 519 |
Format a warning the standard way. This returns a string which may contain |
| 520 |
embedded newlines and ends in a newline. *line* is a line of source code to |
| 521 |
be included in the warning message; if *line* is not supplied, |
| 522 |
:func:`formatwarning` will try to read the line specified by *filename* and |
| 523 |
*lineno*. |
| 524 |
|
| 525 |
|
| 526 |
.. function:: filterwarnings(action, message='', category=Warning, module='', lineno=0, append=False) |
| 527 |
|
| 528 |
Insert an entry into the list of :ref:`warnings filter specifications |
| 529 |
<warning-filter>`. The entry is inserted at the front by default; if |
| 530 |
*append* is true, it is inserted at the end. This checks the types of the |
| 531 |
arguments, compiles the *message* and *module* regular expressions, and |
| 532 |
inserts them as a tuple in the list of warnings filters. Entries closer to |
| 533 |
the front of the list override entries later in the list, if both match a |
| 534 |
particular warning. Omitted arguments default to a value that matches |
| 535 |
everything. |
| 536 |
|
| 537 |
|
| 538 |
.. function:: simplefilter(action, category=Warning, lineno=0, append=False) |
| 539 |
|
| 540 |
Insert a simple entry into the list of :ref:`warnings filter specifications |
| 541 |
<warning-filter>`. The meaning of the function parameters is as for |
| 542 |
:func:`filterwarnings`, but regular expressions are not needed as the filter |
| 543 |
inserted always matches any message in any module as long as the category and |
| 544 |
line number match. |
| 545 |
|
| 546 |
|
| 547 |
.. function:: resetwarnings() |
| 548 |
|
| 549 |
Reset the warnings filter. This discards the effect of all previous calls to |
| 550 |
:func:`filterwarnings`, including that of the :option:`-W` command line options |
| 551 |
and calls to :func:`simplefilter`. |
| 552 |
|
| 553 |
|
| 554 |
.. decorator:: deprecated(msg, *, category=DeprecationWarning, stacklevel=1) |
| 555 |
|
| 556 |
Decorator to indicate that a class, function or overload is deprecated. |
| 557 |
|
| 558 |
When this decorator is applied to an object, |
| 559 |
deprecation warnings may be emitted at runtime when the object is used. |
| 560 |
:term:`static type checkers <static type checker>` |
| 561 |
will also generate a diagnostic on usage of the deprecated object. |
| 562 |
|
| 563 |
Usage:: |
| 564 |
|
| 565 |
from warnings import deprecated |
| 566 |
from typing import overload |
| 567 |
|
| 568 |
@deprecated("Use B instead") |
| 569 |
class A: |
| 570 |
pass |
| 571 |
|
| 572 |
@deprecated("Use g instead") |
| 573 |
def f(): |
| 574 |
pass |
| 575 |
|
| 576 |
@overload |
| 577 |
@deprecated("int support is deprecated") |
| 578 |
def g(x: int) -> int: ... |
| 579 |
@overload |
| 580 |
def g(x: str) -> int: ... |
| 581 |
|
| 582 |
The warning specified by *category* will be emitted at runtime |
| 583 |
on use of deprecated objects. For functions, that happens on calls; |
| 584 |
for classes, on instantiation and on creation of subclasses. |
| 585 |
If the *category* is ``None``, no warning is emitted at runtime. |
| 586 |
The *stacklevel* determines where the |
| 587 |
warning is emitted. If it is ``1`` (the default), the warning |
| 588 |
is emitted at the direct caller of the deprecated object; if it |
| 589 |
is higher, it is emitted further up the stack. |
| 590 |
Static type checker behavior is not affected by the *category* |
| 591 |
and *stacklevel* arguments. |
| 592 |
|
| 593 |
The deprecation message passed to the decorator is saved in the |
| 594 |
``__deprecated__`` attribute on the decorated object. |
| 595 |
If applied to an overload, the decorator |
| 596 |
must be after the :deco:`~typing.overload` decorator |
| 597 |
for the attribute to exist on the overload as returned by |
| 598 |
:func:`typing.get_overloads`. |
| 599 |
|
| 600 |
.. versionadded:: 3.13 |
| 601 |
See :pep:`702`. |
| 602 |
|
| 603 |
|
| 604 |
Available Context Managers |
| 605 |
-------------------------- |
| 606 |
|
| 607 |
.. class:: catch_warnings(*, record=False, module=None, action=None, category=Warning, lineno=0, append=False) |
| 608 |
|
| 609 |
A context manager that copies and, upon exit, restores the warnings filter |
| 610 |
and the :func:`showwarning` function. |
| 611 |
If the *record* argument is :const:`False` (the default) the context manager |
| 612 |
returns :class:`None` on entry. If *record* is :const:`True`, a list is |
| 613 |
returned that is progressively populated with objects as seen by a custom |
| 614 |
:func:`showwarning` function (which also suppresses output to ``sys.stdout``). |
| 615 |
Each object in the list has attributes with the same names as the arguments to |
| 616 |
:func:`showwarning`. |
| 617 |
|
| 618 |
The *module* argument takes a module that will be used instead of the |
| 619 |
module returned when you import :mod:`!warnings` whose filter will be |
| 620 |
protected. This argument exists primarily for testing the :mod:`!warnings` |
| 621 |
module itself. |
| 622 |
|
| 623 |
If the *action* argument is not ``None``, the remaining arguments are |
| 624 |
passed to :func:`simplefilter` as if it were called immediately on |
| 625 |
entering the context. |
| 626 |
|
| 627 |
See :ref:`warning-filter` for the meaning of the *category* and *lineno* |
| 628 |
parameters. |
| 629 |
|
| 630 |
.. note:: |
| 631 |
|
| 632 |
See :ref:`warning-concurrent-safe` for details on the |
| 633 |
concurrency-safety of the :class:`catch_warnings` context manager when |
| 634 |
used in programs using multiple threads or async functions. |
| 635 |
|
| 636 |
|
| 637 |
.. versionchanged:: 3.11 |
| 638 |
|
| 639 |
Added the *action*, *category*, *lineno*, and *append* parameters. |
| 640 |
|
| 641 |
|
| 642 |
.. _warning-concurrent-safe: |
| 643 |
|
| 644 |
Concurrent safety of Context Managers |
| 645 |
------------------------------------- |
| 646 |
|
| 647 |
The behavior of :class:`catch_warnings` context manager depends on the |
| 648 |
:data:`sys.flags.context_aware_warnings` flag. If the flag is true, the |
| 649 |
context manager behaves in a concurrent-safe fashion and otherwise not. |
| 650 |
Concurrent-safe means that it is both thread-safe and safe to use within |
| 651 |
:ref:`asyncio coroutines <coroutine>` and tasks. Being thread-safe means |
| 652 |
that behavior is predictable in a multi-threaded program. The flag defaults |
| 653 |
to true for free-threaded builds and false otherwise. |
| 654 |
|
| 655 |
If the :data:`~sys.flags.context_aware_warnings` flag is false, then |
| 656 |
:class:`catch_warnings` will modify the global attributes of the |
| 657 |
:mod:`!warnings` module. This is not safe if used within a concurrent program |
| 658 |
(using multiple threads or using asyncio coroutines). For example, if two |
| 659 |
or more threads use the :class:`catch_warnings` class at the same time, the |
| 660 |
behavior is undefined. |
| 661 |
|
| 662 |
If the flag is true, :class:`catch_warnings` will not modify global |
| 663 |
attributes and will instead use a :class:`~contextvars.ContextVar` to |
| 664 |
store the newly established warning filtering state. A context variable |
| 665 |
provides thread-local storage and it makes the use of :class:`catch_warnings` |
| 666 |
thread-safe. |
| 667 |
|
| 668 |
The *record* parameter of the context handler also behaves differently |
| 669 |
depending on the value of the flag. When *record* is true and the flag is |
| 670 |
false, the context manager works by replacing and then later restoring the |
| 671 |
module's :func:`showwarning` function. That is not concurrent-safe. |
| 672 |
|
| 673 |
When *record* is true and the flag is true, the :func:`showwarning` function |
| 674 |
is not replaced. Instead, the recording status is indicated by an internal |
| 675 |
property in the context variable. In this case, the :func:`showwarning` |
| 676 |
function will not be restored when exiting the context handler. |
| 677 |
|
| 678 |
The :data:`~sys.flags.context_aware_warnings` flag can be set the :option:`-X |
| 679 |
context_aware_warnings<-X>` command-line option or by the |
| 680 |
:envvar:`PYTHON_CONTEXT_AWARE_WARNINGS` environment variable. |
| 681 |
|
| 682 |
.. note:: |
| 683 |
|
| 684 |
It is likely that most programs that desire thread-safe |
| 685 |
behaviour of the warnings module will also want to set the |
| 686 |
:data:`~sys.flags.thread_inherit_context` flag to true. That flag |
| 687 |
causes threads created by :class:`threading.Thread` to start |
| 688 |
with a copy of the context variables from the thread starting |
| 689 |
it. When true, the context established by :class:`catch_warnings` |
| 690 |
in one thread will also apply to new threads started by it. If false, |
| 691 |
new threads will start with an empty warnings context variable, |
| 692 |
meaning that any filtering that was established by a |
| 693 |
:class:`catch_warnings` context manager will no longer be active. |
| 694 |
|
| 695 |
.. versionchanged:: 3.14 |
| 696 |
|
| 697 |
Added the :data:`sys.flags.context_aware_warnings` flag and the use of a |
| 698 |
context variable for :class:`catch_warnings` if the flag is true. Previous |
| 699 |
versions of Python acted as if the flag was always set to false. |