/Lib/warnings.py

http://unladen-swallow.googlecode.com/ · Python · 402 lines · 328 code · 28 blank · 46 comment · 86 complexity · 76268b537a7101a7d65d02e2277f3f99 MD5 · raw file

  1. """Python part of the warnings subsystem."""
  2. # Note: function level imports should *not* be used
  3. # in this module as it may cause import lock deadlock.
  4. # See bug 683658.
  5. import linecache
  6. import sys
  7. import types
  8. __all__ = ["warn", "showwarning", "formatwarning", "filterwarnings",
  9. "resetwarnings", "catch_warnings"]
  10. def warnpy3k(message, category=None, stacklevel=1):
  11. """Issue a deprecation warning for Python 3.x related changes.
  12. Warnings are omitted unless Python is started with the -3 option.
  13. """
  14. if sys.py3kwarning:
  15. if category is None:
  16. category = DeprecationWarning
  17. warn(message, category, stacklevel+1)
  18. def _show_warning(message, category, filename, lineno, file=None, line=None):
  19. """Hook to write a warning to a file; replace if you like."""
  20. if file is None:
  21. file = sys.stderr
  22. try:
  23. file.write(formatwarning(message, category, filename, lineno, line))
  24. except IOError:
  25. pass # the file (probably stderr) is invalid - this warning gets lost.
  26. # Keep a worrking version around in case the deprecation of the old API is
  27. # triggered.
  28. showwarning = _show_warning
  29. def formatwarning(message, category, filename, lineno, line=None):
  30. """Function to format a warning the standard way."""
  31. s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message)
  32. line = linecache.getline(filename, lineno) if line is None else line
  33. if line:
  34. line = line.strip()
  35. s += " %s\n" % line
  36. return s
  37. def filterwarnings(action, message="", category=Warning, module="", lineno=0,
  38. append=0):
  39. """Insert an entry into the list of warnings filters (at the front).
  40. Use assertions to check that all arguments have the right type."""
  41. import re
  42. assert action in ("error", "ignore", "always", "default", "module",
  43. "once"), "invalid action: %r" % (action,)
  44. assert isinstance(message, basestring), "message must be a string"
  45. assert isinstance(category, (type, types.ClassType)), \
  46. "category must be a class"
  47. assert issubclass(category, Warning), "category must be a Warning subclass"
  48. assert isinstance(module, basestring), "module must be a string"
  49. assert isinstance(lineno, int) and lineno >= 0, \
  50. "lineno must be an int >= 0"
  51. item = (action, re.compile(message, re.I), category,
  52. re.compile(module), lineno)
  53. if append:
  54. filters.append(item)
  55. else:
  56. filters.insert(0, item)
  57. def simplefilter(action, category=Warning, lineno=0, append=0):
  58. """Insert a simple entry into the list of warnings filters (at the front).
  59. A simple filter matches all modules and messages.
  60. """
  61. assert action in ("error", "ignore", "always", "default", "module",
  62. "once"), "invalid action: %r" % (action,)
  63. assert isinstance(lineno, int) and lineno >= 0, \
  64. "lineno must be an int >= 0"
  65. item = (action, None, category, None, lineno)
  66. if append:
  67. filters.append(item)
  68. else:
  69. filters.insert(0, item)
  70. def resetwarnings():
  71. """Clear the list of warning filters, so that no filters are active."""
  72. filters[:] = []
  73. class _OptionError(Exception):
  74. """Exception used by option processing helpers."""
  75. pass
  76. # Helper to process -W options passed via sys.warnoptions
  77. def _processoptions(args):
  78. for arg in args:
  79. try:
  80. _setoption(arg)
  81. except _OptionError, msg:
  82. print >>sys.stderr, "Invalid -W option ignored:", msg
  83. # Helper for _processoptions()
  84. def _setoption(arg):
  85. import re
  86. parts = arg.split(':')
  87. if len(parts) > 5:
  88. raise _OptionError("too many fields (max 5): %r" % (arg,))
  89. while len(parts) < 5:
  90. parts.append('')
  91. action, message, category, module, lineno = [s.strip()
  92. for s in parts]
  93. action = _getaction(action)
  94. message = re.escape(message)
  95. category = _getcategory(category)
  96. module = re.escape(module)
  97. if module:
  98. module = module + '$'
  99. if lineno:
  100. try:
  101. lineno = int(lineno)
  102. if lineno < 0:
  103. raise ValueError
  104. except (ValueError, OverflowError):
  105. raise _OptionError("invalid lineno %r" % (lineno,))
  106. else:
  107. lineno = 0
  108. filterwarnings(action, message, category, module, lineno)
  109. # Helper for _setoption()
  110. def _getaction(action):
  111. if not action:
  112. return "default"
  113. if action == "all": return "always" # Alias
  114. for a in ('default', 'always', 'ignore', 'module', 'once', 'error'):
  115. if a.startswith(action):
  116. return a
  117. raise _OptionError("invalid action: %r" % (action,))
  118. # Helper for _setoption()
  119. def _getcategory(category):
  120. import re
  121. if not category:
  122. return Warning
  123. if re.match("^[a-zA-Z0-9_]+$", category):
  124. try:
  125. cat = eval(category)
  126. except NameError:
  127. raise _OptionError("unknown warning category: %r" % (category,))
  128. else:
  129. i = category.rfind(".")
  130. module = category[:i]
  131. klass = category[i+1:]
  132. try:
  133. m = __import__(module, None, None, [klass])
  134. except ImportError:
  135. raise _OptionError("invalid module name: %r" % (module,))
  136. try:
  137. cat = getattr(m, klass)
  138. except AttributeError:
  139. raise _OptionError("unknown warning category: %r" % (category,))
  140. if not issubclass(cat, Warning):
  141. raise _OptionError("invalid warning category: %r" % (category,))
  142. return cat
  143. # Code typically replaced by _warnings
  144. def warn(message, category=None, stacklevel=1):
  145. """Issue a warning, or maybe ignore it or raise an exception."""
  146. # Check if message is already a Warning object
  147. if isinstance(message, Warning):
  148. category = message.__class__
  149. # Check category argument
  150. if category is None:
  151. category = UserWarning
  152. assert issubclass(category, Warning)
  153. # Get context information
  154. try:
  155. caller = sys._getframe(stacklevel)
  156. except ValueError:
  157. globals = sys.__dict__
  158. lineno = 1
  159. else:
  160. globals = caller.f_globals
  161. lineno = caller.f_lineno
  162. if '__name__' in globals:
  163. module = globals['__name__']
  164. else:
  165. module = "<string>"
  166. filename = globals.get('__file__')
  167. if filename:
  168. fnl = filename.lower()
  169. if fnl.endswith((".pyc", ".pyo")):
  170. filename = filename[:-1]
  171. else:
  172. if module == "__main__":
  173. try:
  174. filename = sys.argv[0]
  175. except AttributeError:
  176. # embedded interpreters don't have sys.argv, see bug #839151
  177. filename = '__main__'
  178. if not filename:
  179. filename = module
  180. registry = globals.setdefault("__warningregistry__", {})
  181. warn_explicit(message, category, filename, lineno, module, registry,
  182. globals)
  183. def warn_explicit(message, category, filename, lineno,
  184. module=None, registry=None, module_globals=None):
  185. lineno = int(lineno)
  186. if module is None:
  187. module = filename or "<unknown>"
  188. if module[-3:].lower() == ".py":
  189. module = module[:-3] # XXX What about leading pathname?
  190. if registry is None:
  191. registry = {}
  192. if isinstance(message, Warning):
  193. text = str(message)
  194. category = message.__class__
  195. else:
  196. text = message
  197. message = category(message)
  198. key = (text, category, lineno)
  199. # Quick test for common case
  200. if registry.get(key):
  201. return
  202. # Search the filters
  203. for item in filters:
  204. action, msg, cat, mod, ln = item
  205. if ((msg is None or msg.match(text)) and
  206. issubclass(category, cat) and
  207. (mod is None or mod.match(module)) and
  208. (ln == 0 or lineno == ln)):
  209. break
  210. else:
  211. action = defaultaction
  212. # Early exit actions
  213. if action == "ignore":
  214. registry[key] = 1
  215. return
  216. # Prime the linecache for formatting, in case the
  217. # "file" is actually in a zipfile or something.
  218. linecache.getlines(filename, module_globals)
  219. if action == "error":
  220. raise message
  221. # Other actions
  222. if action == "once":
  223. registry[key] = 1
  224. oncekey = (text, category)
  225. if onceregistry.get(oncekey):
  226. return
  227. onceregistry[oncekey] = 1
  228. elif action == "always":
  229. pass
  230. elif action == "module":
  231. registry[key] = 1
  232. altkey = (text, category, 0)
  233. if registry.get(altkey):
  234. return
  235. registry[altkey] = 1
  236. elif action == "default":
  237. registry[key] = 1
  238. else:
  239. # Unrecognized actions are errors
  240. raise RuntimeError(
  241. "Unrecognized action (%r) in warnings.filters:\n %s" %
  242. (action, item))
  243. # Warn if showwarning() does not support the 'line' argument.
  244. # Don't use 'inspect' as it relies on an extension module, which break the
  245. # build thanks to 'warnings' being imported by setup.py.
  246. fxn_code = None
  247. if hasattr(showwarning, 'func_code'):
  248. fxn_code = showwarning.func_code
  249. elif hasattr(showwarning, '__func__'):
  250. fxn_code = showwarning.__func__.func_code
  251. if fxn_code:
  252. args = fxn_code.co_varnames[:fxn_code.co_argcount]
  253. CO_VARARGS = 0x4
  254. if 'line' not in args and not fxn_code.co_flags & CO_VARARGS:
  255. showwarning_msg = ("functions overriding warnings.showwarning() "
  256. "must support the 'line' argument")
  257. if message == showwarning_msg:
  258. _show_warning(message, category, filename, lineno)
  259. else:
  260. warn(showwarning_msg, DeprecationWarning)
  261. # Print message and context
  262. showwarning(message, category, filename, lineno)
  263. class WarningMessage(object):
  264. """Holds the result of a single showwarning() call."""
  265. _WARNING_DETAILS = ("message", "category", "filename", "lineno", "file",
  266. "line")
  267. def __init__(self, message, category, filename, lineno, file=None,
  268. line=None):
  269. local_values = locals()
  270. for attr in self._WARNING_DETAILS:
  271. setattr(self, attr, local_values[attr])
  272. self._category_name = category.__name__ if category else None
  273. def __str__(self):
  274. return ("{message : %r, category : %r, filename : %r, lineno : %s, "
  275. "line : %r}" % (self.message, self._category_name,
  276. self.filename, self.lineno, self.line))
  277. class catch_warnings(object):
  278. """A context manager that copies and restores the warnings filter upon
  279. exiting the context.
  280. The 'record' argument specifies whether warnings should be captured by a
  281. custom implementation of warnings.showwarning() and be appended to a list
  282. returned by the context manager. Otherwise None is returned by the context
  283. manager. The objects appended to the list are arguments whose attributes
  284. mirror the arguments to showwarning().
  285. The 'module' argument is to specify an alternative module to the module
  286. named 'warnings' and imported under that name. This argument is only useful
  287. when testing the warnings module itself.
  288. """
  289. def __init__(self, record=False, module=None):
  290. """Specify whether to record warnings and if an alternative module
  291. should be used other than sys.modules['warnings'].
  292. For compatibility with Python 3.0, please consider all arguments to be
  293. keyword-only.
  294. """
  295. self._record = record
  296. self._module = sys.modules['warnings'] if module is None else module
  297. self._entered = False
  298. def __repr__(self):
  299. args = []
  300. if self._record:
  301. args.append("record=True")
  302. if self._module is not sys.modules['warnings']:
  303. args.append("module=%r" % self._module)
  304. name = type(self).__name__
  305. return "%s(%s)" % (name, ", ".join(args))
  306. def __enter__(self):
  307. if self._entered:
  308. raise RuntimeError("Cannot enter %r twice" % self)
  309. self._entered = True
  310. self._filters = self._module.filters
  311. self._module.filters = self._filters[:]
  312. self._showwarning = self._module.showwarning
  313. if self._record:
  314. log = []
  315. def showwarning(*args, **kwargs):
  316. log.append(WarningMessage(*args, **kwargs))
  317. self._module.showwarning = showwarning
  318. return log
  319. else:
  320. return None
  321. def __exit__(self, *exc_info):
  322. if not self._entered:
  323. raise RuntimeError("Cannot exit %r without entering first" % self)
  324. self._module.filters = self._filters
  325. self._module.showwarning = self._showwarning
  326. # filters contains a sequence of filter 5-tuples
  327. # The components of the 5-tuple are:
  328. # - an action: error, ignore, always, default, module, or once
  329. # - a compiled regex that must match the warning message
  330. # - a class representing the warning category
  331. # - a compiled regex that must match the module that is being warned
  332. # - a line number for the line being warning, or 0 to mean any line
  333. # If either if the compiled regexs are None, match anything.
  334. _warnings_defaults = False
  335. try:
  336. from _warnings import (filters, default_action, once_registry,
  337. warn, warn_explicit)
  338. defaultaction = default_action
  339. onceregistry = once_registry
  340. _warnings_defaults = True
  341. except ImportError:
  342. filters = []
  343. defaultaction = "default"
  344. onceregistry = {}
  345. # Module initialization
  346. _processoptions(sys.warnoptions)
  347. if not _warnings_defaults:
  348. simplefilter("ignore", category=PendingDeprecationWarning, append=1)
  349. simplefilter("ignore", category=ImportWarning, append=1)
  350. bytes_warning = sys.flags.bytes_warning
  351. if bytes_warning > 1:
  352. bytes_action = "error"
  353. elif bytes_warning:
  354. bytes_action = "default"
  355. else:
  356. bytes_action = "ignore"
  357. simplefilter(bytes_action, category=BytesWarning, append=1)
  358. del _warnings_defaults