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