Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 1 | """Python part of the warnings subsystem.""" |
| 2 | |
Mark Hammond | a43fd0c | 2003-02-19 00:33:33 +0000 | [diff] [blame] | 3 | # Note: function level imports should *not* be used |
| 4 | # in this module as it may cause import lock deadlock. |
| 5 | # See bug 683658. |
Mark Hammond | a43fd0c | 2003-02-19 00:33:33 +0000 | [diff] [blame] | 6 | import linecache |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 7 | import sys |
| 8 | import types |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 9 | |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 10 | __all__ = ["warn", "showwarning", "formatwarning", "filterwarnings", |
| 11 | "resetwarnings"] |
| 12 | |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 13 | |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 14 | def showwarning(message, category, filename, lineno, file=None, line=None): |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 15 | """Hook to write a warning to a file; replace if you like.""" |
| 16 | if file is None: |
| 17 | file = sys.stderr |
Mark Hammond | 51a0ae3 | 2002-09-11 13:22:35 +0000 | [diff] [blame] | 18 | try: |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 19 | file.write(formatwarning(message, category, filename, lineno, line)) |
Mark Hammond | 51a0ae3 | 2002-09-11 13:22:35 +0000 | [diff] [blame] | 20 | except IOError: |
| 21 | pass # the file (probably stderr) is invalid - this warning gets lost. |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 22 | |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 23 | def formatwarning(message, category, filename, lineno, line=None): |
Guido van Rossum | 9464a7d | 2001-01-14 14:08:40 +0000 | [diff] [blame] | 24 | """Function to format a warning the standard way.""" |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 25 | s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message) |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 26 | line = linecache.getline(filename, lineno) if line is None else line |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 27 | if line: |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 28 | line = line.strip() |
| 29 | s += " %s\n" % line |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 30 | return s |
| 31 | |
Guido van Rossum | 9464a7d | 2001-01-14 14:08:40 +0000 | [diff] [blame] | 32 | def filterwarnings(action, message="", category=Warning, module="", lineno=0, |
| 33 | append=0): |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 34 | """Insert an entry into the list of warnings filters (at the front). |
| 35 | |
| 36 | Use assertions to check that all arguments have the right type.""" |
Skip Montanaro | d8f2120 | 2003-05-14 17:33:53 +0000 | [diff] [blame] | 37 | import re |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 38 | assert action in ("error", "ignore", "always", "default", "module", |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 39 | "once"), "invalid action: %r" % (action,) |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 40 | assert isinstance(message, str), "message must be a string" |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 41 | assert isinstance(category, type), "category must be a class" |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 42 | assert issubclass(category, Warning), "category must be a Warning subclass" |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 43 | assert isinstance(module, str), "module must be a string" |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 44 | assert isinstance(lineno, int) and lineno >= 0, \ |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 45 | "lineno must be an int >= 0" |
Guido van Rossum | 9464a7d | 2001-01-14 14:08:40 +0000 | [diff] [blame] | 46 | item = (action, re.compile(message, re.I), category, |
| 47 | re.compile(module), lineno) |
| 48 | if append: |
| 49 | filters.append(item) |
| 50 | else: |
| 51 | filters.insert(0, item) |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 52 | |
Jeremy Hylton | 8501466 | 2003-07-11 15:37:59 +0000 | [diff] [blame] | 53 | def simplefilter(action, category=Warning, lineno=0, append=0): |
| 54 | """Insert a simple entry into the list of warnings filters (at the front). |
| 55 | |
| 56 | A simple filter matches all modules and messages. |
| 57 | """ |
| 58 | assert action in ("error", "ignore", "always", "default", "module", |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 59 | "once"), "invalid action: %r" % (action,) |
Jeremy Hylton | 8501466 | 2003-07-11 15:37:59 +0000 | [diff] [blame] | 60 | assert isinstance(lineno, int) and lineno >= 0, \ |
| 61 | "lineno must be an int >= 0" |
| 62 | item = (action, None, category, None, lineno) |
| 63 | if append: |
| 64 | filters.append(item) |
| 65 | else: |
| 66 | filters.insert(0, item) |
| 67 | |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 68 | def resetwarnings(): |
Tim Peters | d0cc4f0 | 2002-04-16 01:51:25 +0000 | [diff] [blame] | 69 | """Clear the list of warning filters, so that no filters are active.""" |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 70 | filters[:] = [] |
| 71 | |
| 72 | class _OptionError(Exception): |
| 73 | """Exception used by option processing helpers.""" |
| 74 | pass |
| 75 | |
| 76 | # Helper to process -W options passed via sys.warnoptions |
| 77 | def _processoptions(args): |
| 78 | for arg in args: |
| 79 | try: |
| 80 | _setoption(arg) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 81 | except _OptionError as msg: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 82 | print("Invalid -W option ignored:", msg, file=sys.stderr) |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 83 | |
| 84 | # Helper for _processoptions() |
| 85 | def _setoption(arg): |
Skip Montanaro | d8f2120 | 2003-05-14 17:33:53 +0000 | [diff] [blame] | 86 | import re |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 87 | parts = arg.split(':') |
| 88 | if len(parts) > 5: |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 89 | raise _OptionError("too many fields (max 5): %r" % (arg,)) |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 90 | while len(parts) < 5: |
| 91 | parts.append('') |
| 92 | action, message, category, module, lineno = [s.strip() |
| 93 | for s in parts] |
| 94 | action = _getaction(action) |
| 95 | message = re.escape(message) |
| 96 | category = _getcategory(category) |
| 97 | module = re.escape(module) |
| 98 | if module: |
| 99 | module = module + '$' |
| 100 | if lineno: |
| 101 | try: |
| 102 | lineno = int(lineno) |
| 103 | if lineno < 0: |
| 104 | raise ValueError |
| 105 | except (ValueError, OverflowError): |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 106 | raise _OptionError("invalid lineno %r" % (lineno,)) |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 107 | else: |
| 108 | lineno = 0 |
| 109 | filterwarnings(action, message, category, module, lineno) |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 110 | |
| 111 | # Helper for _setoption() |
| 112 | def _getaction(action): |
| 113 | if not action: |
| 114 | return "default" |
| 115 | if action == "all": return "always" # Alias |
Raymond Hettinger | dbecd93 | 2005-02-06 06:57:08 +0000 | [diff] [blame] | 116 | for a in ('default', 'always', 'ignore', 'module', 'once', 'error'): |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 117 | if a.startswith(action): |
| 118 | return a |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 119 | raise _OptionError("invalid action: %r" % (action,)) |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 120 | |
| 121 | # Helper for _setoption() |
| 122 | def _getcategory(category): |
Skip Montanaro | d8f2120 | 2003-05-14 17:33:53 +0000 | [diff] [blame] | 123 | import re |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 124 | if not category: |
| 125 | return Warning |
| 126 | if re.match("^[a-zA-Z0-9_]+$", category): |
| 127 | try: |
| 128 | cat = eval(category) |
Guido van Rossum | d1db30b | 2000-12-19 03:04:50 +0000 | [diff] [blame] | 129 | except NameError: |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 130 | raise _OptionError("unknown warning category: %r" % (category,)) |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 131 | else: |
| 132 | i = category.rfind(".") |
| 133 | module = category[:i] |
| 134 | klass = category[i+1:] |
Guido van Rossum | d1db30b | 2000-12-19 03:04:50 +0000 | [diff] [blame] | 135 | try: |
| 136 | m = __import__(module, None, None, [klass]) |
| 137 | except ImportError: |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 138 | raise _OptionError("invalid module name: %r" % (module,)) |
Guido van Rossum | d1db30b | 2000-12-19 03:04:50 +0000 | [diff] [blame] | 139 | try: |
| 140 | cat = getattr(m, klass) |
| 141 | except AttributeError: |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 142 | raise _OptionError("unknown warning category: %r" % (category,)) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 143 | if not issubclass(cat, Warning): |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 144 | raise _OptionError("invalid warning category: %r" % (category,)) |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 145 | return cat |
| 146 | |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 147 | |
| 148 | # Code typically replaced by _warnings |
| 149 | def warn(message, category=None, stacklevel=1): |
| 150 | """Issue a warning, or maybe ignore it or raise an exception.""" |
| 151 | # Check if message is already a Warning object |
| 152 | if isinstance(message, Warning): |
| 153 | category = message.__class__ |
| 154 | # Check category argument |
| 155 | if category is None: |
| 156 | category = UserWarning |
| 157 | assert issubclass(category, Warning) |
| 158 | # Get context information |
| 159 | try: |
| 160 | caller = sys._getframe(stacklevel) |
| 161 | except ValueError: |
| 162 | globals = sys.__dict__ |
| 163 | lineno = 1 |
| 164 | else: |
| 165 | globals = caller.f_globals |
| 166 | lineno = caller.f_lineno |
| 167 | if '__name__' in globals: |
| 168 | module = globals['__name__'] |
| 169 | else: |
| 170 | module = "<string>" |
| 171 | filename = globals.get('__file__') |
| 172 | if filename: |
| 173 | fnl = filename.lower() |
| 174 | if fnl.endswith((".pyc", ".pyo")): |
| 175 | filename = filename[:-1] |
| 176 | else: |
| 177 | if module == "__main__": |
| 178 | try: |
| 179 | filename = sys.argv[0] |
| 180 | except AttributeError: |
| 181 | # embedded interpreters don't have sys.argv, see bug #839151 |
| 182 | filename = '__main__' |
| 183 | if not filename: |
| 184 | filename = module |
| 185 | registry = globals.setdefault("__warningregistry__", {}) |
| 186 | warn_explicit(message, category, filename, lineno, module, registry, |
| 187 | globals) |
| 188 | |
| 189 | def warn_explicit(message, category, filename, lineno, |
| 190 | module=None, registry=None, module_globals=None): |
Brett Cannon | db73491 | 2008-06-27 00:52:15 +0000 | [diff] [blame] | 191 | lineno = int(lineno) |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 192 | if module is None: |
| 193 | module = filename or "<unknown>" |
| 194 | if module[-3:].lower() == ".py": |
| 195 | module = module[:-3] # XXX What about leading pathname? |
| 196 | if registry is None: |
| 197 | registry = {} |
| 198 | if isinstance(message, Warning): |
| 199 | text = str(message) |
| 200 | category = message.__class__ |
| 201 | else: |
| 202 | text = message |
| 203 | message = category(message) |
| 204 | key = (text, category, lineno) |
| 205 | # Quick test for common case |
| 206 | if registry.get(key): |
| 207 | return |
| 208 | # Search the filters |
| 209 | for item in filters: |
| 210 | action, msg, cat, mod, ln = item |
| 211 | if ((msg is None or msg.match(text)) and |
| 212 | issubclass(category, cat) and |
| 213 | (mod is None or mod.match(module)) and |
| 214 | (ln == 0 or lineno == ln)): |
| 215 | break |
| 216 | else: |
| 217 | action = defaultaction |
| 218 | # Early exit actions |
| 219 | if action == "ignore": |
| 220 | registry[key] = 1 |
| 221 | return |
| 222 | |
| 223 | # Prime the linecache for formatting, in case the |
| 224 | # "file" is actually in a zipfile or something. |
| 225 | linecache.getlines(filename, module_globals) |
| 226 | |
| 227 | if action == "error": |
| 228 | raise message |
| 229 | # Other actions |
| 230 | if action == "once": |
| 231 | registry[key] = 1 |
| 232 | oncekey = (text, category) |
| 233 | if onceregistry.get(oncekey): |
| 234 | return |
| 235 | onceregistry[oncekey] = 1 |
| 236 | elif action == "always": |
| 237 | pass |
| 238 | elif action == "module": |
| 239 | registry[key] = 1 |
| 240 | altkey = (text, category, 0) |
| 241 | if registry.get(altkey): |
| 242 | return |
| 243 | registry[altkey] = 1 |
| 244 | elif action == "default": |
| 245 | registry[key] = 1 |
| 246 | else: |
| 247 | # Unrecognized actions are errors |
| 248 | raise RuntimeError( |
| 249 | "Unrecognized action (%r) in warnings.filters:\n %s" % |
| 250 | (action, item)) |
Christian Heimes | 8dc226f | 2008-05-06 23:45:46 +0000 | [diff] [blame] | 251 | if not hasattr(showwarning, "__call__"): |
| 252 | raise TypeError("warnings.showwarning() must be set to a " |
| 253 | "function or method") |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 254 | # Print message and context |
| 255 | showwarning(message, category, filename, lineno) |
| 256 | |
| 257 | |
| 258 | # filters contains a sequence of filter 5-tuples |
| 259 | # The components of the 5-tuple are: |
| 260 | # - an action: error, ignore, always, default, module, or once |
| 261 | # - a compiled regex that must match the warning message |
| 262 | # - a class representing the warning category |
| 263 | # - a compiled regex that must match the module that is being warned |
| 264 | # - a line number for the line being warning, or 0 to mean any line |
| 265 | # If either if the compiled regexs are None, match anything. |
| 266 | _warnings_defaults = False |
| 267 | try: |
| 268 | from _warnings import (filters, default_action, once_registry, |
| 269 | warn, warn_explicit) |
| 270 | defaultaction = default_action |
| 271 | onceregistry = once_registry |
| 272 | _warnings_defaults = True |
| 273 | except ImportError: |
| 274 | filters = [] |
| 275 | defaultaction = "default" |
| 276 | onceregistry = {} |
| 277 | |
| 278 | |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 279 | # Module initialization |
Tim Peters | 6602520 | 2004-03-21 17:06:20 +0000 | [diff] [blame] | 280 | _processoptions(sys.warnoptions) |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 281 | if not _warnings_defaults: |
| 282 | simplefilter("ignore", category=PendingDeprecationWarning, append=1) |
| 283 | simplefilter("ignore", category=ImportWarning, append=1) |
| 284 | bytes_warning = sys.flags.bytes_warning |
| 285 | if bytes_warning > 1: |
| 286 | bytes_action = "error" |
| 287 | elif bytes_warning: |
| 288 | bytes_action = "default" |
| 289 | else: |
| 290 | bytes_action = "ignore" |
| 291 | simplefilter(bytes_action, category=BytesWarning, append=1) |
| 292 | del _warnings_defaults |