PageRenderTime 27ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/Doc/library/warnings.rst

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