blob: 970d0ffade7f9ca3ce1f0b1ecdfdffb72db8a426 [file] [log] [blame]
Guido van Rossum2a862c62000-12-15 21:59:53 +00001"""Python part of the warnings subsystem."""
2
Mark Hammonda43fd0c2003-02-19 00:33:33 +00003# Note: function level imports should *not* be used
4# in this module as it may cause import lock deadlock.
5# See bug 683658.
Skip Montanarod8f21202003-05-14 17:33:53 +00006import sys, types
Mark Hammonda43fd0c2003-02-19 00:33:33 +00007import linecache
Guido van Rossum2a862c62000-12-15 21:59:53 +00008
Skip Montanaro40fc1602001-03-01 04:27:19 +00009__all__ = ["warn", "showwarning", "formatwarning", "filterwarnings",
10 "resetwarnings"]
11
Jeremy Hylton85014662003-07-11 15:37:59 +000012# filters contains a sequence of filter 5-tuples
13# The components of the 5-tuple are:
14# - an action: error, ignore, always, default, module, or once
15# - a compiled regex that must match the warning message
16# - a class representing the warning category
17# - a compiled regex that must match the module that is being warned
18# - a line number for the line being warning, or 0 to mean any line
19# If either if the compiled regexs are None, match anything.
Guido van Rossum2a862c62000-12-15 21:59:53 +000020filters = []
Jeremy Hylton85014662003-07-11 15:37:59 +000021defaultaction = "default"
Guido van Rossum2a862c62000-12-15 21:59:53 +000022onceregistry = {}
23
24def warn(message, category=None, stacklevel=1):
25 """Issue a warning, or maybe ignore it or raise an exception."""
Walter Dörwaldb25c2b02002-03-21 10:38:40 +000026 # Check if message is already a Warning object
27 if isinstance(message, Warning):
Tim Peters863ac442002-04-16 01:38:40 +000028 category = message.__class__
Guido van Rossum2a862c62000-12-15 21:59:53 +000029 # Check category argument
30 if category is None:
31 category = UserWarning
32 assert issubclass(category, Warning)
33 # Get context information
34 try:
35 caller = sys._getframe(stacklevel)
36 except ValueError:
37 globals = sys.__dict__
38 lineno = 1
39 else:
40 globals = caller.f_globals
41 lineno = caller.f_lineno
Raymond Hettinger54f02222002-06-01 14:18:47 +000042 if '__name__' in globals:
Guido van Rossum8031bbe2001-08-31 17:46:35 +000043 module = globals['__name__']
44 else:
45 module = "<string>"
Guido van Rossum2a862c62000-12-15 21:59:53 +000046 filename = globals.get('__file__')
47 if filename:
48 fnl = filename.lower()
Georg Brandlb2afe852006-06-09 20:43:48 +000049 if fnl.endswith((".pyc", ".pyo")):
Guido van Rossum2a862c62000-12-15 21:59:53 +000050 filename = filename[:-1]
51 else:
52 if module == "__main__":
Georg Brandl12fe9b42005-06-26 22:53:29 +000053 try:
54 filename = sys.argv[0]
55 except AttributeError:
56 # embedded interpreters don't have sys.argv, see bug #839151
57 filename = '__main__'
Guido van Rossum2a862c62000-12-15 21:59:53 +000058 if not filename:
59 filename = module
Guido van Rossum2a862c62000-12-15 21:59:53 +000060 registry = globals.setdefault("__warningregistry__", {})
Phillip J. Eby47032112006-04-11 01:07:43 +000061 warn_explicit(message, category, filename, lineno, module, registry,
62 globals)
Guido van Rossum9e263182001-02-28 21:43:40 +000063
64def warn_explicit(message, category, filename, lineno,
Phillip J. Eby47032112006-04-11 01:07:43 +000065 module=None, registry=None, module_globals=None):
Guido van Rossum9e263182001-02-28 21:43:40 +000066 if module is None:
Georg Brandl4edd9892006-01-13 16:59:46 +000067 module = filename or "<unknown>"
Guido van Rossum9e263182001-02-28 21:43:40 +000068 if module[-3:].lower() == ".py":
69 module = module[:-3] # XXX What about leading pathname?
70 if registry is None:
71 registry = {}
Walter Dörwaldb25c2b02002-03-21 10:38:40 +000072 if isinstance(message, Warning):
Tim Peters863ac442002-04-16 01:38:40 +000073 text = str(message)
74 category = message.__class__
Walter Dörwaldb25c2b02002-03-21 10:38:40 +000075 else:
Tim Peters863ac442002-04-16 01:38:40 +000076 text = message
77 message = category(message)
Walter Dörwaldb25c2b02002-03-21 10:38:40 +000078 key = (text, category, lineno)
Guido van Rossum3756fa32001-02-28 22:26:36 +000079 # Quick test for common case
Guido van Rossum2a862c62000-12-15 21:59:53 +000080 if registry.get(key):
81 return
82 # Search the filters
83 for item in filters:
84 action, msg, cat, mod, ln = item
Jeremy Hylton85014662003-07-11 15:37:59 +000085 if ((msg is None or msg.match(text)) and
Guido van Rossum2a862c62000-12-15 21:59:53 +000086 issubclass(category, cat) and
Walter Dörwald6cea6932004-12-29 15:28:09 +000087 (mod is None or mod.match(module)) and
Guido van Rossum2a862c62000-12-15 21:59:53 +000088 (ln == 0 or lineno == ln)):
89 break
90 else:
91 action = defaultaction
92 # Early exit actions
93 if action == "ignore":
94 registry[key] = 1
95 return
Phillip J. Eby47032112006-04-11 01:07:43 +000096
97 # Prime the linecache for formatting, in case the
98 # "file" is actually in a zipfile or something.
99 linecache.getlines(filename, module_globals)
100
Guido van Rossum2a862c62000-12-15 21:59:53 +0000101 if action == "error":
Walter Dörwaldb25c2b02002-03-21 10:38:40 +0000102 raise message
Guido van Rossum2a862c62000-12-15 21:59:53 +0000103 # Other actions
104 if action == "once":
105 registry[key] = 1
Walter Dörwaldb25c2b02002-03-21 10:38:40 +0000106 oncekey = (text, category)
Guido van Rossum2a862c62000-12-15 21:59:53 +0000107 if onceregistry.get(oncekey):
108 return
109 onceregistry[oncekey] = 1
110 elif action == "always":
111 pass
112 elif action == "module":
113 registry[key] = 1
Walter Dörwaldb25c2b02002-03-21 10:38:40 +0000114 altkey = (text, category, 0)
Guido van Rossum2a862c62000-12-15 21:59:53 +0000115 if registry.get(altkey):
116 return
117 registry[altkey] = 1
118 elif action == "default":
119 registry[key] = 1
120 else:
121 # Unrecognized actions are errors
122 raise RuntimeError(
Walter Dörwald70a6b492004-02-12 17:35:32 +0000123 "Unrecognized action (%r) in warnings.filters:\n %s" %
124 (action, item))
Guido van Rossum2a862c62000-12-15 21:59:53 +0000125 # Print message and context
126 showwarning(message, category, filename, lineno)
127
Christian Heimes28104c52007-11-27 23:16:44 +0000128def warnpy3k(message, category=None, stacklevel=1):
129 """Issue a deprecation warning for Python 3.x related changes.
130
131 Warnings are omitted unless Python is started with the -3 option.
132 """
133 if sys.py3kwarning:
134 if category is None:
135 category = DeprecationWarning
136 warn(message, category, stacklevel+1)
137
Guido van Rossum2a862c62000-12-15 21:59:53 +0000138def showwarning(message, category, filename, lineno, file=None):
139 """Hook to write a warning to a file; replace if you like."""
140 if file is None:
141 file = sys.stderr
Mark Hammond51a0ae32002-09-11 13:22:35 +0000142 try:
143 file.write(formatwarning(message, category, filename, lineno))
144 except IOError:
145 pass # the file (probably stderr) is invalid - this warning gets lost.
Guido van Rossum2a862c62000-12-15 21:59:53 +0000146
147def formatwarning(message, category, filename, lineno):
Guido van Rossum9464a7d2001-01-14 14:08:40 +0000148 """Function to format a warning the standard way."""
Guido van Rossum2a862c62000-12-15 21:59:53 +0000149 s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message)
150 line = linecache.getline(filename, lineno).strip()
151 if line:
152 s = s + " " + line + "\n"
153 return s
154
Guido van Rossum9464a7d2001-01-14 14:08:40 +0000155def filterwarnings(action, message="", category=Warning, module="", lineno=0,
156 append=0):
Guido van Rossum2a862c62000-12-15 21:59:53 +0000157 """Insert an entry into the list of warnings filters (at the front).
158
159 Use assertions to check that all arguments have the right type."""
Skip Montanarod8f21202003-05-14 17:33:53 +0000160 import re
Guido van Rossum2a862c62000-12-15 21:59:53 +0000161 assert action in ("error", "ignore", "always", "default", "module",
Walter Dörwald70a6b492004-02-12 17:35:32 +0000162 "once"), "invalid action: %r" % (action,)
Martin v. Löwisff9284b2002-10-14 21:06:02 +0000163 assert isinstance(message, basestring), "message must be a string"
Brett Cannonbf364092006-03-01 04:25:17 +0000164 assert isinstance(category, (type, types.ClassType)), \
165 "category must be a class"
Guido van Rossum2a862c62000-12-15 21:59:53 +0000166 assert issubclass(category, Warning), "category must be a Warning subclass"
Martin v. Löwisff9284b2002-10-14 21:06:02 +0000167 assert isinstance(module, basestring), "module must be a string"
Walter Dörwald65230a22002-06-03 15:58:32 +0000168 assert isinstance(lineno, int) and lineno >= 0, \
Guido van Rossum2a862c62000-12-15 21:59:53 +0000169 "lineno must be an int >= 0"
Guido van Rossum9464a7d2001-01-14 14:08:40 +0000170 item = (action, re.compile(message, re.I), category,
171 re.compile(module), lineno)
172 if append:
173 filters.append(item)
174 else:
175 filters.insert(0, item)
Guido van Rossum2a862c62000-12-15 21:59:53 +0000176
Jeremy Hylton85014662003-07-11 15:37:59 +0000177def simplefilter(action, category=Warning, lineno=0, append=0):
178 """Insert a simple entry into the list of warnings filters (at the front).
179
180 A simple filter matches all modules and messages.
181 """
182 assert action in ("error", "ignore", "always", "default", "module",
Walter Dörwald70a6b492004-02-12 17:35:32 +0000183 "once"), "invalid action: %r" % (action,)
Jeremy Hylton85014662003-07-11 15:37:59 +0000184 assert isinstance(lineno, int) and lineno >= 0, \
185 "lineno must be an int >= 0"
186 item = (action, None, category, None, lineno)
187 if append:
188 filters.append(item)
189 else:
190 filters.insert(0, item)
191
Guido van Rossum2a862c62000-12-15 21:59:53 +0000192def resetwarnings():
Tim Petersd0cc4f02002-04-16 01:51:25 +0000193 """Clear the list of warning filters, so that no filters are active."""
Guido van Rossum2a862c62000-12-15 21:59:53 +0000194 filters[:] = []
195
196class _OptionError(Exception):
197 """Exception used by option processing helpers."""
198 pass
199
200# Helper to process -W options passed via sys.warnoptions
201def _processoptions(args):
202 for arg in args:
203 try:
204 _setoption(arg)
205 except _OptionError, msg:
206 print >>sys.stderr, "Invalid -W option ignored:", msg
207
208# Helper for _processoptions()
209def _setoption(arg):
Skip Montanarod8f21202003-05-14 17:33:53 +0000210 import re
Tim Peterse1190062001-01-15 03:34:38 +0000211 parts = arg.split(':')
212 if len(parts) > 5:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000213 raise _OptionError("too many fields (max 5): %r" % (arg,))
Tim Peterse1190062001-01-15 03:34:38 +0000214 while len(parts) < 5:
215 parts.append('')
216 action, message, category, module, lineno = [s.strip()
217 for s in parts]
218 action = _getaction(action)
219 message = re.escape(message)
220 category = _getcategory(category)
221 module = re.escape(module)
222 if module:
223 module = module + '$'
224 if lineno:
225 try:
226 lineno = int(lineno)
227 if lineno < 0:
228 raise ValueError
229 except (ValueError, OverflowError):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000230 raise _OptionError("invalid lineno %r" % (lineno,))
Tim Peterse1190062001-01-15 03:34:38 +0000231 else:
232 lineno = 0
233 filterwarnings(action, message, category, module, lineno)
Guido van Rossum2a862c62000-12-15 21:59:53 +0000234
235# Helper for _setoption()
236def _getaction(action):
237 if not action:
238 return "default"
239 if action == "all": return "always" # Alias
Raymond Hettingerdbecd932005-02-06 06:57:08 +0000240 for a in ('default', 'always', 'ignore', 'module', 'once', 'error'):
Guido van Rossum2a862c62000-12-15 21:59:53 +0000241 if a.startswith(action):
242 return a
Walter Dörwald70a6b492004-02-12 17:35:32 +0000243 raise _OptionError("invalid action: %r" % (action,))
Guido van Rossum2a862c62000-12-15 21:59:53 +0000244
245# Helper for _setoption()
246def _getcategory(category):
Skip Montanarod8f21202003-05-14 17:33:53 +0000247 import re
Guido van Rossum2a862c62000-12-15 21:59:53 +0000248 if not category:
249 return Warning
250 if re.match("^[a-zA-Z0-9_]+$", category):
251 try:
252 cat = eval(category)
Guido van Rossumd1db30b2000-12-19 03:04:50 +0000253 except NameError:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000254 raise _OptionError("unknown warning category: %r" % (category,))
Guido van Rossum2a862c62000-12-15 21:59:53 +0000255 else:
256 i = category.rfind(".")
257 module = category[:i]
258 klass = category[i+1:]
Guido van Rossumd1db30b2000-12-19 03:04:50 +0000259 try:
260 m = __import__(module, None, None, [klass])
261 except ImportError:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000262 raise _OptionError("invalid module name: %r" % (module,))
Guido van Rossumd1db30b2000-12-19 03:04:50 +0000263 try:
264 cat = getattr(m, klass)
265 except AttributeError:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000266 raise _OptionError("unknown warning category: %r" % (category,))
Brett Cannon53ab5b72006-06-22 16:49:14 +0000267 if not issubclass(cat, Warning):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000268 raise _OptionError("invalid warning category: %r" % (category,))
Guido van Rossum2a862c62000-12-15 21:59:53 +0000269 return cat
270
Guido van Rossum2a862c62000-12-15 21:59:53 +0000271# Module initialization
Tim Peters66025202004-03-21 17:06:20 +0000272_processoptions(sys.warnoptions)
Tim Peters66025202004-03-21 17:06:20 +0000273simplefilter("ignore", category=PendingDeprecationWarning, append=1)
Nick Coghlanb6983bb2006-07-06 13:35:27 +0000274simplefilter("ignore", category=ImportWarning, append=1)