Debian Codegraph @

Doc/library/warnings.rst

raw
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 | ``"module"`` | print the first occurrence of matching |
151 | | warnings for each module where the warning |
152 | | is issued (regardless of line number) |
153 +---------------+----------------------------------------------+
154 | ``"once"`` | print only the first occurrence of matching |
155 | | warnings, regardless of location |
156 +---------------+----------------------------------------------+
157
158 * *message* is a string containing a regular expression that the start of
159 the warning message must match, case-insensitively. In :option:`-W` and
160 :envvar:`PYTHONWARNINGS`, *message* is a literal string that the start of the
161 warning message must contain (case-insensitively), ignoring any whitespace at
162 the start or end of *message*.
163
164 * *category* is a class (a subclass of :exc:`Warning`) of which the warning
165 category must be a subclass in order to match.
166
167 * *module* is a string containing a regular expression that the start of the
168 fully qualified module name must match, case-sensitively. In :option:`-W` and
169 :envvar:`PYTHONWARNINGS`, *module* is a literal string that the
170 fully qualified module name must be equal to (case-sensitively), ignoring any
171 whitespace at the start or end of *module*.
172
173 * *lineno* is an integer that the line number where the warning occurred must
174 match, or ``0`` to match all line numbers.
175
176 Since the :exc:`Warning` class is derived from the built-in :exc:`Exception`
177 class, to turn a warning into an error we simply raise ``category(message)``.
178
179 If a warning is reported and doesn't match any registered filter then the
180 "default" action is applied (hence its name).
181
182
183
184 .. _repeated-warning-suppression-criteria:
185
186 Repeated Warning Suppression Criteria
187 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
188
189 The filters that suppress repeated warnings apply the following criteria to determine if a warning is considered a repeat:
190
191 - ``"default"``: A warning is considered a repeat only if the (*message*, *category*, *module*, *lineno*) are all the same.
192 - ``"module"``: A warning is considered a repeat if the (*message*, *category*, *module*) are the same, ignoring the line number.
193 - ``"once"``: A warning is considered a repeat if the (*message*, *category*) are the same, ignoring the module and line number.
194
195
196 .. _describing-warning-filters:
197
198 Describing Warning Filters
199 ~~~~~~~~~~~~~~~~~~~~~~~~~~
200
201 The warnings filter is initialized by :option:`-W` options passed to the Python
202 interpreter command line and the :envvar:`PYTHONWARNINGS` environment variable.
203 The interpreter saves the arguments for all supplied entries without
204 interpretation in :data:`sys.warnoptions`; the :mod:`warnings` module parses these
205 when it is first imported (invalid options are ignored, after printing a
206 message to :data:`sys.stderr`).
207
208 Individual warnings filters are specified as a sequence of fields separated by
209 colons::
210
211 action:message:category:module:line
212
213 The meaning of each of these fields is as described in :ref:`warning-filter`.
214 When listing multiple filters on a single line (as for
215 :envvar:`PYTHONWARNINGS`), the individual filters are separated by commas and
216 the filters listed later take precedence over those listed before them (as
217 they're applied left-to-right, and the most recently applied filters take
218 precedence over earlier ones).
219
220 Commonly used warning filters apply to either all warnings, warnings in a
221 particular category, or warnings raised by particular modules or packages.
222 Some examples::
223
224 default # Show all warnings (even those ignored by default)
225 ignore # Ignore all warnings
226 error # Convert all warnings to errors
227 error::ResourceWarning # Treat ResourceWarning messages as errors
228 default::DeprecationWarning # Show DeprecationWarning messages
229 ignore,default:::mymodule # Only report warnings triggered by "mymodule"
230 error:::mymodule # Convert warnings to errors in "mymodule"
231
232
233 .. _default-warning-filter:
234
235 Default Warning Filter
236 ~~~~~~~~~~~~~~~~~~~~~~
237
238 By default, Python installs several warning filters, which can be overridden by
239 the :option:`-W` command-line option, the :envvar:`PYTHONWARNINGS` environment
240 variable and calls to :func:`filterwarnings`.
241
242 In regular release builds, the default warning filter has the following entries
243 (in order of precedence)::
244
245 default::DeprecationWarning:__main__
246 ignore::DeprecationWarning
247 ignore::PendingDeprecationWarning
248 ignore::ImportWarning
249 ignore::ResourceWarning
250
251 In a :ref:`debug build <debug-build>`, the list of default warning filters is empty.
252
253 .. versionchanged:: 3.2
254 :exc:`DeprecationWarning` is now ignored by default in addition to
255 :exc:`PendingDeprecationWarning`.
256
257 .. versionchanged:: 3.7
258 :exc:`DeprecationWarning` is once again shown by default when triggered
259 directly by code in ``__main__``.
260
261 .. versionchanged:: 3.7
262 :exc:`BytesWarning` no longer appears in the default filter list and is
263 instead configured via :data:`sys.warnoptions` when :option:`-b` is specified
264 twice.
265
266
267 .. _warning-disable:
268
269 Overriding the default filter
270 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
271
272 Developers of applications written in Python may wish to hide *all* Python level
273 warnings from their users by default, and only display them when running tests
274 or otherwise working on the application. The :data:`sys.warnoptions` attribute
275 used to pass filter configurations to the interpreter can be used as a marker to
276 indicate whether or not warnings should be disabled::
277
278 import sys
279
280 if not sys.warnoptions:
281 import warnings
282 warnings.simplefilter("ignore")
283
284 Developers of test runners for Python code are advised to instead ensure that
285 *all* warnings are displayed by default for the code under test, using code
286 like::
287
288 import sys
289
290 if not sys.warnoptions:
291 import os, warnings
292 warnings.simplefilter("default") # Change the filter in this process
293 os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
294
295 Finally, developers of interactive shells that run user code in a namespace
296 other than ``__main__`` are advised to ensure that :exc:`DeprecationWarning`
297 messages are made visible by default, using code like the following (where
298 ``user_ns`` is the module used to execute code entered interactively)::
299
300 import warnings
301 warnings.filterwarnings("default", category=DeprecationWarning,
302 module=user_ns.get("__name__"))
303
304
305 .. _warning-suppress:
306
307 Temporarily Suppressing Warnings
308 --------------------------------
309
310 If you are using code that you know will raise a warning, such as a deprecated
311 function, but do not want to see the warning (even when warnings have been
312 explicitly configured via the command line), then it is possible to suppress
313 the warning using the :class:`catch_warnings` context manager::
314
315 import warnings
316
317 def fxn():
318 warnings.warn("deprecated", DeprecationWarning)
319
320 with warnings.catch_warnings():
321 warnings.simplefilter("ignore")
322 fxn()
323
324 While within the context manager all warnings will simply be ignored. This
325 allows you to use known-deprecated code without having to see the warning while
326 not suppressing the warning for other code that might not be aware of its use
327 of deprecated code. Note: this can only be guaranteed in a single-threaded
328 application. If two or more threads use the :class:`catch_warnings` context
329 manager at the same time, the behavior is undefined.
330
331
332
333 .. _warning-testing:
334
335 Testing Warnings
336 ----------------
337
338 To test warnings raised by code, use the :class:`catch_warnings` context
339 manager. With it you can temporarily mutate the warnings filter to facilitate
340 your testing. For instance, do the following to capture all raised warnings to
341 check::
342
343 import warnings
344
345 def fxn():
346 warnings.warn("deprecated", DeprecationWarning)
347
348 with warnings.catch_warnings(record=True) as w:
349 # Cause all warnings to always be triggered.
350 warnings.simplefilter("always")
351 # Trigger a warning.
352 fxn()
353 # Verify some things
354 assert len(w) == 1
355 assert issubclass(w[-1].category, DeprecationWarning)
356 assert "deprecated" in str(w[-1].message)
357
358 One can also cause all warnings to be exceptions by using ``error`` instead of
359 ``always``. One thing to be aware of is that if a warning has already been
360 raised because of a ``once``/``default`` rule, then no matter what filters are
361 set the warning will not be seen again unless the warnings registry related to
362 the warning has been cleared.
363
364 Once the context manager exits, the warnings filter is restored to its state
365 when the context was entered. This prevents tests from changing the warnings
366 filter in unexpected ways between tests and leading to indeterminate test
367 results. The :func:`showwarning` function in the module is also restored to
368 its original value. Note: this can only be guaranteed in a single-threaded
369 application. If two or more threads use the :class:`catch_warnings` context
370 manager at the same time, the behavior is undefined.
371
372 When testing multiple operations that raise the same kind of warning, it
373 is important to test them in a manner that confirms each operation is raising
374 a new warning (e.g. set warnings to be raised as exceptions and check the
375 operations raise exceptions, check that the length of the warning list
376 continues to increase after each operation, or else delete the previous
377 entries from the warnings list before each new operation).
378
379
380 .. _warning-ignored:
381
382 Updating Code For New Versions of Dependencies
383 ----------------------------------------------
384
385 Warning categories that are primarily of interest to Python developers (rather
386 than end users of applications written in Python) are ignored by default.
387
388 Notably, this "ignored by default" list includes :exc:`DeprecationWarning`
389 (for every module except ``__main__``), which means developers should make sure
390 to test their code with typically ignored warnings made visible in order to
391 receive timely notifications of future breaking API changes (whether in the
392 standard library or third party packages).
393
394 In the ideal case, the code will have a suitable test suite, and the test runner
395 will take care of implicitly enabling all warnings when running tests
396 (the test runner provided by the :mod:`unittest` module does this).
397
398 In less ideal cases, applications can be checked for use of deprecated
399 interfaces by passing :option:`-Wd <-W>` to the Python interpreter (this is
400 shorthand for :option:`!-W default`) or setting ``PYTHONWARNINGS=default`` in
401 the environment. This enables default handling for all warnings, including those
402 that are ignored by default. To change what action is taken for encountered
403 warnings you can change what argument is passed to :option:`-W` (e.g.
404 :option:`!-W error`). See the :option:`-W` flag for more details on what is
405 possible.
406
407
408 .. _warning-functions:
409
410 Available Functions
411 -------------------
412
413
414 .. function:: warn(message, category=None, stacklevel=1, source=None, *, skip_file_prefixes=())
415
416 Issue a warning, or maybe ignore it or raise an exception. The *category*
417 argument, if given, must be a :ref:`warning category class <warning-categories>`; it
418 defaults to :exc:`UserWarning`. Alternatively, *message* can be a :exc:`Warning` instance,
419 in which case *category* will be ignored and ``message.__class__`` will be used.
420 In this case, the message text will be ``str(message)``. This function raises an
421 exception if the particular warning issued is changed into an error by the
422 :ref:`warnings filter <warning-filter>`. The *stacklevel* argument can be used by wrapper
423 functions written in Python, like this::
424
425 def deprecated_api(message):
426 warnings.warn(message, DeprecationWarning, stacklevel=2)
427
428 This makes the warning refer to ``deprecated_api``'s caller, rather than to
429 the source of ``deprecated_api`` itself (since the latter would defeat the
430 purpose of the warning message).
431
432 The *skip_file_prefixes* keyword argument can be used to indicate which
433 stack frames are ignored when counting stack levels. This can be useful when
434 you want the warning to always appear at call sites outside of a package
435 when a constant *stacklevel* does not fit all call paths or is otherwise
436 challenging to maintain. If supplied, it must be a tuple of strings. When
437 prefixes are supplied, stacklevel is implicitly overridden to be ``max(2,
438 stacklevel)``. To cause a warning to be attributed to the caller from
439 outside of the current package you might write::
440
441 # example/lower.py
442 _warn_skips = (os.path.dirname(__file__),)
443
444 def one_way(r_luxury_yacht=None, t_wobbler_mangrove=None):
445 if r_luxury_yacht:
446 warnings.warn("Please migrate to t_wobbler_mangrove=.",
447 skip_file_prefixes=_warn_skips)
448
449 # example/higher.py
450 from . import lower
451
452 def another_way(**kw):
453 lower.one_way(**kw)
454
455 This makes the warning refer to both the ``example.lower.one_way()`` and
456 ``example.higher.another_way()`` call sites only from calling code living
457 outside of ``example`` package.
458
459 *source*, if supplied, is the destroyed object which emitted a
460 :exc:`ResourceWarning`.
461
462 .. versionchanged:: 3.6
463 Added *source* parameter.
464
465 .. versionchanged:: 3.12
466 Added *skip_file_prefixes*.
467
468
469 .. function:: warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None, source=None)
470
471 This is a low-level interface to the functionality of :func:`warn`, passing in
472 explicitly the message, category, filename and line number, and optionally
473 other arguments.
474 *message* must be a string and *category* a subclass of :exc:`Warning` or
475 *message* may be a :exc:`Warning` instance, in which case *category* will be
476 ignored.
477
478 *module*, if supplied, should be the module name.
479 If no module is passed, the filename with ``.py`` stripped is used.
480
481 *registry*, if supplied, should be the ``__warningregistry__`` dictionary
482 of the module.
483 If no registry is passed, each warning is treated as the first occurrence,
484 that is, filter actions ``"default"``, ``"module"`` and ``"once"`` are
485 handled as ``"always"``.
486
487 *module_globals*, if supplied, should be the global namespace in use by the code
488 for which the warning is issued. (This argument is used to support displaying
489 source for modules found in zipfiles or other non-filesystem import
490 sources).
491
492 *source*, if supplied, is the destroyed object which emitted a
493 :exc:`ResourceWarning`.
494
495 .. versionchanged:: 3.6
496 Add the *source* parameter.
497
498
499 .. function:: showwarning(message, category, filename, lineno, file=None, line=None)
500
501 Write a warning to a file. The default implementation calls
502 ``formatwarning(message, category, filename, lineno, line)`` and writes the
503 resulting string to *file*, which defaults to :data:`sys.stderr`. You may replace
504 this function with any callable by assigning to ``warnings.showwarning``.
505 *line* is a line of source code to be included in the warning
506 message; if *line* is not supplied, :func:`showwarning` will
507 try to read the line specified by *filename* and *lineno*.
508
509
510 .. function:: formatwarning(message, category, filename, lineno, line=None)
511
512 Format a warning the standard way. This returns a string which may contain
513 embedded newlines and ends in a newline. *line* is a line of source code to
514 be included in the warning message; if *line* is not supplied,
515 :func:`formatwarning` will try to read the line specified by *filename* and
516 *lineno*.
517
518
519 .. function:: filterwarnings(action, message='', category=Warning, module='', lineno=0, append=False)
520
521 Insert an entry into the list of :ref:`warnings filter specifications
522 <warning-filter>`. The entry is inserted at the front by default; if
523 *append* is true, it is inserted at the end. This checks the types of the
524 arguments, compiles the *message* and *module* regular expressions, and
525 inserts them as a tuple in the list of warnings filters. Entries closer to
526 the front of the list override entries later in the list, if both match a
527 particular warning. Omitted arguments default to a value that matches
528 everything.
529
530
531 .. function:: simplefilter(action, category=Warning, lineno=0, append=False)
532
533 Insert a simple entry into the list of :ref:`warnings filter specifications
534 <warning-filter>`. The meaning of the function parameters is as for
535 :func:`filterwarnings`, but regular expressions are not needed as the filter
536 inserted always matches any message in any module as long as the category and
537 line number match.
538
539
540 .. function:: resetwarnings()
541
542 Reset the warnings filter. This discards the effect of all previous calls to
543 :func:`filterwarnings`, including that of the :option:`-W` command line options
544 and calls to :func:`simplefilter`.
545
546
547 .. decorator:: deprecated(message, /, *, category=DeprecationWarning, stacklevel=1)
548
549 Decorator to indicate that a class, function or overload is deprecated.
550
551 When this decorator is applied to an object,
552 deprecation warnings may be emitted at runtime when the object is used.
553 :term:`static type checkers <static type checker>`
554 will also generate a diagnostic on usage of the deprecated object.
555
556 Usage::
557
558 from warnings import deprecated
559 from typing import overload
560
561 @deprecated("Use B instead")
562 class A:
563 pass
564
565 @deprecated("Use g instead")
566 def f():
567 pass
568
569 @overload
570 @deprecated("int support is deprecated")
571 def g(x: int) -> int: ...
572 @overload
573 def g(x: str) -> int: ...
574
575 The warning specified by *category* will be emitted at runtime
576 on use of deprecated objects. For functions, that happens on calls;
577 for classes, on instantiation and on creation of subclasses.
578 If the *category* is ``None``, no warning is emitted at runtime.
579 The *stacklevel* determines where the
580 warning is emitted. If it is ``1`` (the default), the warning
581 is emitted at the direct caller of the deprecated object; if it
582 is higher, it is emitted further up the stack.
583 Static type checker behavior is not affected by the *category*
584 and *stacklevel* arguments.
585
586 The deprecation message passed to the decorator is saved in the
587 ``__deprecated__`` attribute on the decorated object.
588 If applied to an overload, the decorator
589 must be after the :deco:`~typing.overload` decorator
590 for the attribute to exist on the overload as returned by
591 :func:`typing.get_overloads`.
592
593 .. versionadded:: 3.13
594 See :pep:`702`.
595
596
597 Available Context Managers
598 --------------------------
599
600 .. class:: catch_warnings(*, record=False, module=None, action=None, category=Warning, lineno=0, append=False)
601
602 A context manager that copies and, upon exit, restores the warnings filter
603 and the :func:`showwarning` function.
604 If the *record* argument is :const:`False` (the default) the context manager
605 returns :class:`None` on entry. If *record* is :const:`True`, a list is
606 returned that is progressively populated with objects as seen by a custom
607 :func:`showwarning` function (which also suppresses output to ``sys.stderr``).
608 Each object in the list is guaranteed to have the following attributes:
609
610 - ``message``: the warning message (an instance of :exc:`Warning`)
611 - ``category``: the warning category (a subclass of :exc:`Warning`)
612 - ``filename``: the file name where the warning occurred (:class:`str`)
613 - ``lineno``: the line number in the file (:class:`int`)
614 - ``file``: the file object used for output (if any), or ``None``
615 - ``line``: the line of source code (if available), or ``None``
616 - ``source``: the original object that generated the warning (if
617 available), or ``None``
618
619 .. versionchanged:: 3.6
620 The ``source`` attribute was added.
621
622 The type of these objects is not specified and may change; only the
623 presence of these attributes is guaranteed.
624
625 The *module* argument takes a module that will be used instead of the
626 module returned when you import :mod:`warnings` whose filter will be
627 protected. This argument exists primarily for testing the :mod:`warnings`
628 module itself.
629
630 If the *action* argument is not ``None``, the remaining arguments are
631 passed to :func:`simplefilter` as if it were called immediately on
632 entering the context.
633
634 See :ref:`warning-filter` for the meaning of the *category* and *lineno*
635 parameters.
636
637 .. note::
638
639 The :class:`catch_warnings` manager works by replacing and
640 then later restoring the module's
641 :func:`showwarning` function and internal list of filter
642 specifications. This means the context manager is modifying
643 global state and therefore is not thread-safe.
644
645 .. versionchanged:: 3.11
646
647 Added the *action*, *category*, *lineno*, and *append* parameters.