Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 1 | """Python part of the warnings subsystem.""" |
| 2 | |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 3 | import sys |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 4 | |
Victor Stinner | 914cde8 | 2016-03-19 01:03:51 +0100 | [diff] [blame] | 5 | |
Brett Cannon | 14ad531 | 2014-08-22 10:44:47 -0400 | [diff] [blame] | 6 | __all__ = ["warn", "warn_explicit", "showwarning", |
| 7 | "formatwarning", "filterwarnings", "simplefilter", |
Brett Cannon | 1cd0247 | 2008-09-09 01:52:27 +0000 | [diff] [blame] | 8 | "resetwarnings", "catch_warnings"] |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 9 | |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 10 | def showwarning(message, category, filename, lineno, file=None, line=None): |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 11 | """Hook to write a warning to a file; replace if you like.""" |
Victor Stinner | 1231a46 | 2016-03-19 00:47:17 +0100 | [diff] [blame] | 12 | msg = WarningMessage(message, category, filename, lineno, file, line) |
Victor Stinner | eedf13f | 2016-03-19 02:11:56 +0100 | [diff] [blame] | 13 | _showwarnmsg_impl(msg) |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 14 | |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 15 | def formatwarning(message, category, filename, lineno, line=None): |
Guido van Rossum | 9464a7d | 2001-01-14 14:08:40 +0000 | [diff] [blame] | 16 | """Function to format a warning the standard way.""" |
Victor Stinner | 1231a46 | 2016-03-19 00:47:17 +0100 | [diff] [blame] | 17 | msg = WarningMessage(message, category, filename, lineno, None, line) |
Victor Stinner | eedf13f | 2016-03-19 02:11:56 +0100 | [diff] [blame] | 18 | return _formatwarnmsg_impl(msg) |
Victor Stinner | 1231a46 | 2016-03-19 00:47:17 +0100 | [diff] [blame] | 19 | |
Victor Stinner | eedf13f | 2016-03-19 02:11:56 +0100 | [diff] [blame] | 20 | def _showwarnmsg_impl(msg): |
Victor Stinner | 1231a46 | 2016-03-19 00:47:17 +0100 | [diff] [blame] | 21 | file = msg.file |
| 22 | if file is None: |
| 23 | file = sys.stderr |
| 24 | if file is None: |
| 25 | # sys.stderr is None when run with pythonw.exe: |
| 26 | # warnings get lost |
| 27 | return |
| 28 | text = _formatwarnmsg(msg) |
| 29 | try: |
| 30 | file.write(text) |
| 31 | except OSError: |
| 32 | # the file (probably stderr) is invalid - this warning gets lost. |
| 33 | pass |
| 34 | |
Victor Stinner | eedf13f | 2016-03-19 02:11:56 +0100 | [diff] [blame] | 35 | def _formatwarnmsg_impl(msg): |
Antoine Pitrou | 7cb11fa | 2013-10-24 22:23:42 +0200 | [diff] [blame] | 36 | import linecache |
Victor Stinner | 1231a46 | 2016-03-19 00:47:17 +0100 | [diff] [blame] | 37 | s = ("%s:%s: %s: %s\n" |
| 38 | % (msg.filename, msg.lineno, msg.category.__name__, |
| 39 | msg.message)) |
| 40 | if msg.line is None: |
| 41 | line = linecache.getline(msg.filename, msg.lineno) |
| 42 | else: |
| 43 | line = msg.line |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 44 | if line: |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 45 | line = line.strip() |
| 46 | s += " %s\n" % line |
Victor Stinner | 914cde8 | 2016-03-19 01:03:51 +0100 | [diff] [blame] | 47 | if msg.source is not None: |
| 48 | import tracemalloc |
| 49 | tb = tracemalloc.get_object_traceback(msg.source) |
| 50 | if tb is not None: |
| 51 | s += 'Object allocated at (most recent call first):\n' |
| 52 | for frame in tb: |
| 53 | s += (' File "%s", lineno %s\n' |
| 54 | % (frame.filename, frame.lineno)) |
| 55 | line = linecache.getline(frame.filename, frame.lineno) |
| 56 | if line: |
| 57 | line = line.strip() |
| 58 | s += ' %s\n' % line |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 59 | return s |
| 60 | |
Victor Stinner | eedf13f | 2016-03-19 02:11:56 +0100 | [diff] [blame] | 61 | # Keep a reference to check if the function was replaced |
| 62 | _showwarning = showwarning |
| 63 | |
| 64 | def _showwarnmsg(msg): |
| 65 | """Hook to write a warning to a file; replace if you like.""" |
| 66 | showwarning = globals().get('showwarning', _showwarning) |
| 67 | if showwarning is not _showwarning: |
| 68 | # warnings.showwarning() was replaced |
| 69 | if not callable(showwarning): |
| 70 | raise TypeError("warnings.showwarning() must be set to a " |
| 71 | "function or method") |
| 72 | |
| 73 | showwarning(msg.message, msg.category, msg.filename, msg.lineno, |
| 74 | msg.file, msg.line) |
| 75 | return |
| 76 | _showwarnmsg_impl(msg) |
| 77 | |
| 78 | # Keep a reference to check if the function was replaced |
| 79 | _formatwarning = formatwarning |
| 80 | |
| 81 | def _formatwarnmsg(msg): |
| 82 | """Function to format a warning the standard way.""" |
| 83 | formatwarning = globals().get('formatwarning', _formatwarning) |
| 84 | if formatwarning is not _formatwarning: |
| 85 | # warnings.formatwarning() was replaced |
| 86 | return formatwarning(msg.message, msg.category, |
| 87 | msg.filename, msg.lineno, line=msg.line) |
| 88 | return _formatwarnmsg_impl(msg) |
| 89 | |
Guido van Rossum | 9464a7d | 2001-01-14 14:08:40 +0000 | [diff] [blame] | 90 | def filterwarnings(action, message="", category=Warning, module="", lineno=0, |
Georg Brandl | fe99105 | 2009-09-16 15:54:04 +0000 | [diff] [blame] | 91 | append=False): |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 92 | """Insert an entry into the list of warnings filters (at the front). |
| 93 | |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 94 | 'action' -- one of "error", "ignore", "always", "default", "module", |
| 95 | or "once" |
| 96 | 'message' -- a regex that the warning message must match |
| 97 | 'category' -- a class that the warning must be a subclass of |
| 98 | 'module' -- a regex that the module name must match |
| 99 | 'lineno' -- an integer line number, 0 matches all warnings |
| 100 | 'append' -- if true, append to the list of filters |
| 101 | """ |
Skip Montanaro | d8f2120 | 2003-05-14 17:33:53 +0000 | [diff] [blame] | 102 | import re |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 103 | assert action in ("error", "ignore", "always", "default", "module", |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 104 | "once"), "invalid action: %r" % (action,) |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 105 | assert isinstance(message, str), "message must be a string" |
Guido van Rossum | 1325790 | 2007-06-07 23:15:56 +0000 | [diff] [blame] | 106 | assert isinstance(category, type), "category must be a class" |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 107 | assert issubclass(category, Warning), "category must be a Warning subclass" |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 108 | assert isinstance(module, str), "module must be a string" |
Walter Dörwald | 65230a2 | 2002-06-03 15:58:32 +0000 | [diff] [blame] | 109 | assert isinstance(lineno, int) and lineno >= 0, \ |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 110 | "lineno must be an int >= 0" |
Guido van Rossum | 9464a7d | 2001-01-14 14:08:40 +0000 | [diff] [blame] | 111 | item = (action, re.compile(message, re.I), category, |
| 112 | re.compile(module), lineno) |
| 113 | if append: |
| 114 | filters.append(item) |
| 115 | else: |
| 116 | filters.insert(0, item) |
Antoine Pitrou | cb0a006 | 2014-09-18 02:40:46 +0200 | [diff] [blame] | 117 | _filters_mutated() |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 118 | |
Georg Brandl | fe99105 | 2009-09-16 15:54:04 +0000 | [diff] [blame] | 119 | def simplefilter(action, category=Warning, lineno=0, append=False): |
Jeremy Hylton | 8501466 | 2003-07-11 15:37:59 +0000 | [diff] [blame] | 120 | """Insert a simple entry into the list of warnings filters (at the front). |
| 121 | |
| 122 | A simple filter matches all modules and messages. |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 123 | 'action' -- one of "error", "ignore", "always", "default", "module", |
| 124 | or "once" |
| 125 | 'category' -- a class that the warning must be a subclass of |
| 126 | 'lineno' -- an integer line number, 0 matches all warnings |
| 127 | 'append' -- if true, append to the list of filters |
Jeremy Hylton | 8501466 | 2003-07-11 15:37:59 +0000 | [diff] [blame] | 128 | """ |
| 129 | assert action in ("error", "ignore", "always", "default", "module", |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 130 | "once"), "invalid action: %r" % (action,) |
Jeremy Hylton | 8501466 | 2003-07-11 15:37:59 +0000 | [diff] [blame] | 131 | assert isinstance(lineno, int) and lineno >= 0, \ |
| 132 | "lineno must be an int >= 0" |
| 133 | item = (action, None, category, None, lineno) |
| 134 | if append: |
| 135 | filters.append(item) |
| 136 | else: |
| 137 | filters.insert(0, item) |
Antoine Pitrou | cb0a006 | 2014-09-18 02:40:46 +0200 | [diff] [blame] | 138 | _filters_mutated() |
Jeremy Hylton | 8501466 | 2003-07-11 15:37:59 +0000 | [diff] [blame] | 139 | |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 140 | def resetwarnings(): |
Tim Peters | d0cc4f0 | 2002-04-16 01:51:25 +0000 | [diff] [blame] | 141 | """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] | 142 | filters[:] = [] |
Antoine Pitrou | cb0a006 | 2014-09-18 02:40:46 +0200 | [diff] [blame] | 143 | _filters_mutated() |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 144 | |
| 145 | class _OptionError(Exception): |
| 146 | """Exception used by option processing helpers.""" |
| 147 | pass |
| 148 | |
| 149 | # Helper to process -W options passed via sys.warnoptions |
| 150 | def _processoptions(args): |
| 151 | for arg in args: |
| 152 | try: |
| 153 | _setoption(arg) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 154 | except _OptionError as msg: |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 155 | print("Invalid -W option ignored:", msg, file=sys.stderr) |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 156 | |
| 157 | # Helper for _processoptions() |
| 158 | def _setoption(arg): |
Skip Montanaro | d8f2120 | 2003-05-14 17:33:53 +0000 | [diff] [blame] | 159 | import re |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 160 | parts = arg.split(':') |
| 161 | if len(parts) > 5: |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 162 | raise _OptionError("too many fields (max 5): %r" % (arg,)) |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 163 | while len(parts) < 5: |
| 164 | parts.append('') |
| 165 | action, message, category, module, lineno = [s.strip() |
| 166 | for s in parts] |
| 167 | action = _getaction(action) |
| 168 | message = re.escape(message) |
| 169 | category = _getcategory(category) |
| 170 | module = re.escape(module) |
| 171 | if module: |
| 172 | module = module + '$' |
| 173 | if lineno: |
| 174 | try: |
| 175 | lineno = int(lineno) |
| 176 | if lineno < 0: |
| 177 | raise ValueError |
| 178 | except (ValueError, OverflowError): |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 179 | raise _OptionError("invalid lineno %r" % (lineno,)) |
Tim Peters | e119006 | 2001-01-15 03:34:38 +0000 | [diff] [blame] | 180 | else: |
| 181 | lineno = 0 |
| 182 | filterwarnings(action, message, category, module, lineno) |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 183 | |
| 184 | # Helper for _setoption() |
| 185 | def _getaction(action): |
| 186 | if not action: |
| 187 | return "default" |
| 188 | if action == "all": return "always" # Alias |
Raymond Hettinger | dbecd93 | 2005-02-06 06:57:08 +0000 | [diff] [blame] | 189 | for a in ('default', 'always', 'ignore', 'module', 'once', 'error'): |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 190 | if a.startswith(action): |
| 191 | return a |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 192 | raise _OptionError("invalid action: %r" % (action,)) |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 193 | |
| 194 | # Helper for _setoption() |
| 195 | def _getcategory(category): |
Skip Montanaro | d8f2120 | 2003-05-14 17:33:53 +0000 | [diff] [blame] | 196 | import re |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 197 | if not category: |
| 198 | return Warning |
| 199 | if re.match("^[a-zA-Z0-9_]+$", category): |
| 200 | try: |
| 201 | cat = eval(category) |
Guido van Rossum | d1db30b | 2000-12-19 03:04:50 +0000 | [diff] [blame] | 202 | except NameError: |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 203 | raise _OptionError("unknown warning category: %r" % (category,)) |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 204 | else: |
| 205 | i = category.rfind(".") |
| 206 | module = category[:i] |
| 207 | klass = category[i+1:] |
Guido van Rossum | d1db30b | 2000-12-19 03:04:50 +0000 | [diff] [blame] | 208 | try: |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 209 | m = __import__(module, None, None, [klass]) |
| 210 | except ImportError: |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 211 | raise _OptionError("invalid module name: %r" % (module,)) |
Guido van Rossum | d1db30b | 2000-12-19 03:04:50 +0000 | [diff] [blame] | 212 | try: |
| 213 | cat = getattr(m, klass) |
| 214 | except AttributeError: |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 215 | raise _OptionError("unknown warning category: %r" % (category,)) |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 216 | if not issubclass(cat, Warning): |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 217 | raise _OptionError("invalid warning category: %r" % (category,)) |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 218 | return cat |
| 219 | |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 220 | |
Larry Hastings | 714e493 | 2015-09-06 00:39:37 -0700 | [diff] [blame] | 221 | def _is_internal_frame(frame): |
| 222 | """Signal whether the frame is an internal CPython implementation detail.""" |
| 223 | filename = frame.f_code.co_filename |
| 224 | return 'importlib' in filename and '_bootstrap' in filename |
| 225 | |
| 226 | |
| 227 | def _next_external_frame(frame): |
| 228 | """Find the next frame that doesn't involve CPython internals.""" |
| 229 | frame = frame.f_back |
| 230 | while frame is not None and _is_internal_frame(frame): |
| 231 | frame = frame.f_back |
| 232 | return frame |
| 233 | |
| 234 | |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 235 | # Code typically replaced by _warnings |
Victor Stinner | e19558a | 2016-03-23 00:28:08 +0100 | [diff] [blame^] | 236 | def warn(message, category=None, stacklevel=1, source=None): |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 237 | """Issue a warning, or maybe ignore it or raise an exception.""" |
| 238 | # Check if message is already a Warning object |
| 239 | if isinstance(message, Warning): |
| 240 | category = message.__class__ |
| 241 | # Check category argument |
| 242 | if category is None: |
| 243 | category = UserWarning |
Berker Peksag | d8089e0 | 2014-07-11 19:50:25 +0300 | [diff] [blame] | 244 | if not (isinstance(category, type) and issubclass(category, Warning)): |
| 245 | raise TypeError("category must be a Warning subclass, " |
| 246 | "not '{:s}'".format(type(category).__name__)) |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 247 | # Get context information |
| 248 | try: |
Larry Hastings | 714e493 | 2015-09-06 00:39:37 -0700 | [diff] [blame] | 249 | if stacklevel <= 1 or _is_internal_frame(sys._getframe(1)): |
| 250 | # If frame is too small to care or if the warning originated in |
| 251 | # internal code, then do not try to hide any frames. |
| 252 | frame = sys._getframe(stacklevel) |
| 253 | else: |
| 254 | frame = sys._getframe(1) |
| 255 | # Look for one frame less since the above line starts us off. |
| 256 | for x in range(stacklevel-1): |
| 257 | frame = _next_external_frame(frame) |
| 258 | if frame is None: |
| 259 | raise ValueError |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 260 | except ValueError: |
| 261 | globals = sys.__dict__ |
| 262 | lineno = 1 |
| 263 | else: |
Larry Hastings | 714e493 | 2015-09-06 00:39:37 -0700 | [diff] [blame] | 264 | globals = frame.f_globals |
| 265 | lineno = frame.f_lineno |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 266 | if '__name__' in globals: |
| 267 | module = globals['__name__'] |
| 268 | else: |
| 269 | module = "<string>" |
| 270 | filename = globals.get('__file__') |
| 271 | if filename: |
| 272 | fnl = filename.lower() |
Brett Cannon | f299abd | 2015-04-13 14:21:02 -0400 | [diff] [blame] | 273 | if fnl.endswith(".pyc"): |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 274 | filename = filename[:-1] |
| 275 | else: |
| 276 | if module == "__main__": |
| 277 | try: |
| 278 | filename = sys.argv[0] |
| 279 | except AttributeError: |
| 280 | # embedded interpreters don't have sys.argv, see bug #839151 |
| 281 | filename = '__main__' |
| 282 | if not filename: |
| 283 | filename = module |
| 284 | registry = globals.setdefault("__warningregistry__", {}) |
| 285 | warn_explicit(message, category, filename, lineno, module, registry, |
Victor Stinner | e19558a | 2016-03-23 00:28:08 +0100 | [diff] [blame^] | 286 | globals, source) |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 287 | |
| 288 | def warn_explicit(message, category, filename, lineno, |
Victor Stinner | 914cde8 | 2016-03-19 01:03:51 +0100 | [diff] [blame] | 289 | module=None, registry=None, module_globals=None, |
| 290 | source=None): |
Brett Cannon | db73491 | 2008-06-27 00:52:15 +0000 | [diff] [blame] | 291 | lineno = int(lineno) |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 292 | if module is None: |
| 293 | module = filename or "<unknown>" |
| 294 | if module[-3:].lower() == ".py": |
| 295 | module = module[:-3] # XXX What about leading pathname? |
| 296 | if registry is None: |
| 297 | registry = {} |
Antoine Pitrou | cb0a006 | 2014-09-18 02:40:46 +0200 | [diff] [blame] | 298 | if registry.get('version', 0) != _filters_version: |
| 299 | registry.clear() |
| 300 | registry['version'] = _filters_version |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 301 | if isinstance(message, Warning): |
| 302 | text = str(message) |
| 303 | category = message.__class__ |
| 304 | else: |
| 305 | text = message |
| 306 | message = category(message) |
| 307 | key = (text, category, lineno) |
| 308 | # Quick test for common case |
| 309 | if registry.get(key): |
| 310 | return |
| 311 | # Search the filters |
| 312 | for item in filters: |
| 313 | action, msg, cat, mod, ln = item |
| 314 | if ((msg is None or msg.match(text)) and |
| 315 | issubclass(category, cat) and |
| 316 | (mod is None or mod.match(module)) and |
| 317 | (ln == 0 or lineno == ln)): |
| 318 | break |
| 319 | else: |
| 320 | action = defaultaction |
| 321 | # Early exit actions |
| 322 | if action == "ignore": |
| 323 | registry[key] = 1 |
| 324 | return |
| 325 | |
| 326 | # Prime the linecache for formatting, in case the |
| 327 | # "file" is actually in a zipfile or something. |
Antoine Pitrou | 7cb11fa | 2013-10-24 22:23:42 +0200 | [diff] [blame] | 328 | import linecache |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 329 | linecache.getlines(filename, module_globals) |
| 330 | |
| 331 | if action == "error": |
| 332 | raise message |
| 333 | # Other actions |
| 334 | if action == "once": |
| 335 | registry[key] = 1 |
| 336 | oncekey = (text, category) |
| 337 | if onceregistry.get(oncekey): |
| 338 | return |
| 339 | onceregistry[oncekey] = 1 |
| 340 | elif action == "always": |
| 341 | pass |
| 342 | elif action == "module": |
| 343 | registry[key] = 1 |
| 344 | altkey = (text, category, 0) |
| 345 | if registry.get(altkey): |
| 346 | return |
| 347 | registry[altkey] = 1 |
| 348 | elif action == "default": |
| 349 | registry[key] = 1 |
| 350 | else: |
| 351 | # Unrecognized actions are errors |
| 352 | raise RuntimeError( |
| 353 | "Unrecognized action (%r) in warnings.filters:\n %s" % |
| 354 | (action, item)) |
| 355 | # Print message and context |
Victor Stinner | 914cde8 | 2016-03-19 01:03:51 +0100 | [diff] [blame] | 356 | msg = WarningMessage(message, category, filename, lineno, source) |
Victor Stinner | 1231a46 | 2016-03-19 00:47:17 +0100 | [diff] [blame] | 357 | _showwarnmsg(msg) |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 358 | |
| 359 | |
Brett Cannon | ec92e18 | 2008-09-02 02:46:59 +0000 | [diff] [blame] | 360 | class WarningMessage(object): |
| 361 | |
Brett Cannon | ec92e18 | 2008-09-02 02:46:59 +0000 | [diff] [blame] | 362 | _WARNING_DETAILS = ("message", "category", "filename", "lineno", "file", |
Victor Stinner | 914cde8 | 2016-03-19 01:03:51 +0100 | [diff] [blame] | 363 | "line", "source") |
Brett Cannon | ec92e18 | 2008-09-02 02:46:59 +0000 | [diff] [blame] | 364 | |
| 365 | def __init__(self, message, category, filename, lineno, file=None, |
Victor Stinner | 914cde8 | 2016-03-19 01:03:51 +0100 | [diff] [blame] | 366 | line=None, source=None): |
Brett Cannon | ec92e18 | 2008-09-02 02:46:59 +0000 | [diff] [blame] | 367 | local_values = locals() |
| 368 | for attr in self._WARNING_DETAILS: |
| 369 | setattr(self, attr, local_values[attr]) |
| 370 | self._category_name = category.__name__ if category else None |
| 371 | |
| 372 | def __str__(self): |
| 373 | return ("{message : %r, category : %r, filename : %r, lineno : %s, " |
| 374 | "line : %r}" % (self.message, self._category_name, |
| 375 | self.filename, self.lineno, self.line)) |
| 376 | |
| 377 | |
Brett Cannon | ec92e18 | 2008-09-02 02:46:59 +0000 | [diff] [blame] | 378 | class catch_warnings(object): |
| 379 | |
Brett Cannon | 1cd0247 | 2008-09-09 01:52:27 +0000 | [diff] [blame] | 380 | """A context manager that copies and restores the warnings filter upon |
| 381 | exiting the context. |
Brett Cannon | ec92e18 | 2008-09-02 02:46:59 +0000 | [diff] [blame] | 382 | |
Brett Cannon | 1cd0247 | 2008-09-09 01:52:27 +0000 | [diff] [blame] | 383 | The 'record' argument specifies whether warnings should be captured by a |
| 384 | custom implementation of warnings.showwarning() and be appended to a list |
| 385 | returned by the context manager. Otherwise None is returned by the context |
| 386 | manager. The objects appended to the list are arguments whose attributes |
| 387 | mirror the arguments to showwarning(). |
| 388 | |
| 389 | The 'module' argument is to specify an alternative module to the module |
| 390 | named 'warnings' and imported under that name. This argument is only useful |
| 391 | when testing the warnings module itself. |
Brett Cannon | ec92e18 | 2008-09-02 02:46:59 +0000 | [diff] [blame] | 392 | |
| 393 | """ |
| 394 | |
| 395 | def __init__(self, *, record=False, module=None): |
| 396 | """Specify whether to record warnings and if an alternative module |
| 397 | should be used other than sys.modules['warnings']. |
| 398 | |
| 399 | For compatibility with Python 3.0, please consider all arguments to be |
| 400 | keyword-only. |
| 401 | |
| 402 | """ |
Brett Cannon | 1cd0247 | 2008-09-09 01:52:27 +0000 | [diff] [blame] | 403 | self._record = record |
Brett Cannon | ec92e18 | 2008-09-02 02:46:59 +0000 | [diff] [blame] | 404 | self._module = sys.modules['warnings'] if module is None else module |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 405 | self._entered = False |
| 406 | |
| 407 | def __repr__(self): |
| 408 | args = [] |
| 409 | if self._record: |
| 410 | args.append("record=True") |
| 411 | if self._module is not sys.modules['warnings']: |
| 412 | args.append("module=%r" % self._module) |
| 413 | name = type(self).__name__ |
| 414 | return "%s(%s)" % (name, ", ".join(args)) |
Brett Cannon | ec92e18 | 2008-09-02 02:46:59 +0000 | [diff] [blame] | 415 | |
| 416 | def __enter__(self): |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 417 | if self._entered: |
| 418 | raise RuntimeError("Cannot enter %r twice" % self) |
| 419 | self._entered = True |
Brett Cannon | ec92e18 | 2008-09-02 02:46:59 +0000 | [diff] [blame] | 420 | self._filters = self._module.filters |
| 421 | self._module.filters = self._filters[:] |
Antoine Pitrou | cb0a006 | 2014-09-18 02:40:46 +0200 | [diff] [blame] | 422 | self._module._filters_mutated() |
Brett Cannon | ec92e18 | 2008-09-02 02:46:59 +0000 | [diff] [blame] | 423 | self._showwarning = self._module.showwarning |
Victor Stinner | 1231a46 | 2016-03-19 00:47:17 +0100 | [diff] [blame] | 424 | self._showwarnmsg = self._module._showwarnmsg |
Brett Cannon | 1cd0247 | 2008-09-09 01:52:27 +0000 | [diff] [blame] | 425 | if self._record: |
| 426 | log = [] |
Victor Stinner | 1231a46 | 2016-03-19 00:47:17 +0100 | [diff] [blame] | 427 | def showarnmsg(msg): |
| 428 | log.append(msg) |
| 429 | self._module._showwarnmsg = showarnmsg |
Brett Cannon | 1cd0247 | 2008-09-09 01:52:27 +0000 | [diff] [blame] | 430 | return log |
| 431 | else: |
| 432 | return None |
Brett Cannon | ec92e18 | 2008-09-02 02:46:59 +0000 | [diff] [blame] | 433 | |
| 434 | def __exit__(self, *exc_info): |
Benjamin Peterson | fcf5d63 | 2008-10-16 23:24:44 +0000 | [diff] [blame] | 435 | if not self._entered: |
| 436 | raise RuntimeError("Cannot exit %r without entering first" % self) |
Brett Cannon | ec92e18 | 2008-09-02 02:46:59 +0000 | [diff] [blame] | 437 | self._module.filters = self._filters |
Antoine Pitrou | cb0a006 | 2014-09-18 02:40:46 +0200 | [diff] [blame] | 438 | self._module._filters_mutated() |
Brett Cannon | ec92e18 | 2008-09-02 02:46:59 +0000 | [diff] [blame] | 439 | self._module.showwarning = self._showwarning |
Victor Stinner | 1231a46 | 2016-03-19 00:47:17 +0100 | [diff] [blame] | 440 | self._module._showwarnmsg = self._showwarnmsg |
Brett Cannon | ec92e18 | 2008-09-02 02:46:59 +0000 | [diff] [blame] | 441 | |
| 442 | |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 443 | # filters contains a sequence of filter 5-tuples |
| 444 | # The components of the 5-tuple are: |
| 445 | # - an action: error, ignore, always, default, module, or once |
| 446 | # - a compiled regex that must match the warning message |
| 447 | # - a class representing the warning category |
| 448 | # - a compiled regex that must match the module that is being warned |
| 449 | # - a line number for the line being warning, or 0 to mean any line |
| 450 | # If either if the compiled regexs are None, match anything. |
| 451 | _warnings_defaults = False |
| 452 | try: |
Brett Cannon | ef0e6c3 | 2010-09-04 18:24:04 +0000 | [diff] [blame] | 453 | from _warnings import (filters, _defaultaction, _onceregistry, |
Antoine Pitrou | cb0a006 | 2014-09-18 02:40:46 +0200 | [diff] [blame] | 454 | warn, warn_explicit, _filters_mutated) |
Brett Cannon | ef0e6c3 | 2010-09-04 18:24:04 +0000 | [diff] [blame] | 455 | defaultaction = _defaultaction |
| 456 | onceregistry = _onceregistry |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 457 | _warnings_defaults = True |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 458 | except ImportError: |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 459 | filters = [] |
| 460 | defaultaction = "default" |
| 461 | onceregistry = {} |
| 462 | |
Antoine Pitrou | cb0a006 | 2014-09-18 02:40:46 +0200 | [diff] [blame] | 463 | _filters_version = 1 |
| 464 | |
| 465 | def _filters_mutated(): |
| 466 | global _filters_version |
| 467 | _filters_version += 1 |
| 468 | |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 469 | |
Guido van Rossum | 2a862c6 | 2000-12-15 21:59:53 +0000 | [diff] [blame] | 470 | # Module initialization |
Tim Peters | 6602520 | 2004-03-21 17:06:20 +0000 | [diff] [blame] | 471 | _processoptions(sys.warnoptions) |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 472 | if not _warnings_defaults: |
Benjamin Peterson | 7ab4b8d | 2010-06-28 00:01:59 +0000 | [diff] [blame] | 473 | silence = [ImportWarning, PendingDeprecationWarning] |
| 474 | silence.append(DeprecationWarning) |
| 475 | for cls in silence: |
| 476 | simplefilter("ignore", category=cls) |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 477 | bytes_warning = sys.flags.bytes_warning |
| 478 | if bytes_warning > 1: |
| 479 | bytes_action = "error" |
| 480 | elif bytes_warning: |
| 481 | bytes_action = "default" |
| 482 | else: |
| 483 | bytes_action = "ignore" |
| 484 | simplefilter(bytes_action, category=BytesWarning, append=1) |
Georg Brandl | 08be72d | 2010-10-24 15:11:22 +0000 | [diff] [blame] | 485 | # resource usage warnings are enabled by default in pydebug mode |
| 486 | if hasattr(sys, 'gettotalrefcount'): |
| 487 | resource_action = "always" |
| 488 | else: |
| 489 | resource_action = "ignore" |
| 490 | simplefilter(resource_action, category=ResourceWarning, append=1) |
| 491 | |
Christian Heimes | 33fe809 | 2008-04-13 13:53:33 +0000 | [diff] [blame] | 492 | del _warnings_defaults |