blob: 1ece5149f4be57dd14e3588aebdc95fc63be86b6 [file] [log] [blame]
Guido van Rossum2a862c62000-12-15 21:59:53 +00001"""Python part of the warnings subsystem."""
2
Christian Heimes33fe8092008-04-13 13:53:33 +00003import sys
Guido van Rossum2a862c62000-12-15 21:59:53 +00004
Victor Stinner914cde82016-03-19 01:03:51 +01005
Brett Cannon14ad5312014-08-22 10:44:47 -04006__all__ = ["warn", "warn_explicit", "showwarning",
7 "formatwarning", "filterwarnings", "simplefilter",
Brett Cannon1cd02472008-09-09 01:52:27 +00008 "resetwarnings", "catch_warnings"]
Skip Montanaro40fc1602001-03-01 04:27:19 +00009
Christian Heimes33fe8092008-04-13 13:53:33 +000010def showwarning(message, category, filename, lineno, file=None, line=None):
Guido van Rossum2a862c62000-12-15 21:59:53 +000011 """Hook to write a warning to a file; replace if you like."""
Victor Stinner1231a462016-03-19 00:47:17 +010012 msg = WarningMessage(message, category, filename, lineno, file, line)
Victor Stinnereedf13f2016-03-19 02:11:56 +010013 _showwarnmsg_impl(msg)
Guido van Rossum2a862c62000-12-15 21:59:53 +000014
Christian Heimes33fe8092008-04-13 13:53:33 +000015def formatwarning(message, category, filename, lineno, line=None):
Guido van Rossum9464a7d2001-01-14 14:08:40 +000016 """Function to format a warning the standard way."""
Victor Stinner1231a462016-03-19 00:47:17 +010017 msg = WarningMessage(message, category, filename, lineno, None, line)
Victor Stinnereedf13f2016-03-19 02:11:56 +010018 return _formatwarnmsg_impl(msg)
Victor Stinner1231a462016-03-19 00:47:17 +010019
Victor Stinnereedf13f2016-03-19 02:11:56 +010020def _showwarnmsg_impl(msg):
Victor Stinner1231a462016-03-19 00:47:17 +010021 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 Stinnereedf13f2016-03-19 02:11:56 +010035def _formatwarnmsg_impl(msg):
Victor Stinner1231a462016-03-19 00:47:17 +010036 s = ("%s:%s: %s: %s\n"
37 % (msg.filename, msg.lineno, msg.category.__name__,
38 msg.message))
Victor Stinnere091d322016-03-25 00:33:12 +010039
Victor Stinner1231a462016-03-19 00:47:17 +010040 if msg.line is None:
Victor Stinner27461682016-03-25 00:30:32 +010041 try:
42 import linecache
Victor Stinnere091d322016-03-25 00:33:12 +010043 line = linecache.getline(msg.filename, msg.lineno)
Victor Stinner27461682016-03-25 00:30:32 +010044 except Exception:
45 # When a warning is logged during Python shutdown, linecache
46 # and the improt machinery don't work anymore
47 line = None
Victor Stinnere091d322016-03-25 00:33:12 +010048 linecache = None
Victor Stinner1231a462016-03-19 00:47:17 +010049 else:
50 line = msg.line
Guido van Rossum2a862c62000-12-15 21:59:53 +000051 if line:
Christian Heimes33fe8092008-04-13 13:53:33 +000052 line = line.strip()
53 s += " %s\n" % line
Victor Stinnere091d322016-03-25 00:33:12 +010054
Victor Stinner914cde82016-03-19 01:03:51 +010055 if msg.source is not None:
Victor Stinnere091d322016-03-25 00:33:12 +010056 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 Stinner914cde82016-03-19 01:03:51 +010064 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 Stinnere091d322016-03-25 00:33:12 +010069
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 Stinner914cde82016-03-19 01:03:51 +010077 if line:
78 line = line.strip()
79 s += ' %s\n' % line
Guido van Rossum2a862c62000-12-15 21:59:53 +000080 return s
81
Victor Stinnereedf13f2016-03-19 02:11:56 +010082# Keep a reference to check if the function was replaced
83_showwarning = showwarning
84
85def _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
102def _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 Rossum9464a7d2001-01-14 14:08:40 +0000111def filterwarnings(action, message="", category=Warning, module="", lineno=0,
Georg Brandlfe991052009-09-16 15:54:04 +0000112 append=False):
Guido van Rossum2a862c62000-12-15 21:59:53 +0000113 """Insert an entry into the list of warnings filters (at the front).
114
Georg Brandl495f7b52009-10-27 15:28:25 +0000115 '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 Montanarod8f21202003-05-14 17:33:53 +0000123 import re
Guido van Rossum2a862c62000-12-15 21:59:53 +0000124 assert action in ("error", "ignore", "always", "default", "module",
Walter Dörwald70a6b492004-02-12 17:35:32 +0000125 "once"), "invalid action: %r" % (action,)
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000126 assert isinstance(message, str), "message must be a string"
Guido van Rossum13257902007-06-07 23:15:56 +0000127 assert isinstance(category, type), "category must be a class"
Guido van Rossum2a862c62000-12-15 21:59:53 +0000128 assert issubclass(category, Warning), "category must be a Warning subclass"
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000129 assert isinstance(module, str), "module must be a string"
Walter Dörwald65230a22002-06-03 15:58:32 +0000130 assert isinstance(lineno, int) and lineno >= 0, \
Guido van Rossum2a862c62000-12-15 21:59:53 +0000131 "lineno must be an int >= 0"
Guido van Rossum9464a7d2001-01-14 14:08:40 +0000132 item = (action, re.compile(message, re.I), category,
133 re.compile(module), lineno)
134 if append:
135 filters.append(item)
136 else:
137 filters.insert(0, item)
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200138 _filters_mutated()
Guido van Rossum2a862c62000-12-15 21:59:53 +0000139
Georg Brandlfe991052009-09-16 15:54:04 +0000140def simplefilter(action, category=Warning, lineno=0, append=False):
Jeremy Hylton85014662003-07-11 15:37:59 +0000141 """Insert a simple entry into the list of warnings filters (at the front).
142
143 A simple filter matches all modules and messages.
Georg Brandl495f7b52009-10-27 15:28:25 +0000144 'action' -- one of "error", "ignore", "always", "default", "module",
145 or "once"
146 'category' -- a class that the warning must be a subclass of
147 'lineno' -- an integer line number, 0 matches all warnings
148 'append' -- if true, append to the list of filters
Jeremy Hylton85014662003-07-11 15:37:59 +0000149 """
150 assert action in ("error", "ignore", "always", "default", "module",
Walter Dörwald70a6b492004-02-12 17:35:32 +0000151 "once"), "invalid action: %r" % (action,)
Jeremy Hylton85014662003-07-11 15:37:59 +0000152 assert isinstance(lineno, int) and lineno >= 0, \
153 "lineno must be an int >= 0"
154 item = (action, None, category, None, lineno)
155 if append:
156 filters.append(item)
157 else:
158 filters.insert(0, item)
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200159 _filters_mutated()
Jeremy Hylton85014662003-07-11 15:37:59 +0000160
Guido van Rossum2a862c62000-12-15 21:59:53 +0000161def resetwarnings():
Tim Petersd0cc4f02002-04-16 01:51:25 +0000162 """Clear the list of warning filters, so that no filters are active."""
Guido van Rossum2a862c62000-12-15 21:59:53 +0000163 filters[:] = []
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200164 _filters_mutated()
Guido van Rossum2a862c62000-12-15 21:59:53 +0000165
166class _OptionError(Exception):
167 """Exception used by option processing helpers."""
168 pass
169
170# Helper to process -W options passed via sys.warnoptions
171def _processoptions(args):
172 for arg in args:
173 try:
174 _setoption(arg)
Guido van Rossumb940e112007-01-10 16:19:56 +0000175 except _OptionError as msg:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000176 print("Invalid -W option ignored:", msg, file=sys.stderr)
Guido van Rossum2a862c62000-12-15 21:59:53 +0000177
178# Helper for _processoptions()
179def _setoption(arg):
Skip Montanarod8f21202003-05-14 17:33:53 +0000180 import re
Tim Peterse1190062001-01-15 03:34:38 +0000181 parts = arg.split(':')
182 if len(parts) > 5:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000183 raise _OptionError("too many fields (max 5): %r" % (arg,))
Tim Peterse1190062001-01-15 03:34:38 +0000184 while len(parts) < 5:
185 parts.append('')
186 action, message, category, module, lineno = [s.strip()
187 for s in parts]
188 action = _getaction(action)
189 message = re.escape(message)
190 category = _getcategory(category)
191 module = re.escape(module)
192 if module:
193 module = module + '$'
194 if lineno:
195 try:
196 lineno = int(lineno)
197 if lineno < 0:
198 raise ValueError
199 except (ValueError, OverflowError):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000200 raise _OptionError("invalid lineno %r" % (lineno,))
Tim Peterse1190062001-01-15 03:34:38 +0000201 else:
202 lineno = 0
203 filterwarnings(action, message, category, module, lineno)
Guido van Rossum2a862c62000-12-15 21:59:53 +0000204
205# Helper for _setoption()
206def _getaction(action):
207 if not action:
208 return "default"
209 if action == "all": return "always" # Alias
Raymond Hettingerdbecd932005-02-06 06:57:08 +0000210 for a in ('default', 'always', 'ignore', 'module', 'once', 'error'):
Guido van Rossum2a862c62000-12-15 21:59:53 +0000211 if a.startswith(action):
212 return a
Walter Dörwald70a6b492004-02-12 17:35:32 +0000213 raise _OptionError("invalid action: %r" % (action,))
Guido van Rossum2a862c62000-12-15 21:59:53 +0000214
215# Helper for _setoption()
216def _getcategory(category):
Skip Montanarod8f21202003-05-14 17:33:53 +0000217 import re
Guido van Rossum2a862c62000-12-15 21:59:53 +0000218 if not category:
219 return Warning
220 if re.match("^[a-zA-Z0-9_]+$", category):
221 try:
222 cat = eval(category)
Guido van Rossumd1db30b2000-12-19 03:04:50 +0000223 except NameError:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000224 raise _OptionError("unknown warning category: %r" % (category,))
Guido van Rossum2a862c62000-12-15 21:59:53 +0000225 else:
226 i = category.rfind(".")
227 module = category[:i]
228 klass = category[i+1:]
Guido van Rossumd1db30b2000-12-19 03:04:50 +0000229 try:
Brett Cannoncd171c82013-07-04 17:43:24 -0400230 m = __import__(module, None, None, [klass])
231 except ImportError:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000232 raise _OptionError("invalid module name: %r" % (module,))
Guido van Rossumd1db30b2000-12-19 03:04:50 +0000233 try:
234 cat = getattr(m, klass)
235 except AttributeError:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000236 raise _OptionError("unknown warning category: %r" % (category,))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000237 if not issubclass(cat, Warning):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000238 raise _OptionError("invalid warning category: %r" % (category,))
Guido van Rossum2a862c62000-12-15 21:59:53 +0000239 return cat
240
Christian Heimes33fe8092008-04-13 13:53:33 +0000241
Larry Hastings714e4932015-09-06 00:39:37 -0700242def _is_internal_frame(frame):
243 """Signal whether the frame is an internal CPython implementation detail."""
244 filename = frame.f_code.co_filename
245 return 'importlib' in filename and '_bootstrap' in filename
246
247
248def _next_external_frame(frame):
249 """Find the next frame that doesn't involve CPython internals."""
250 frame = frame.f_back
251 while frame is not None and _is_internal_frame(frame):
252 frame = frame.f_back
253 return frame
254
255
Christian Heimes33fe8092008-04-13 13:53:33 +0000256# Code typically replaced by _warnings
Victor Stinnere19558a2016-03-23 00:28:08 +0100257def warn(message, category=None, stacklevel=1, source=None):
Christian Heimes33fe8092008-04-13 13:53:33 +0000258 """Issue a warning, or maybe ignore it or raise an exception."""
259 # Check if message is already a Warning object
260 if isinstance(message, Warning):
261 category = message.__class__
262 # Check category argument
263 if category is None:
264 category = UserWarning
Berker Peksagd8089e02014-07-11 19:50:25 +0300265 if not (isinstance(category, type) and issubclass(category, Warning)):
266 raise TypeError("category must be a Warning subclass, "
267 "not '{:s}'".format(type(category).__name__))
Christian Heimes33fe8092008-04-13 13:53:33 +0000268 # Get context information
269 try:
Larry Hastings714e4932015-09-06 00:39:37 -0700270 if stacklevel <= 1 or _is_internal_frame(sys._getframe(1)):
271 # If frame is too small to care or if the warning originated in
272 # internal code, then do not try to hide any frames.
273 frame = sys._getframe(stacklevel)
274 else:
275 frame = sys._getframe(1)
276 # Look for one frame less since the above line starts us off.
277 for x in range(stacklevel-1):
278 frame = _next_external_frame(frame)
279 if frame is None:
280 raise ValueError
Christian Heimes33fe8092008-04-13 13:53:33 +0000281 except ValueError:
282 globals = sys.__dict__
283 lineno = 1
284 else:
Larry Hastings714e4932015-09-06 00:39:37 -0700285 globals = frame.f_globals
286 lineno = frame.f_lineno
Christian Heimes33fe8092008-04-13 13:53:33 +0000287 if '__name__' in globals:
288 module = globals['__name__']
289 else:
290 module = "<string>"
291 filename = globals.get('__file__')
292 if filename:
293 fnl = filename.lower()
Brett Cannonf299abd2015-04-13 14:21:02 -0400294 if fnl.endswith(".pyc"):
Christian Heimes33fe8092008-04-13 13:53:33 +0000295 filename = filename[:-1]
296 else:
297 if module == "__main__":
298 try:
299 filename = sys.argv[0]
300 except AttributeError:
301 # embedded interpreters don't have sys.argv, see bug #839151
302 filename = '__main__'
303 if not filename:
304 filename = module
305 registry = globals.setdefault("__warningregistry__", {})
306 warn_explicit(message, category, filename, lineno, module, registry,
Victor Stinnere19558a2016-03-23 00:28:08 +0100307 globals, source)
Christian Heimes33fe8092008-04-13 13:53:33 +0000308
309def warn_explicit(message, category, filename, lineno,
Victor Stinner914cde82016-03-19 01:03:51 +0100310 module=None, registry=None, module_globals=None,
311 source=None):
Brett Cannondb734912008-06-27 00:52:15 +0000312 lineno = int(lineno)
Christian Heimes33fe8092008-04-13 13:53:33 +0000313 if module is None:
314 module = filename or "<unknown>"
315 if module[-3:].lower() == ".py":
316 module = module[:-3] # XXX What about leading pathname?
317 if registry is None:
318 registry = {}
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200319 if registry.get('version', 0) != _filters_version:
320 registry.clear()
321 registry['version'] = _filters_version
Christian Heimes33fe8092008-04-13 13:53:33 +0000322 if isinstance(message, Warning):
323 text = str(message)
324 category = message.__class__
325 else:
326 text = message
327 message = category(message)
328 key = (text, category, lineno)
329 # Quick test for common case
330 if registry.get(key):
331 return
332 # Search the filters
333 for item in filters:
334 action, msg, cat, mod, ln = item
335 if ((msg is None or msg.match(text)) and
336 issubclass(category, cat) and
337 (mod is None or mod.match(module)) and
338 (ln == 0 or lineno == ln)):
339 break
340 else:
341 action = defaultaction
342 # Early exit actions
343 if action == "ignore":
344 registry[key] = 1
345 return
346
347 # Prime the linecache for formatting, in case the
348 # "file" is actually in a zipfile or something.
Antoine Pitrou7cb11fa2013-10-24 22:23:42 +0200349 import linecache
Christian Heimes33fe8092008-04-13 13:53:33 +0000350 linecache.getlines(filename, module_globals)
351
352 if action == "error":
353 raise message
354 # Other actions
355 if action == "once":
356 registry[key] = 1
357 oncekey = (text, category)
358 if onceregistry.get(oncekey):
359 return
360 onceregistry[oncekey] = 1
361 elif action == "always":
362 pass
363 elif action == "module":
364 registry[key] = 1
365 altkey = (text, category, 0)
366 if registry.get(altkey):
367 return
368 registry[altkey] = 1
369 elif action == "default":
370 registry[key] = 1
371 else:
372 # Unrecognized actions are errors
373 raise RuntimeError(
374 "Unrecognized action (%r) in warnings.filters:\n %s" %
375 (action, item))
376 # Print message and context
Victor Stinner914cde82016-03-19 01:03:51 +0100377 msg = WarningMessage(message, category, filename, lineno, source)
Victor Stinner1231a462016-03-19 00:47:17 +0100378 _showwarnmsg(msg)
Christian Heimes33fe8092008-04-13 13:53:33 +0000379
380
Brett Cannonec92e182008-09-02 02:46:59 +0000381class WarningMessage(object):
382
Brett Cannonec92e182008-09-02 02:46:59 +0000383 _WARNING_DETAILS = ("message", "category", "filename", "lineno", "file",
Victor Stinner914cde82016-03-19 01:03:51 +0100384 "line", "source")
Brett Cannonec92e182008-09-02 02:46:59 +0000385
386 def __init__(self, message, category, filename, lineno, file=None,
Victor Stinner914cde82016-03-19 01:03:51 +0100387 line=None, source=None):
Brett Cannonec92e182008-09-02 02:46:59 +0000388 local_values = locals()
389 for attr in self._WARNING_DETAILS:
390 setattr(self, attr, local_values[attr])
391 self._category_name = category.__name__ if category else None
392
393 def __str__(self):
394 return ("{message : %r, category : %r, filename : %r, lineno : %s, "
395 "line : %r}" % (self.message, self._category_name,
396 self.filename, self.lineno, self.line))
397
398
Brett Cannonec92e182008-09-02 02:46:59 +0000399class catch_warnings(object):
400
Brett Cannon1cd02472008-09-09 01:52:27 +0000401 """A context manager that copies and restores the warnings filter upon
402 exiting the context.
Brett Cannonec92e182008-09-02 02:46:59 +0000403
Brett Cannon1cd02472008-09-09 01:52:27 +0000404 The 'record' argument specifies whether warnings should be captured by a
405 custom implementation of warnings.showwarning() and be appended to a list
406 returned by the context manager. Otherwise None is returned by the context
407 manager. The objects appended to the list are arguments whose attributes
408 mirror the arguments to showwarning().
409
410 The 'module' argument is to specify an alternative module to the module
411 named 'warnings' and imported under that name. This argument is only useful
412 when testing the warnings module itself.
Brett Cannonec92e182008-09-02 02:46:59 +0000413
414 """
415
416 def __init__(self, *, record=False, module=None):
417 """Specify whether to record warnings and if an alternative module
418 should be used other than sys.modules['warnings'].
419
420 For compatibility with Python 3.0, please consider all arguments to be
421 keyword-only.
422
423 """
Brett Cannon1cd02472008-09-09 01:52:27 +0000424 self._record = record
Brett Cannonec92e182008-09-02 02:46:59 +0000425 self._module = sys.modules['warnings'] if module is None else module
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000426 self._entered = False
427
428 def __repr__(self):
429 args = []
430 if self._record:
431 args.append("record=True")
432 if self._module is not sys.modules['warnings']:
433 args.append("module=%r" % self._module)
434 name = type(self).__name__
435 return "%s(%s)" % (name, ", ".join(args))
Brett Cannonec92e182008-09-02 02:46:59 +0000436
437 def __enter__(self):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000438 if self._entered:
439 raise RuntimeError("Cannot enter %r twice" % self)
440 self._entered = True
Brett Cannonec92e182008-09-02 02:46:59 +0000441 self._filters = self._module.filters
442 self._module.filters = self._filters[:]
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200443 self._module._filters_mutated()
Brett Cannonec92e182008-09-02 02:46:59 +0000444 self._showwarning = self._module.showwarning
Victor Stinner1231a462016-03-19 00:47:17 +0100445 self._showwarnmsg = self._module._showwarnmsg
Brett Cannon1cd02472008-09-09 01:52:27 +0000446 if self._record:
447 log = []
Victor Stinner1231a462016-03-19 00:47:17 +0100448 def showarnmsg(msg):
449 log.append(msg)
450 self._module._showwarnmsg = showarnmsg
Brett Cannon1cd02472008-09-09 01:52:27 +0000451 return log
452 else:
453 return None
Brett Cannonec92e182008-09-02 02:46:59 +0000454
455 def __exit__(self, *exc_info):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000456 if not self._entered:
457 raise RuntimeError("Cannot exit %r without entering first" % self)
Brett Cannonec92e182008-09-02 02:46:59 +0000458 self._module.filters = self._filters
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200459 self._module._filters_mutated()
Brett Cannonec92e182008-09-02 02:46:59 +0000460 self._module.showwarning = self._showwarning
Victor Stinner1231a462016-03-19 00:47:17 +0100461 self._module._showwarnmsg = self._showwarnmsg
Brett Cannonec92e182008-09-02 02:46:59 +0000462
463
Christian Heimes33fe8092008-04-13 13:53:33 +0000464# filters contains a sequence of filter 5-tuples
465# The components of the 5-tuple are:
466# - an action: error, ignore, always, default, module, or once
467# - a compiled regex that must match the warning message
468# - a class representing the warning category
469# - a compiled regex that must match the module that is being warned
470# - a line number for the line being warning, or 0 to mean any line
471# If either if the compiled regexs are None, match anything.
472_warnings_defaults = False
473try:
Brett Cannonef0e6c32010-09-04 18:24:04 +0000474 from _warnings import (filters, _defaultaction, _onceregistry,
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200475 warn, warn_explicit, _filters_mutated)
Brett Cannonef0e6c32010-09-04 18:24:04 +0000476 defaultaction = _defaultaction
477 onceregistry = _onceregistry
Christian Heimes33fe8092008-04-13 13:53:33 +0000478 _warnings_defaults = True
Brett Cannoncd171c82013-07-04 17:43:24 -0400479except ImportError:
Christian Heimes33fe8092008-04-13 13:53:33 +0000480 filters = []
481 defaultaction = "default"
482 onceregistry = {}
483
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200484 _filters_version = 1
485
486 def _filters_mutated():
487 global _filters_version
488 _filters_version += 1
489
Christian Heimes33fe8092008-04-13 13:53:33 +0000490
Guido van Rossum2a862c62000-12-15 21:59:53 +0000491# Module initialization
Tim Peters66025202004-03-21 17:06:20 +0000492_processoptions(sys.warnoptions)
Christian Heimes33fe8092008-04-13 13:53:33 +0000493if not _warnings_defaults:
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000494 silence = [ImportWarning, PendingDeprecationWarning]
495 silence.append(DeprecationWarning)
496 for cls in silence:
497 simplefilter("ignore", category=cls)
Christian Heimes33fe8092008-04-13 13:53:33 +0000498 bytes_warning = sys.flags.bytes_warning
499 if bytes_warning > 1:
500 bytes_action = "error"
501 elif bytes_warning:
502 bytes_action = "default"
503 else:
504 bytes_action = "ignore"
505 simplefilter(bytes_action, category=BytesWarning, append=1)
Georg Brandl08be72d2010-10-24 15:11:22 +0000506 # resource usage warnings are enabled by default in pydebug mode
507 if hasattr(sys, 'gettotalrefcount'):
508 resource_action = "always"
509 else:
510 resource_action = "ignore"
511 simplefilter(resource_action, category=ResourceWarning, append=1)
512
Christian Heimes33fe8092008-04-13 13:53:33 +0000513del _warnings_defaults