/Doc/library/warnings.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 361 lines · 268 code · 93 blank · 0 comment · 0 complexity · 794a3c05702192c25ebaa065f6081f9f MD5 · raw file

  1. :mod:`warnings` --- Warning control
  2. ===================================
  3. .. index:: single: warnings
  4. .. module:: warnings
  5. :synopsis: Issue warning messages and control their disposition.
  6. .. versionadded:: 2.1
  7. Warning messages are typically issued in situations where it is useful to alert
  8. the user of some condition in a program, where that condition (normally) doesn't
  9. warrant raising an exception and terminating the program. For example, one
  10. might want to issue a warning when a program uses an obsolete module.
  11. Python programmers issue warnings by calling the :func:`warn` function defined
  12. in this module. (C programmers use :cfunc:`PyErr_WarnEx`; see
  13. :ref:`exceptionhandling` for details).
  14. Warning messages are normally written to ``sys.stderr``, but their disposition
  15. can be changed flexibly, from ignoring all warnings to turning them into
  16. exceptions. The disposition of warnings can vary based on the warning category
  17. (see below), the text of the warning message, and the source location where it
  18. is issued. Repetitions of a particular warning for the same source location are
  19. typically suppressed.
  20. There are two stages in warning control: first, each time a warning is issued, a
  21. determination is made whether a message should be issued or not; next, if a
  22. message is to be issued, it is formatted and printed using a user-settable hook.
  23. The determination whether to issue a warning message is controlled by the
  24. warning filter, which is a sequence of matching rules and actions. Rules can be
  25. added to the filter by calling :func:`filterwarnings` and reset to its default
  26. state by calling :func:`resetwarnings`.
  27. The printing of warning messages is done by calling :func:`showwarning`, which
  28. may be overridden; the default implementation of this function formats the
  29. message by calling :func:`formatwarning`, which is also available for use by
  30. custom implementations.
  31. .. _warning-categories:
  32. Warning Categories
  33. ------------------
  34. There are a number of built-in exceptions that represent warning categories.
  35. This categorization is useful to be able to filter out groups of warnings. The
  36. following warnings category classes are currently defined:
  37. +----------------------------------+-----------------------------------------------+
  38. | Class | Description |
  39. +==================================+===============================================+
  40. | :exc:`Warning` | This is the base class of all warning |
  41. | | category classes. It is a subclass of |
  42. | | :exc:`Exception`. |
  43. +----------------------------------+-----------------------------------------------+
  44. | :exc:`UserWarning` | The default category for :func:`warn`. |
  45. +----------------------------------+-----------------------------------------------+
  46. | :exc:`DeprecationWarning` | Base category for warnings about deprecated |
  47. | | features. |
  48. +----------------------------------+-----------------------------------------------+
  49. | :exc:`SyntaxWarning` | Base category for warnings about dubious |
  50. | | syntactic features. |
  51. +----------------------------------+-----------------------------------------------+
  52. | :exc:`RuntimeWarning` | Base category for warnings about dubious |
  53. | | runtime features. |
  54. +----------------------------------+-----------------------------------------------+
  55. | :exc:`FutureWarning` | Base category for warnings about constructs |
  56. | | that will change semantically in the future. |
  57. +----------------------------------+-----------------------------------------------+
  58. | :exc:`PendingDeprecationWarning` | Base category for warnings about features |
  59. | | that will be deprecated in the future |
  60. | | (ignored by default). |
  61. +----------------------------------+-----------------------------------------------+
  62. | :exc:`ImportWarning` | Base category for warnings triggered during |
  63. | | the process of importing a module (ignored by |
  64. | | default). |
  65. +----------------------------------+-----------------------------------------------+
  66. | :exc:`UnicodeWarning` | Base category for warnings related to |
  67. | | Unicode. |
  68. +----------------------------------+-----------------------------------------------+
  69. While these are technically built-in exceptions, they are documented here,
  70. because conceptually they belong to the warnings mechanism.
  71. User code can define additional warning categories by subclassing one of the
  72. standard warning categories. A warning category must always be a subclass of
  73. the :exc:`Warning` class.
  74. .. _warning-filter:
  75. The Warnings Filter
  76. -------------------
  77. The warnings filter controls whether warnings are ignored, displayed, or turned
  78. into errors (raising an exception).
  79. Conceptually, the warnings filter maintains an ordered list of filter
  80. specifications; any specific warning is matched against each filter
  81. specification in the list in turn until a match is found; the match determines
  82. the disposition of the match. Each entry is a tuple of the form (*action*,
  83. *message*, *category*, *module*, *lineno*), where:
  84. * *action* is one of the following strings:
  85. +---------------+----------------------------------------------+
  86. | Value | Disposition |
  87. +===============+==============================================+
  88. | ``"error"`` | turn matching warnings into exceptions |
  89. +---------------+----------------------------------------------+
  90. | ``"ignore"`` | never print matching warnings |
  91. +---------------+----------------------------------------------+
  92. | ``"always"`` | always print matching warnings |
  93. +---------------+----------------------------------------------+
  94. | ``"default"`` | print the first occurrence of matching |
  95. | | warnings for each location where the warning |
  96. | | is issued |
  97. +---------------+----------------------------------------------+
  98. | ``"module"`` | print the first occurrence of matching |
  99. | | warnings for each module where the warning |
  100. | | is issued |
  101. +---------------+----------------------------------------------+
  102. | ``"once"`` | print only the first occurrence of matching |
  103. | | warnings, regardless of location |
  104. +---------------+----------------------------------------------+
  105. * *message* is a string containing a regular expression that the warning message
  106. must match (the match is compiled to always be case-insensitive)
  107. * *category* is a class (a subclass of :exc:`Warning`) of which the warning
  108. category must be a subclass in order to match
  109. * *module* is a string containing a regular expression that the module name must
  110. match (the match is compiled to be case-sensitive)
  111. * *lineno* is an integer that the line number where the warning occurred must
  112. match, or ``0`` to match all line numbers
  113. Since the :exc:`Warning` class is derived from the built-in :exc:`Exception`
  114. class, to turn a warning into an error we simply raise ``category(message)``.
  115. The warnings filter is initialized by :option:`-W` options passed to the Python
  116. interpreter command line. The interpreter saves the arguments for all
  117. :option:`-W` options without interpretation in ``sys.warnoptions``; the
  118. :mod:`warnings` module parses these when it is first imported (invalid options
  119. are ignored, after printing a message to ``sys.stderr``).
  120. The warnings that are ignored by default may be enabled by passing :option:`-Wd`
  121. to the interpreter. This enables default handling for all warnings, including
  122. those that are normally ignored by default. This is particular useful for
  123. enabling ImportWarning when debugging problems importing a developed package.
  124. ImportWarning can also be enabled explicitly in Python code using::
  125. warnings.simplefilter('default', ImportWarning)
  126. .. _warning-suppress:
  127. Temporarily Suppressing Warnings
  128. --------------------------------
  129. If you are using code that you know will raise a warning, such as a deprecated
  130. function, but do not want to see the warning, then it is possible to suppress
  131. the warning using the :class:`catch_warnings` context manager::
  132. import warnings
  133. def fxn():
  134. warnings.warn("deprecated", DeprecationWarning)
  135. with warnings.catch_warnings():
  136. warnings.simplefilter("ignore")
  137. fxn()
  138. While within the context manager all warnings will simply be ignored. This
  139. allows you to use known-deprecated code without having to see the warning while
  140. not suppressing the warning for other code that might not be aware of its use
  141. of deprecated code.
  142. .. _warning-testing:
  143. Testing Warnings
  144. ----------------
  145. To test warnings raised by code, use the :class:`catch_warnings` context
  146. manager. With it you can temporarily mutate the warnings filter to facilitate
  147. your testing. For instance, do the following to capture all raised warnings to
  148. check::
  149. import warnings
  150. def fxn():
  151. warnings.warn("deprecated", DeprecationWarning)
  152. with warnings.catch_warnings(record=True) as w:
  153. # Cause all warnings to always be triggered.
  154. warnings.simplefilter("always")
  155. # Trigger a warning.
  156. fxn()
  157. # Verify some things
  158. assert len(w) == 1
  159. assert isinstance(w[-1].category, DeprecationWarning)
  160. assert "deprecated" in str(w[-1].message)
  161. One can also cause all warnings to be exceptions by using ``error`` instead of
  162. ``always``. One thing to be aware of is that if a warning has already been
  163. raised because of a ``once``/``default`` rule, then no matter what filters are
  164. set the warning will not be seen again unless the warnings registry related to
  165. the warning has been cleared.
  166. Once the context manager exits, the warnings filter is restored to its state
  167. when the context was entered. This prevents tests from changing the warnings
  168. filter in unexpected ways between tests and leading to indeterminate test
  169. results. The :func:`showwarning` function in the module is also restored to
  170. its original value.
  171. When testing multiple operations that raise the same kind of warning, it
  172. is important to test them in a manner that confirms each operation is raising
  173. a new warning (e.g. set warnings to be raised as exceptions and check the
  174. operations raise exceptions, check that the length of the warning list
  175. continues to increase after each operation, or else delete the previous
  176. entries from the warnings list before each new operation).
  177. .. _warning-functions:
  178. Available Functions
  179. -------------------
  180. .. function:: warn(message[, category[, stacklevel]])
  181. Issue a warning, or maybe ignore it or raise an exception. The *category*
  182. argument, if given, must be a warning category class (see above); it defaults to
  183. :exc:`UserWarning`. Alternatively *message* can be a :exc:`Warning` instance,
  184. in which case *category* will be ignored and ``message.__class__`` will be used.
  185. In this case the message text will be ``str(message)``. This function raises an
  186. exception if the particular warning issued is changed into an error by the
  187. warnings filter see above. The *stacklevel* argument can be used by wrapper
  188. functions written in Python, like this::
  189. def deprecation(message):
  190. warnings.warn(message, DeprecationWarning, stacklevel=2)
  191. This makes the warning refer to :func:`deprecation`'s caller, rather than to the
  192. source of :func:`deprecation` itself (since the latter would defeat the purpose
  193. of the warning message).
  194. .. function:: warn_explicit(message, category, filename, lineno[, module[, registry[, module_globals]]])
  195. This is a low-level interface to the functionality of :func:`warn`, passing in
  196. explicitly the message, category, filename and line number, and optionally the
  197. module name and the registry (which should be the ``__warningregistry__``
  198. dictionary of the module). The module name defaults to the filename with
  199. ``.py`` stripped; if no registry is passed, the warning is never suppressed.
  200. *message* must be a string and *category* a subclass of :exc:`Warning` or
  201. *message* may be a :exc:`Warning` instance, in which case *category* will be
  202. ignored.
  203. *module_globals*, if supplied, should be the global namespace in use by the code
  204. for which the warning is issued. (This argument is used to support displaying
  205. source for modules found in zipfiles or other non-filesystem import
  206. sources).
  207. .. versionchanged:: 2.5
  208. Added the *module_globals* parameter.
  209. .. function:: warnpy3k(message[, category[, stacklevel]])
  210. Issue a warning related to Python 3.x deprecation. Warnings are only shown
  211. when Python is started with the -3 option. Like :func:`warn` *message* must
  212. be a string and *category* a subclass of :exc:`Warning`. :func:`warnpy3k`
  213. is using :exc:`DeprecationWarning` as default warning class.
  214. .. function:: showwarning(message, category, filename, lineno[, file[, line]])
  215. Write a warning to a file. The default implementation calls
  216. ``formatwarning(message, category, filename, lineno, line)`` and writes the
  217. resulting string to *file*, which defaults to ``sys.stderr``. You may replace
  218. this function with an alternative implementation by assigning to
  219. ``warnings.showwarning``.
  220. *line* is a line of source code to be included in the warning
  221. message; if *line* is not supplied, :func:`showwarning` will
  222. try to read the line specified by *filename* and *lineno*.
  223. .. versionchanged:: 2.6
  224. Added the *line* argument. Implementations that lack the new argument
  225. will trigger a :exc:`DeprecationWarning`.
  226. .. function:: formatwarning(message, category, filename, lineno[, line])
  227. Format a warning the standard way. This returns a string which may contain
  228. embedded newlines and ends in a newline. *line* is
  229. a line of source code to be included in the warning message; if *line* is not supplied,
  230. :func:`formatwarning` will try to read the line specified by *filename* and *lineno*.
  231. .. versionchanged:: 2.6
  232. Added the *line* argument.
  233. .. function:: filterwarnings(action[, message[, category[, module[, lineno[, append]]]]])
  234. Insert an entry into the list of warnings filters. The entry is inserted at the
  235. front by default; if *append* is true, it is inserted at the end. This checks
  236. the types of the arguments, compiles the message and module regular expressions,
  237. and inserts them as a tuple in the list of warnings filters. Entries closer to
  238. the front of the list override entries later in the list, if both match a
  239. particular warning. Omitted arguments default to a value that matches
  240. everything.
  241. .. function:: simplefilter(action[, category[, lineno[, append]]])
  242. Insert a simple entry into the list of warnings filters. The meaning of the
  243. function parameters is as for :func:`filterwarnings`, but regular expressions
  244. are not needed as the filter inserted always matches any message in any module
  245. as long as the category and line number match.
  246. .. function:: resetwarnings()
  247. Reset the warnings filter. This discards the effect of all previous calls to
  248. :func:`filterwarnings`, including that of the :option:`-W` command line options
  249. and calls to :func:`simplefilter`.
  250. Available Context Managers
  251. --------------------------
  252. .. class:: catch_warnings([\*, record=False, module=None])
  253. A context manager that copies and, upon exit, restores the warnings filter
  254. and the :func:`showwarning` function.
  255. If the *record* argument is :const:`False` (the default) the context manager
  256. returns :class:`None` on entry. If *record* is :const:`True`, a list is
  257. returned that is progressively populated with objects as seen by a custom
  258. :func:`showwarning` function (which also suppresses output to ``sys.stdout``).
  259. Each object in the list has attributes with the same names as the arguments to
  260. :func:`showwarning`.
  261. The *module* argument takes a module that will be used instead of the
  262. module returned when you import :mod:`warnings` whose filter will be
  263. protected. This argument exists primarily for testing the :mod:`warnings`
  264. module itself.
  265. .. note::
  266. In Python 3.0, the arguments to the constructor for
  267. :class:`catch_warnings` are keyword-only arguments.
  268. .. versionadded:: 2.6