PageRenderTime 71ms CodeModel.GetById 12ms RepoModel.GetById 3ms app.codeStats 0ms

/lib-python/2.7/warnings.py

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