PageRenderTime 60ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Doc/PythonDocs/library/warnings.rst

https://github.com/jdhardy/ironpython
ReStructuredText | 403 lines | 301 code | 102 blank | 0 comment | 0 complexity | 5f2b3b38cc43445dde7e010873b43f5c 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 (ignored by default). |
  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. .. versionchanged:: 2.7
  75. :exc:`DeprecationWarning` is ignored by default.
  76. .. _warning-filter:
  77. The Warnings Filter
  78. -------------------
  79. The warnings filter controls whether warnings are ignored, displayed, or turned
  80. into errors (raising an exception).
  81. Conceptually, the warnings filter maintains an ordered list of filter
  82. specifications; any specific warning is matched against each filter
  83. specification in the list in turn until a match is found; the match determines
  84. the disposition of the match. Each entry is a tuple of the form (*action*,
  85. *message*, *category*, *module*, *lineno*), where:
  86. * *action* is one of the following strings:
  87. +---------------+----------------------------------------------+
  88. | Value | Disposition |
  89. +===============+==============================================+
  90. | ``"error"`` | turn matching warnings into exceptions |
  91. +---------------+----------------------------------------------+
  92. | ``"ignore"`` | never print matching warnings |
  93. +---------------+----------------------------------------------+
  94. | ``"always"`` | always print matching warnings |
  95. +---------------+----------------------------------------------+
  96. | ``"default"`` | print the first occurrence of matching |
  97. | | warnings for each location where the warning |
  98. | | is issued |
  99. +---------------+----------------------------------------------+
  100. | ``"module"`` | print the first occurrence of matching |
  101. | | warnings for each module where the warning |
  102. | | is issued |
  103. +---------------+----------------------------------------------+
  104. | ``"once"`` | print only the first occurrence of matching |
  105. | | warnings, regardless of location |
  106. +---------------+----------------------------------------------+
  107. * *message* is a string containing a regular expression that the warning message
  108. must match (the match is compiled to always be case-insensitive).
  109. * *category* is a class (a subclass of :exc:`Warning`) of which the warning
  110. category must be a subclass in order to match.
  111. * *module* is a string containing a regular expression that the module name must
  112. match (the match is compiled to be case-sensitive).
  113. * *lineno* is an integer that the line number where the warning occurred must
  114. match, or ``0`` to match all line numbers.
  115. Since the :exc:`Warning` class is derived from the built-in :exc:`Exception`
  116. class, to turn a warning into an error we simply raise ``category(message)``.
  117. The warnings filter is initialized by :option:`-W` options passed to the Python
  118. interpreter command line. The interpreter saves the arguments for all
  119. :option:`-W` options without interpretation in ``sys.warnoptions``; the
  120. :mod:`warnings` module parses these when it is first imported (invalid options
  121. are ignored, after printing a message to ``sys.stderr``).
  122. .. _warning-suppress:
  123. Temporarily Suppressing Warnings
  124. --------------------------------
  125. If you are using code that you know will raise a warning, such as a deprecated
  126. function, but do not want to see the warning, then it is possible to suppress
  127. the warning using the :class:`catch_warnings` context manager::
  128. import warnings
  129. def fxn():
  130. warnings.warn("deprecated", DeprecationWarning)
  131. with warnings.catch_warnings():
  132. warnings.simplefilter("ignore")
  133. fxn()
  134. While within the context manager all warnings will simply be ignored. This
  135. allows you to use known-deprecated code without having to see the warning while
  136. not suppressing the warning for other code that might not be aware of its use
  137. of deprecated code. Note: this can only be guaranteed in a single-threaded
  138. application. If two or more threads use the :class:`catch_warnings` context
  139. manager at the same time, the behavior is undefined.
  140. .. _warning-testing:
  141. Testing Warnings
  142. ----------------
  143. To test warnings raised by code, use the :class:`catch_warnings` context
  144. manager. With it you can temporarily mutate the warnings filter to facilitate
  145. your testing. For instance, do the following to capture all raised warnings to
  146. check::
  147. import warnings
  148. def fxn():
  149. warnings.warn("deprecated", DeprecationWarning)
  150. with warnings.catch_warnings(record=True) as w:
  151. # Cause all warnings to always be triggered.
  152. warnings.simplefilter("always")
  153. # Trigger a warning.
  154. fxn()
  155. # Verify some things
  156. assert len(w) == 1
  157. assert issubclass(w[-1].category, DeprecationWarning)
  158. assert "deprecated" in str(w[-1].message)
  159. One can also cause all warnings to be exceptions by using ``error`` instead of
  160. ``always``. One thing to be aware of is that if a warning has already been
  161. raised because of a ``once``/``default`` rule, then no matter what filters are
  162. set the warning will not be seen again unless the warnings registry related to
  163. the warning has been cleared.
  164. Once the context manager exits, the warnings filter is restored to its state
  165. when the context was entered. This prevents tests from changing the warnings
  166. filter in unexpected ways between tests and leading to indeterminate test
  167. results. The :func:`showwarning` function in the module is also restored to
  168. its original value. Note: this can only be guaranteed in a single-threaded
  169. application. If two or more threads use the :class:`catch_warnings` context
  170. manager at the same time, the behavior is undefined.
  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. Updating Code For New Versions of Python
  178. ----------------------------------------
  179. Warnings that are only of interest to the developer are ignored by default. As
  180. such you should make sure to test your code with typically ignored warnings
  181. made visible. You can do this from the command-line by passing :option:`-Wd`
  182. to the interpreter (this is shorthand for :option:`-W default`). This enables
  183. default handling for all warnings, including those that are ignored by default.
  184. To change what action is taken for encountered warnings you simply change what
  185. argument is passed to :option:`-W`, e.g. :option:`-W error`. See the
  186. :option:`-W` flag for more details on what is possible.
  187. To programmatically do the same as :option:`-Wd`, use::
  188. warnings.simplefilter('default')
  189. Make sure to execute this code as soon as possible. This prevents the
  190. registering of what warnings have been raised from unexpectedly influencing how
  191. future warnings are treated.
  192. Having certain warnings ignored by default is done to prevent a user from
  193. seeing warnings that are only of interest to the developer. As you do not
  194. necessarily have control over what interpreter a user uses to run their code,
  195. it is possible that a new version of Python will be released between your
  196. release cycles. The new interpreter release could trigger new warnings in your
  197. code that were not there in an older interpreter, e.g.
  198. :exc:`DeprecationWarning` for a module that you are using. While you as a
  199. developer want to be notified that your code is using a deprecated module, to a
  200. user this information is essentially noise and provides no benefit to them.
  201. .. _warning-functions:
  202. Available Functions
  203. -------------------
  204. .. function:: warn(message[, category[, stacklevel]])
  205. Issue a warning, or maybe ignore it or raise an exception. The *category*
  206. argument, if given, must be a warning category class (see above); it defaults to
  207. :exc:`UserWarning`. Alternatively *message* can be a :exc:`Warning` instance,
  208. in which case *category* will be ignored and ``message.__class__`` will be used.
  209. In this case the message text will be ``str(message)``. This function raises an
  210. exception if the particular warning issued is changed into an error by the
  211. warnings filter see above. The *stacklevel* argument can be used by wrapper
  212. functions written in Python, like this::
  213. def deprecation(message):
  214. warnings.warn(message, DeprecationWarning, stacklevel=2)
  215. This makes the warning refer to :func:`deprecation`'s caller, rather than to the
  216. source of :func:`deprecation` itself (since the latter would defeat the purpose
  217. of the warning message).
  218. .. function:: warn_explicit(message, category, filename, lineno[, module[, registry[, module_globals]]])
  219. This is a low-level interface to the functionality of :func:`warn`, passing in
  220. explicitly the message, category, filename and line number, and optionally the
  221. module name and the registry (which should be the ``__warningregistry__``
  222. dictionary of the module). The module name defaults to the filename with
  223. ``.py`` stripped; if no registry is passed, the warning is never suppressed.
  224. *message* must be a string and *category* a subclass of :exc:`Warning` or
  225. *message* may be a :exc:`Warning` instance, in which case *category* will be
  226. ignored.
  227. *module_globals*, if supplied, should be the global namespace in use by the code
  228. for which the warning is issued. (This argument is used to support displaying
  229. source for modules found in zipfiles or other non-filesystem import
  230. sources).
  231. .. versionchanged:: 2.5
  232. Added the *module_globals* parameter.
  233. .. function:: warnpy3k(message[, category[, stacklevel]])
  234. Issue a warning related to Python 3.x deprecation. Warnings are only shown
  235. when Python is started with the -3 option. Like :func:`warn` *message* must
  236. be a string and *category* a subclass of :exc:`Warning`. :func:`warnpy3k`
  237. is using :exc:`DeprecationWarning` as default warning class.
  238. .. versionadded:: 2.6
  239. .. function:: showwarning(message, category, filename, lineno[, file[, line]])
  240. Write a warning to a file. The default implementation calls
  241. ``formatwarning(message, category, filename, lineno, line)`` and writes the
  242. resulting string to *file*, which defaults to ``sys.stderr``. You may replace
  243. this function with an alternative implementation by assigning to
  244. ``warnings.showwarning``.
  245. *line* is a line of source code to be included in the warning
  246. message; if *line* is not supplied, :func:`showwarning` will
  247. try to read the line specified by *filename* and *lineno*.
  248. .. versionchanged:: 2.7
  249. The *line* argument is required to be supported.
  250. .. function:: formatwarning(message, category, filename, lineno[, line])
  251. Format a warning the standard way. This returns a string which may contain
  252. embedded newlines and ends in a newline. *line* is a line of source code to
  253. be included in the warning message; if *line* is not supplied,
  254. :func:`formatwarning` will try to read the line specified by *filename* and
  255. *lineno*.
  256. .. versionchanged:: 2.6
  257. Added the *line* argument.
  258. .. function:: filterwarnings(action[, message[, category[, module[, lineno[, append]]]]])
  259. Insert an entry into the list of :ref:`warnings filter specifications
  260. <warning-filter>`. The entry is inserted at the front by default; if
  261. *append* is true, it is inserted at the end. This checks the types of the
  262. arguments, compiles the *message* and *module* regular expressions, and
  263. inserts them as a tuple in the list of warnings filters. Entries closer to
  264. the front of the list override entries later in the list, if both match a
  265. particular warning. Omitted arguments default to a value that matches
  266. everything.
  267. .. function:: simplefilter(action[, category[, lineno[, append]]])
  268. Insert a simple entry into the list of :ref:`warnings filter specifications
  269. <warning-filter>`. The meaning of the function parameters is as for
  270. :func:`filterwarnings`, but regular expressions are not needed as the filter
  271. inserted always matches any message in any module as long as the category and
  272. line number match.
  273. .. function:: resetwarnings()
  274. Reset the warnings filter. This discards the effect of all previous calls to
  275. :func:`filterwarnings`, including that of the :option:`-W` command line options
  276. and calls to :func:`simplefilter`.
  277. Available Context Managers
  278. --------------------------
  279. .. class:: catch_warnings([\*, record=False, module=None])
  280. A context manager that copies and, upon exit, restores the warnings filter
  281. and the :func:`showwarning` function.
  282. If the *record* argument is :const:`False` (the default) the context manager
  283. returns :class:`None` on entry. If *record* is :const:`True`, a list is
  284. returned that is progressively populated with objects as seen by a custom
  285. :func:`showwarning` function (which also suppresses output to ``sys.stdout``).
  286. Each object in the list has attributes with the same names as the arguments to
  287. :func:`showwarning`.
  288. The *module* argument takes a module that will be used instead of the
  289. module returned when you import :mod:`warnings` whose filter will be
  290. protected. This argument exists primarily for testing the :mod:`warnings`
  291. module itself.
  292. .. note::
  293. The :class:`catch_warnings` manager works by replacing and
  294. then later restoring the module's
  295. :func:`showwarning` function and internal list of filter
  296. specifications. This means the context manager is modifying
  297. global state and therefore is not thread-safe.
  298. .. note::
  299. In Python 3.0, the arguments to the constructor for
  300. :class:`catch_warnings` are keyword-only arguments.
  301. .. versionadded:: 2.6