Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | |
| 2 | :mod:`warnings` --- Warning control |
| 3 | =================================== |
| 4 | |
| 5 | .. index:: single: warnings |
| 6 | |
| 7 | .. module:: warnings |
| 8 | :synopsis: Issue warning messages and control their disposition. |
| 9 | |
| 10 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 11 | Warning messages are typically issued in situations where it is useful to alert |
| 12 | the user of some condition in a program, where that condition (normally) doesn't |
| 13 | warrant raising an exception and terminating the program. For example, one |
| 14 | might want to issue a warning when a program uses an obsolete module. |
| 15 | |
| 16 | Python programmers issue warnings by calling the :func:`warn` function defined |
| 17 | in this module. (C programmers use :cfunc:`PyErr_WarnEx`; see |
| 18 | :ref:`exceptionhandling` for details). |
| 19 | |
| 20 | Warning messages are normally written to ``sys.stderr``, but their disposition |
| 21 | can be changed flexibly, from ignoring all warnings to turning them into |
| 22 | exceptions. The disposition of warnings can vary based on the warning category |
| 23 | (see below), the text of the warning message, and the source location where it |
| 24 | is issued. Repetitions of a particular warning for the same source location are |
| 25 | typically suppressed. |
| 26 | |
| 27 | There are two stages in warning control: first, each time a warning is issued, a |
| 28 | determination is made whether a message should be issued or not; next, if a |
| 29 | message is to be issued, it is formatted and printed using a user-settable hook. |
| 30 | |
| 31 | The determination whether to issue a warning message is controlled by the |
| 32 | warning filter, which is a sequence of matching rules and actions. Rules can be |
| 33 | added to the filter by calling :func:`filterwarnings` and reset to its default |
| 34 | state by calling :func:`resetwarnings`. |
| 35 | |
| 36 | The printing of warning messages is done by calling :func:`showwarning`, which |
| 37 | may be overridden; the default implementation of this function formats the |
| 38 | message by calling :func:`formatwarning`, which is also available for use by |
| 39 | custom implementations. |
| 40 | |
| 41 | |
| 42 | .. _warning-categories: |
| 43 | |
| 44 | Warning Categories |
| 45 | ------------------ |
| 46 | |
| 47 | There are a number of built-in exceptions that represent warning categories. |
| 48 | This categorization is useful to be able to filter out groups of warnings. The |
| 49 | following warnings category classes are currently defined: |
| 50 | |
| 51 | +----------------------------------+-----------------------------------------------+ |
| 52 | | Class | Description | |
| 53 | +==================================+===============================================+ |
| 54 | | :exc:`Warning` | This is the base class of all warning | |
| 55 | | | category classes. It is a subclass of | |
| 56 | | | :exc:`Exception`. | |
| 57 | +----------------------------------+-----------------------------------------------+ |
| 58 | | :exc:`UserWarning` | The default category for :func:`warn`. | |
| 59 | +----------------------------------+-----------------------------------------------+ |
| 60 | | :exc:`DeprecationWarning` | Base category for warnings about deprecated | |
| 61 | | | features. | |
| 62 | +----------------------------------+-----------------------------------------------+ |
| 63 | | :exc:`SyntaxWarning` | Base category for warnings about dubious | |
| 64 | | | syntactic features. | |
| 65 | +----------------------------------+-----------------------------------------------+ |
| 66 | | :exc:`RuntimeWarning` | Base category for warnings about dubious | |
| 67 | | | runtime features. | |
| 68 | +----------------------------------+-----------------------------------------------+ |
| 69 | | :exc:`FutureWarning` | Base category for warnings about constructs | |
| 70 | | | that will change semantically in the future. | |
| 71 | +----------------------------------+-----------------------------------------------+ |
| 72 | | :exc:`PendingDeprecationWarning` | Base category for warnings about features | |
| 73 | | | that will be deprecated in the future | |
| 74 | | | (ignored by default). | |
| 75 | +----------------------------------+-----------------------------------------------+ |
| 76 | | :exc:`ImportWarning` | Base category for warnings triggered during | |
| 77 | | | the process of importing a module (ignored by | |
| 78 | | | default). | |
| 79 | +----------------------------------+-----------------------------------------------+ |
| 80 | | :exc:`UnicodeWarning` | Base category for warnings related to | |
| 81 | | | Unicode. | |
| 82 | +----------------------------------+-----------------------------------------------+ |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 83 | | :exc:`BytesWarning` | Base category for warnings related to | |
| 84 | | | :class:`bytes` and :class:`buffer`. | |
| 85 | +----------------------------------+-----------------------------------------------+ |
| 86 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 87 | |
| 88 | While these are technically built-in exceptions, they are documented here, |
| 89 | because conceptually they belong to the warnings mechanism. |
| 90 | |
| 91 | User code can define additional warning categories by subclassing one of the |
| 92 | standard warning categories. A warning category must always be a subclass of |
| 93 | the :exc:`Warning` class. |
| 94 | |
| 95 | |
| 96 | .. _warning-filter: |
| 97 | |
| 98 | The Warnings Filter |
| 99 | ------------------- |
| 100 | |
| 101 | The warnings filter controls whether warnings are ignored, displayed, or turned |
| 102 | into errors (raising an exception). |
| 103 | |
| 104 | Conceptually, the warnings filter maintains an ordered list of filter |
| 105 | specifications; any specific warning is matched against each filter |
| 106 | specification in the list in turn until a match is found; the match determines |
| 107 | the disposition of the match. Each entry is a tuple of the form (*action*, |
| 108 | *message*, *category*, *module*, *lineno*), where: |
| 109 | |
| 110 | * *action* is one of the following strings: |
| 111 | |
| 112 | +---------------+----------------------------------------------+ |
| 113 | | Value | Disposition | |
| 114 | +===============+==============================================+ |
| 115 | | ``"error"`` | turn matching warnings into exceptions | |
| 116 | +---------------+----------------------------------------------+ |
| 117 | | ``"ignore"`` | never print matching warnings | |
| 118 | +---------------+----------------------------------------------+ |
| 119 | | ``"always"`` | always print matching warnings | |
| 120 | +---------------+----------------------------------------------+ |
| 121 | | ``"default"`` | print the first occurrence of matching | |
| 122 | | | warnings for each location where the warning | |
| 123 | | | is issued | |
| 124 | +---------------+----------------------------------------------+ |
| 125 | | ``"module"`` | print the first occurrence of matching | |
| 126 | | | warnings for each module where the warning | |
| 127 | | | is issued | |
| 128 | +---------------+----------------------------------------------+ |
| 129 | | ``"once"`` | print only the first occurrence of matching | |
| 130 | | | warnings, regardless of location | |
| 131 | +---------------+----------------------------------------------+ |
| 132 | |
| 133 | * *message* is a string containing a regular expression that the warning message |
| 134 | must match (the match is compiled to always be case-insensitive) |
| 135 | |
| 136 | * *category* is a class (a subclass of :exc:`Warning`) of which the warning |
| 137 | category must be a subclass in order to match |
| 138 | |
| 139 | * *module* is a string containing a regular expression that the module name must |
| 140 | match (the match is compiled to be case-sensitive) |
| 141 | |
| 142 | * *lineno* is an integer that the line number where the warning occurred must |
| 143 | match, or ``0`` to match all line numbers |
| 144 | |
| 145 | Since the :exc:`Warning` class is derived from the built-in :exc:`Exception` |
| 146 | class, to turn a warning into an error we simply raise ``category(message)``. |
| 147 | |
| 148 | The warnings filter is initialized by :option:`-W` options passed to the Python |
| 149 | interpreter command line. The interpreter saves the arguments for all |
| 150 | :option:`-W` options without interpretation in ``sys.warnoptions``; the |
| 151 | :mod:`warnings` module parses these when it is first imported (invalid options |
| 152 | are ignored, after printing a message to ``sys.stderr``). |
| 153 | |
| 154 | The warnings that are ignored by default may be enabled by passing :option:`-Wd` |
| 155 | to the interpreter. This enables default handling for all warnings, including |
| 156 | those that are normally ignored by default. This is particular useful for |
| 157 | enabling ImportWarning when debugging problems importing a developed package. |
| 158 | ImportWarning can also be enabled explicitly in Python code using:: |
| 159 | |
| 160 | warnings.simplefilter('default', ImportWarning) |
| 161 | |
| 162 | |
| 163 | .. _warning-functions: |
| 164 | |
| 165 | Available Functions |
| 166 | ------------------- |
| 167 | |
| 168 | |
| 169 | .. function:: warn(message[, category[, stacklevel]]) |
| 170 | |
| 171 | Issue a warning, or maybe ignore it or raise an exception. The *category* |
| 172 | argument, if given, must be a warning category class (see above); it defaults to |
| 173 | :exc:`UserWarning`. Alternatively *message* can be a :exc:`Warning` instance, |
| 174 | in which case *category* will be ignored and ``message.__class__`` will be used. |
| 175 | In this case the message text will be ``str(message)``. This function raises an |
| 176 | exception if the particular warning issued is changed into an error by the |
| 177 | warnings filter see above. The *stacklevel* argument can be used by wrapper |
| 178 | functions written in Python, like this:: |
| 179 | |
| 180 | def deprecation(message): |
| 181 | warnings.warn(message, DeprecationWarning, stacklevel=2) |
| 182 | |
| 183 | This makes the warning refer to :func:`deprecation`'s caller, rather than to the |
| 184 | source of :func:`deprecation` itself (since the latter would defeat the purpose |
| 185 | of the warning message). |
| 186 | |
| 187 | |
| 188 | .. function:: warn_explicit(message, category, filename, lineno[, module[, registry[, module_globals]]]) |
| 189 | |
| 190 | This is a low-level interface to the functionality of :func:`warn`, passing in |
| 191 | explicitly the message, category, filename and line number, and optionally the |
| 192 | module name and the registry (which should be the ``__warningregistry__`` |
| 193 | dictionary of the module). The module name defaults to the filename with |
| 194 | ``.py`` stripped; if no registry is passed, the warning is never suppressed. |
| 195 | *message* must be a string and *category* a subclass of :exc:`Warning` or |
| 196 | *message* may be a :exc:`Warning` instance, in which case *category* will be |
| 197 | ignored. |
| 198 | |
| 199 | *module_globals*, if supplied, should be the global namespace in use by the code |
| 200 | for which the warning is issued. (This argument is used to support displaying |
Christian Heimes | 3279b5d | 2007-12-09 15:58:13 +0000 | [diff] [blame] | 201 | source for modules found in zipfiles or other non-filesystem import |
| 202 | sources). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 203 | |
| 204 | |
| 205 | .. function:: showwarning(message, category, filename, lineno[, file]) |
| 206 | |
| 207 | Write a warning to a file. The default implementation calls |
| 208 | ``formatwarning(message, category, filename, lineno)`` and writes the resulting |
| 209 | string to *file*, which defaults to ``sys.stderr``. You may replace this |
| 210 | function with an alternative implementation by assigning to |
| 211 | ``warnings.showwarning``. |
| 212 | |
| 213 | |
| 214 | .. function:: formatwarning(message, category, filename, lineno) |
| 215 | |
| 216 | Format a warning the standard way. This returns a string which may contain |
| 217 | embedded newlines and ends in a newline. |
| 218 | |
| 219 | |
| 220 | .. function:: filterwarnings(action[, message[, category[, module[, lineno[, append]]]]]) |
| 221 | |
| 222 | Insert an entry into the list of warnings filters. The entry is inserted at the |
| 223 | front by default; if *append* is true, it is inserted at the end. This checks |
| 224 | the types of the arguments, compiles the message and module regular expressions, |
| 225 | and inserts them as a tuple in the list of warnings filters. Entries closer to |
| 226 | the front of the list override entries later in the list, if both match a |
| 227 | particular warning. Omitted arguments default to a value that matches |
| 228 | everything. |
| 229 | |
| 230 | |
| 231 | .. function:: simplefilter(action[, category[, lineno[, append]]]) |
| 232 | |
| 233 | Insert a simple entry into the list of warnings filters. The meaning of the |
| 234 | function parameters is as for :func:`filterwarnings`, but regular expressions |
| 235 | are not needed as the filter inserted always matches any message in any module |
| 236 | as long as the category and line number match. |
| 237 | |
| 238 | |
| 239 | .. function:: resetwarnings() |
| 240 | |
| 241 | Reset the warnings filter. This discards the effect of all previous calls to |
| 242 | :func:`filterwarnings`, including that of the :option:`-W` command line options |
| 243 | and calls to :func:`simplefilter`. |
| 244 | |