blob: d4f591ee71d85744442da571551663378b88161d [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):
Antoine Pitrou7cb11fa2013-10-24 22:23:42 +020036 import linecache
Victor Stinner1231a462016-03-19 00:47:17 +010037 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 Rossum2a862c62000-12-15 21:59:53 +000044 if line:
Christian Heimes33fe8092008-04-13 13:53:33 +000045 line = line.strip()
46 s += " %s\n" % line
Victor Stinner914cde82016-03-19 01:03:51 +010047 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 Rossum2a862c62000-12-15 21:59:53 +000059 return s
60
Victor Stinnereedf13f2016-03-19 02:11:56 +010061# Keep a reference to check if the function was replaced
62_showwarning = showwarning
63
64def _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
81def _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 Rossum9464a7d2001-01-14 14:08:40 +000090def filterwarnings(action, message="", category=Warning, module="", lineno=0,
Georg Brandlfe991052009-09-16 15:54:04 +000091 append=False):
Guido van Rossum2a862c62000-12-15 21:59:53 +000092 """Insert an entry into the list of warnings filters (at the front).
93
Georg Brandl495f7b52009-10-27 15:28:25 +000094 '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 Montanarod8f21202003-05-14 17:33:53 +0000102 import re
Guido van Rossum2a862c62000-12-15 21:59:53 +0000103 assert action in ("error", "ignore", "always", "default", "module",
Walter Dörwald70a6b492004-02-12 17:35:32 +0000104 "once"), "invalid action: %r" % (action,)
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000105 assert isinstance(message, str), "message must be a string"
Guido van Rossum13257902007-06-07 23:15:56 +0000106 assert isinstance(category, type), "category must be a class"
Guido van Rossum2a862c62000-12-15 21:59:53 +0000107 assert issubclass(category, Warning), "category must be a Warning subclass"
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000108 assert isinstance(module, str), "module must be a string"
Walter Dörwald65230a22002-06-03 15:58:32 +0000109 assert isinstance(lineno, int) and lineno >= 0, \
Guido van Rossum2a862c62000-12-15 21:59:53 +0000110 "lineno must be an int >= 0"
Guido van Rossum9464a7d2001-01-14 14:08:40 +0000111 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 Pitroucb0a0062014-09-18 02:40:46 +0200117 _filters_mutated()
Guido van Rossum2a862c62000-12-15 21:59:53 +0000118
Georg Brandlfe991052009-09-16 15:54:04 +0000119def simplefilter(action, category=Warning, lineno=0, append=False):
Jeremy Hylton85014662003-07-11 15:37:59 +0000120 """Insert a simple entry into the list of warnings filters (at the front).
121
122 A simple filter matches all modules and messages.
Georg Brandl495f7b52009-10-27 15:28:25 +0000123 '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 Hylton85014662003-07-11 15:37:59 +0000128 """
129 assert action in ("error", "ignore", "always", "default", "module",
Walter Dörwald70a6b492004-02-12 17:35:32 +0000130 "once"), "invalid action: %r" % (action,)
Jeremy Hylton85014662003-07-11 15:37:59 +0000131 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 Pitroucb0a0062014-09-18 02:40:46 +0200138 _filters_mutated()
Jeremy Hylton85014662003-07-11 15:37:59 +0000139
Guido van Rossum2a862c62000-12-15 21:59:53 +0000140def resetwarnings():
Tim Petersd0cc4f02002-04-16 01:51:25 +0000141 """Clear the list of warning filters, so that no filters are active."""
Guido van Rossum2a862c62000-12-15 21:59:53 +0000142 filters[:] = []
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200143 _filters_mutated()
Guido van Rossum2a862c62000-12-15 21:59:53 +0000144
145class _OptionError(Exception):
146 """Exception used by option processing helpers."""
147 pass
148
149# Helper to process -W options passed via sys.warnoptions
150def _processoptions(args):
151 for arg in args:
152 try:
153 _setoption(arg)
Guido van Rossumb940e112007-01-10 16:19:56 +0000154 except _OptionError as msg:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000155 print("Invalid -W option ignored:", msg, file=sys.stderr)
Guido van Rossum2a862c62000-12-15 21:59:53 +0000156
157# Helper for _processoptions()
158def _setoption(arg):
Skip Montanarod8f21202003-05-14 17:33:53 +0000159 import re
Tim Peterse1190062001-01-15 03:34:38 +0000160 parts = arg.split(':')
161 if len(parts) > 5:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000162 raise _OptionError("too many fields (max 5): %r" % (arg,))
Tim Peterse1190062001-01-15 03:34:38 +0000163 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örwald70a6b492004-02-12 17:35:32 +0000179 raise _OptionError("invalid lineno %r" % (lineno,))
Tim Peterse1190062001-01-15 03:34:38 +0000180 else:
181 lineno = 0
182 filterwarnings(action, message, category, module, lineno)
Guido van Rossum2a862c62000-12-15 21:59:53 +0000183
184# Helper for _setoption()
185def _getaction(action):
186 if not action:
187 return "default"
188 if action == "all": return "always" # Alias
Raymond Hettingerdbecd932005-02-06 06:57:08 +0000189 for a in ('default', 'always', 'ignore', 'module', 'once', 'error'):
Guido van Rossum2a862c62000-12-15 21:59:53 +0000190 if a.startswith(action):
191 return a
Walter Dörwald70a6b492004-02-12 17:35:32 +0000192 raise _OptionError("invalid action: %r" % (action,))
Guido van Rossum2a862c62000-12-15 21:59:53 +0000193
194# Helper for _setoption()
195def _getcategory(category):
Skip Montanarod8f21202003-05-14 17:33:53 +0000196 import re
Guido van Rossum2a862c62000-12-15 21:59:53 +0000197 if not category:
198 return Warning
199 if re.match("^[a-zA-Z0-9_]+$", category):
200 try:
201 cat = eval(category)
Guido van Rossumd1db30b2000-12-19 03:04:50 +0000202 except NameError:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000203 raise _OptionError("unknown warning category: %r" % (category,))
Guido van Rossum2a862c62000-12-15 21:59:53 +0000204 else:
205 i = category.rfind(".")
206 module = category[:i]
207 klass = category[i+1:]
Guido van Rossumd1db30b2000-12-19 03:04:50 +0000208 try:
Brett Cannoncd171c82013-07-04 17:43:24 -0400209 m = __import__(module, None, None, [klass])
210 except ImportError:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000211 raise _OptionError("invalid module name: %r" % (module,))
Guido van Rossumd1db30b2000-12-19 03:04:50 +0000212 try:
213 cat = getattr(m, klass)
214 except AttributeError:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000215 raise _OptionError("unknown warning category: %r" % (category,))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000216 if not issubclass(cat, Warning):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000217 raise _OptionError("invalid warning category: %r" % (category,))
Guido van Rossum2a862c62000-12-15 21:59:53 +0000218 return cat
219
Christian Heimes33fe8092008-04-13 13:53:33 +0000220
Larry Hastings714e4932015-09-06 00:39:37 -0700221def _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
227def _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 Heimes33fe8092008-04-13 13:53:33 +0000235# Code typically replaced by _warnings
Victor Stinnere19558a2016-03-23 00:28:08 +0100236def warn(message, category=None, stacklevel=1, source=None):
Christian Heimes33fe8092008-04-13 13:53:33 +0000237 """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 Peksagd8089e02014-07-11 19:50:25 +0300244 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 Heimes33fe8092008-04-13 13:53:33 +0000247 # Get context information
248 try:
Larry Hastings714e4932015-09-06 00:39:37 -0700249 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 Heimes33fe8092008-04-13 13:53:33 +0000260 except ValueError:
261 globals = sys.__dict__
262 lineno = 1
263 else:
Larry Hastings714e4932015-09-06 00:39:37 -0700264 globals = frame.f_globals
265 lineno = frame.f_lineno
Christian Heimes33fe8092008-04-13 13:53:33 +0000266 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 Cannonf299abd2015-04-13 14:21:02 -0400273 if fnl.endswith(".pyc"):
Christian Heimes33fe8092008-04-13 13:53:33 +0000274 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 Stinnere19558a2016-03-23 00:28:08 +0100286 globals, source)
Christian Heimes33fe8092008-04-13 13:53:33 +0000287
288def warn_explicit(message, category, filename, lineno,
Victor Stinner914cde82016-03-19 01:03:51 +0100289 module=None, registry=None, module_globals=None,
290 source=None):
Brett Cannondb734912008-06-27 00:52:15 +0000291 lineno = int(lineno)
Christian Heimes33fe8092008-04-13 13:53:33 +0000292 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 Pitroucb0a0062014-09-18 02:40:46 +0200298 if registry.get('version', 0) != _filters_version:
299 registry.clear()
300 registry['version'] = _filters_version
Christian Heimes33fe8092008-04-13 13:53:33 +0000301 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 Pitrou7cb11fa2013-10-24 22:23:42 +0200328 import linecache
Christian Heimes33fe8092008-04-13 13:53:33 +0000329 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 Stinner914cde82016-03-19 01:03:51 +0100356 msg = WarningMessage(message, category, filename, lineno, source)
Victor Stinner1231a462016-03-19 00:47:17 +0100357 _showwarnmsg(msg)
Christian Heimes33fe8092008-04-13 13:53:33 +0000358
359
Brett Cannonec92e182008-09-02 02:46:59 +0000360class WarningMessage(object):
361
Brett Cannonec92e182008-09-02 02:46:59 +0000362 _WARNING_DETAILS = ("message", "category", "filename", "lineno", "file",
Victor Stinner914cde82016-03-19 01:03:51 +0100363 "line", "source")
Brett Cannonec92e182008-09-02 02:46:59 +0000364
365 def __init__(self, message, category, filename, lineno, file=None,
Victor Stinner914cde82016-03-19 01:03:51 +0100366 line=None, source=None):
Brett Cannonec92e182008-09-02 02:46:59 +0000367 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 Cannonec92e182008-09-02 02:46:59 +0000378class catch_warnings(object):
379
Brett Cannon1cd02472008-09-09 01:52:27 +0000380 """A context manager that copies and restores the warnings filter upon
381 exiting the context.
Brett Cannonec92e182008-09-02 02:46:59 +0000382
Brett Cannon1cd02472008-09-09 01:52:27 +0000383 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 Cannonec92e182008-09-02 02:46:59 +0000392
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 Cannon1cd02472008-09-09 01:52:27 +0000403 self._record = record
Brett Cannonec92e182008-09-02 02:46:59 +0000404 self._module = sys.modules['warnings'] if module is None else module
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000405 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 Cannonec92e182008-09-02 02:46:59 +0000415
416 def __enter__(self):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000417 if self._entered:
418 raise RuntimeError("Cannot enter %r twice" % self)
419 self._entered = True
Brett Cannonec92e182008-09-02 02:46:59 +0000420 self._filters = self._module.filters
421 self._module.filters = self._filters[:]
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200422 self._module._filters_mutated()
Brett Cannonec92e182008-09-02 02:46:59 +0000423 self._showwarning = self._module.showwarning
Victor Stinner1231a462016-03-19 00:47:17 +0100424 self._showwarnmsg = self._module._showwarnmsg
Brett Cannon1cd02472008-09-09 01:52:27 +0000425 if self._record:
426 log = []
Victor Stinner1231a462016-03-19 00:47:17 +0100427 def showarnmsg(msg):
428 log.append(msg)
429 self._module._showwarnmsg = showarnmsg
Brett Cannon1cd02472008-09-09 01:52:27 +0000430 return log
431 else:
432 return None
Brett Cannonec92e182008-09-02 02:46:59 +0000433
434 def __exit__(self, *exc_info):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000435 if not self._entered:
436 raise RuntimeError("Cannot exit %r without entering first" % self)
Brett Cannonec92e182008-09-02 02:46:59 +0000437 self._module.filters = self._filters
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200438 self._module._filters_mutated()
Brett Cannonec92e182008-09-02 02:46:59 +0000439 self._module.showwarning = self._showwarning
Victor Stinner1231a462016-03-19 00:47:17 +0100440 self._module._showwarnmsg = self._showwarnmsg
Brett Cannonec92e182008-09-02 02:46:59 +0000441
442
Christian Heimes33fe8092008-04-13 13:53:33 +0000443# 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
452try:
Brett Cannonef0e6c32010-09-04 18:24:04 +0000453 from _warnings import (filters, _defaultaction, _onceregistry,
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200454 warn, warn_explicit, _filters_mutated)
Brett Cannonef0e6c32010-09-04 18:24:04 +0000455 defaultaction = _defaultaction
456 onceregistry = _onceregistry
Christian Heimes33fe8092008-04-13 13:53:33 +0000457 _warnings_defaults = True
Brett Cannoncd171c82013-07-04 17:43:24 -0400458except ImportError:
Christian Heimes33fe8092008-04-13 13:53:33 +0000459 filters = []
460 defaultaction = "default"
461 onceregistry = {}
462
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200463 _filters_version = 1
464
465 def _filters_mutated():
466 global _filters_version
467 _filters_version += 1
468
Christian Heimes33fe8092008-04-13 13:53:33 +0000469
Guido van Rossum2a862c62000-12-15 21:59:53 +0000470# Module initialization
Tim Peters66025202004-03-21 17:06:20 +0000471_processoptions(sys.warnoptions)
Christian Heimes33fe8092008-04-13 13:53:33 +0000472if not _warnings_defaults:
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000473 silence = [ImportWarning, PendingDeprecationWarning]
474 silence.append(DeprecationWarning)
475 for cls in silence:
476 simplefilter("ignore", category=cls)
Christian Heimes33fe8092008-04-13 13:53:33 +0000477 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 Brandl08be72d2010-10-24 15:11:22 +0000485 # 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 Heimes33fe8092008-04-13 13:53:33 +0000492del _warnings_defaults