warnings.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. """Python part of the warnings subsystem."""
  2. import sys
  3. __all__ = ["warn", "warn_explicit", "showwarning",
  4. "formatwarning", "filterwarnings", "simplefilter",
  5. "resetwarnings", "catch_warnings"]
  6. def showwarning(message, category, filename, lineno, file=None, line=None):
  7. """Hook to write a warning to a file; replace if you like."""
  8. msg = WarningMessage(message, category, filename, lineno, file, line)
  9. _showwarnmsg_impl(msg)
  10. def formatwarning(message, category, filename, lineno, line=None):
  11. """Function to format a warning the standard way."""
  12. msg = WarningMessage(message, category, filename, lineno, None, line)
  13. return _formatwarnmsg_impl(msg)
  14. def _showwarnmsg_impl(msg):
  15. file = msg.file
  16. if file is None:
  17. file = sys.stderr
  18. if file is None:
  19. # sys.stderr is None when run with pythonw.exe:
  20. # warnings get lost
  21. return
  22. text = _formatwarnmsg(msg)
  23. try:
  24. file.write(text)
  25. except OSError:
  26. # the file (probably stderr) is invalid - this warning gets lost.
  27. pass
  28. def _formatwarnmsg_impl(msg):
  29. category = msg.category.__name__
  30. s = f"{msg.filename}:{msg.lineno}: {category}: {msg.message}\n"
  31. # "sys" is a made up file name when we are not able to get the frame
  32. # so do not try to get the source line
  33. if msg.line is None and msg.filename != "sys":
  34. try:
  35. import linecache
  36. line = linecache.getline(msg.filename, msg.lineno)
  37. except Exception:
  38. # When a warning is logged during Python shutdown, linecache
  39. # and the import machinery don't work anymore
  40. line = None
  41. linecache = None
  42. else:
  43. line = msg.line
  44. if line:
  45. line = line.strip()
  46. s += " %s\n" % line
  47. if msg.source is not None:
  48. try:
  49. import tracemalloc
  50. # Logging a warning should not raise a new exception:
  51. # catch Exception, not only ImportError and RecursionError.
  52. except Exception:
  53. # don't suggest to enable tracemalloc if it's not available
  54. suggest_tracemalloc = False
  55. tb = None
  56. else:
  57. try:
  58. suggest_tracemalloc = not tracemalloc.is_tracing()
  59. tb = tracemalloc.get_object_traceback(msg.source)
  60. except Exception:
  61. # When a warning is logged during Python shutdown, tracemalloc
  62. # and the import machinery don't work anymore
  63. suggest_tracemalloc = False
  64. tb = None
  65. if tb is not None:
  66. s += 'Object allocated at (most recent call last):\n'
  67. for frame in tb:
  68. s += (' File "%s", lineno %s\n'
  69. % (frame.filename, frame.lineno))
  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
  77. if line:
  78. line = line.strip()
  79. s += ' %s\n' % line
  80. elif suggest_tracemalloc:
  81. s += (f'{category}: Enable tracemalloc to get the object '
  82. f'allocation traceback\n')
  83. return s
  84. # Keep a reference to check if the function was replaced
  85. _showwarning_orig = showwarning
  86. def _showwarnmsg(msg):
  87. """Hook to write a warning to a file; replace if you like."""
  88. try:
  89. sw = showwarning
  90. except NameError:
  91. pass
  92. else:
  93. if sw is not _showwarning_orig:
  94. # warnings.showwarning() was replaced
  95. if not callable(sw):
  96. raise TypeError("warnings.showwarning() must be set to a "
  97. "function or method")
  98. sw(msg.message, msg.category, msg.filename, msg.lineno,
  99. msg.file, msg.line)
  100. return
  101. _showwarnmsg_impl(msg)
  102. # Keep a reference to check if the function was replaced
  103. _formatwarning_orig = formatwarning
  104. def _formatwarnmsg(msg):
  105. """Function to format a warning the standard way."""
  106. try:
  107. fw = formatwarning
  108. except NameError:
  109. pass
  110. else:
  111. if fw is not _formatwarning_orig:
  112. # warnings.formatwarning() was replaced
  113. return fw(msg.message, msg.category,
  114. msg.filename, msg.lineno, msg.line)
  115. return _formatwarnmsg_impl(msg)
  116. def filterwarnings(action, message="", category=Warning, module="", lineno=0,
  117. append=False):
  118. """Insert an entry into the list of warnings filters (at the front).
  119. 'action' -- one of "error", "ignore", "always", "default", "module",
  120. or "once"
  121. 'message' -- a regex that the warning message must match
  122. 'category' -- a class that the warning must be a subclass of
  123. 'module' -- a regex that the module name must match
  124. 'lineno' -- an integer line number, 0 matches all warnings
  125. 'append' -- if true, append to the list of filters
  126. """
  127. assert action in ("error", "ignore", "always", "default", "module",
  128. "once"), "invalid action: %r" % (action,)
  129. assert isinstance(message, str), "message must be a string"
  130. assert isinstance(category, type), "category must be a class"
  131. assert issubclass(category, Warning), "category must be a Warning subclass"
  132. assert isinstance(module, str), "module must be a string"
  133. assert isinstance(lineno, int) and lineno >= 0, \
  134. "lineno must be an int >= 0"
  135. if message or module:
  136. import re
  137. if message:
  138. message = re.compile(message, re.I)
  139. else:
  140. message = None
  141. if module:
  142. module = re.compile(module)
  143. else:
  144. module = None
  145. _add_filter(action, message, category, module, lineno, append=append)
  146. def simplefilter(action, category=Warning, lineno=0, append=False):
  147. """Insert a simple entry into the list of warnings filters (at the front).
  148. A simple filter matches all modules and messages.
  149. 'action' -- one of "error", "ignore", "always", "default", "module",
  150. or "once"
  151. 'category' -- a class that the warning must be a subclass of
  152. 'lineno' -- an integer line number, 0 matches all warnings
  153. 'append' -- if true, append to the list of filters
  154. """
  155. assert action in ("error", "ignore", "always", "default", "module",
  156. "once"), "invalid action: %r" % (action,)
  157. assert isinstance(lineno, int) and lineno >= 0, \
  158. "lineno must be an int >= 0"
  159. _add_filter(action, None, category, None, lineno, append=append)
  160. def _add_filter(*item, append):
  161. # Remove possible duplicate filters, so new one will be placed
  162. # in correct place. If append=True and duplicate exists, do nothing.
  163. if not append:
  164. try:
  165. filters.remove(item)
  166. except ValueError:
  167. pass
  168. filters.insert(0, item)
  169. else:
  170. if item not in filters:
  171. filters.append(item)
  172. _filters_mutated()
  173. def resetwarnings():
  174. """Clear the list of warning filters, so that no filters are active."""
  175. filters[:] = []
  176. _filters_mutated()
  177. class _OptionError(Exception):
  178. """Exception used by option processing helpers."""
  179. pass
  180. # Helper to process -W options passed via sys.warnoptions
  181. def _processoptions(args):
  182. for arg in args:
  183. try:
  184. _setoption(arg)
  185. except _OptionError as msg:
  186. print("Invalid -W option ignored:", msg, file=sys.stderr)
  187. # Helper for _processoptions()
  188. def _setoption(arg):
  189. parts = arg.split(':')
  190. if len(parts) > 5:
  191. raise _OptionError("too many fields (max 5): %r" % (arg,))
  192. while len(parts) < 5:
  193. parts.append('')
  194. action, message, category, module, lineno = [s.strip()
  195. for s in parts]
  196. action = _getaction(action)
  197. category = _getcategory(category)
  198. if message or module:
  199. import re
  200. if message:
  201. message = re.escape(message)
  202. if module:
  203. module = re.escape(module) + r'\Z'
  204. if lineno:
  205. try:
  206. lineno = int(lineno)
  207. if lineno < 0:
  208. raise ValueError
  209. except (ValueError, OverflowError):
  210. raise _OptionError("invalid lineno %r" % (lineno,)) from None
  211. else:
  212. lineno = 0
  213. filterwarnings(action, message, category, module, lineno)
  214. # Helper for _setoption()
  215. def _getaction(action):
  216. if not action:
  217. return "default"
  218. if action == "all": return "always" # Alias
  219. for a in ('default', 'always', 'ignore', 'module', 'once', 'error'):
  220. if a.startswith(action):
  221. return a
  222. raise _OptionError("invalid action: %r" % (action,))
  223. # Helper for _setoption()
  224. def _getcategory(category):
  225. if not category:
  226. return Warning
  227. if '.' not in category:
  228. import builtins as m
  229. klass = category
  230. else:
  231. module, _, klass = category.rpartition('.')
  232. try:
  233. m = __import__(module, None, None, [klass])
  234. except ImportError:
  235. raise _OptionError("invalid module name: %r" % (module,)) from None
  236. try:
  237. cat = getattr(m, klass)
  238. except AttributeError:
  239. raise _OptionError("unknown warning category: %r" % (category,)) from None
  240. if not issubclass(cat, Warning):
  241. raise _OptionError("invalid warning category: %r" % (category,))
  242. return cat
  243. def _is_internal_filename(filename):
  244. return 'importlib' in filename and '_bootstrap' in filename
  245. def _is_filename_to_skip(filename, skip_file_prefixes):
  246. return any(filename.startswith(prefix) for prefix in skip_file_prefixes)
  247. def _is_internal_frame(frame):
  248. """Signal whether the frame is an internal CPython implementation detail."""
  249. return _is_internal_filename(frame.f_code.co_filename)
  250. def _next_external_frame(frame, skip_file_prefixes):
  251. """Find the next frame that doesn't involve Python or user internals."""
  252. frame = frame.f_back
  253. while frame is not None and (
  254. _is_internal_filename(filename := frame.f_code.co_filename) or
  255. _is_filename_to_skip(filename, skip_file_prefixes)):
  256. frame = frame.f_back
  257. return frame
  258. # Code typically replaced by _warnings
  259. def warn(message, category=None, stacklevel=1, source=None,
  260. *, skip_file_prefixes=()):
  261. """Issue a warning, or maybe ignore it or raise an exception."""
  262. # Check if message is already a Warning object
  263. if isinstance(message, Warning):
  264. category = message.__class__
  265. # Check category argument
  266. if category is None:
  267. category = UserWarning
  268. if not (isinstance(category, type) and issubclass(category, Warning)):
  269. raise TypeError("category must be a Warning subclass, "
  270. "not '{:s}'".format(type(category).__name__))
  271. if not isinstance(skip_file_prefixes, tuple):
  272. # The C version demands a tuple for implementation performance.
  273. raise TypeError('skip_file_prefixes must be a tuple of strs.')
  274. if skip_file_prefixes:
  275. stacklevel = max(2, stacklevel)
  276. # Get context information
  277. try:
  278. if stacklevel <= 1 or _is_internal_frame(sys._getframe(1)):
  279. # If frame is too small to care or if the warning originated in
  280. # internal code, then do not try to hide any frames.
  281. frame = sys._getframe(stacklevel)
  282. else:
  283. frame = sys._getframe(1)
  284. # Look for one frame less since the above line starts us off.
  285. for x in range(stacklevel-1):
  286. frame = _next_external_frame(frame, skip_file_prefixes)
  287. if frame is None:
  288. raise ValueError
  289. except ValueError:
  290. globals = sys.__dict__
  291. filename = "sys"
  292. lineno = 1
  293. else:
  294. globals = frame.f_globals
  295. filename = frame.f_code.co_filename
  296. lineno = frame.f_lineno
  297. if '__name__' in globals:
  298. module = globals['__name__']
  299. else:
  300. module = "<string>"
  301. registry = globals.setdefault("__warningregistry__", {})
  302. warn_explicit(message, category, filename, lineno, module, registry,
  303. globals, source)
  304. def warn_explicit(message, category, filename, lineno,
  305. module=None, registry=None, module_globals=None,
  306. source=None):
  307. lineno = int(lineno)
  308. if module is None:
  309. module = filename or "<unknown>"
  310. if module[-3:].lower() == ".py":
  311. module = module[:-3] # XXX What about leading pathname?
  312. if registry is None:
  313. registry = {}
  314. if registry.get('version', 0) != _filters_version:
  315. registry.clear()
  316. registry['version'] = _filters_version
  317. if isinstance(message, Warning):
  318. text = str(message)
  319. category = message.__class__
  320. else:
  321. text = message
  322. message = category(message)
  323. key = (text, category, lineno)
  324. # Quick test for common case
  325. if registry.get(key):
  326. return
  327. # Search the filters
  328. for item in filters:
  329. action, msg, cat, mod, ln = item
  330. if ((msg is None or msg.match(text)) and
  331. issubclass(category, cat) and
  332. (mod is None or mod.match(module)) and
  333. (ln == 0 or lineno == ln)):
  334. break
  335. else:
  336. action = defaultaction
  337. # Early exit actions
  338. if action == "ignore":
  339. return
  340. # Prime the linecache for formatting, in case the
  341. # "file" is actually in a zipfile or something.
  342. import linecache
  343. linecache.getlines(filename, module_globals)
  344. if action == "error":
  345. raise message
  346. # Other actions
  347. if action == "once":
  348. registry[key] = 1
  349. oncekey = (text, category)
  350. if onceregistry.get(oncekey):
  351. return
  352. onceregistry[oncekey] = 1
  353. elif action == "always":
  354. pass
  355. elif action == "module":
  356. registry[key] = 1
  357. altkey = (text, category, 0)
  358. if registry.get(altkey):
  359. return
  360. registry[altkey] = 1
  361. elif action == "default":
  362. registry[key] = 1
  363. else:
  364. # Unrecognized actions are errors
  365. raise RuntimeError(
  366. "Unrecognized action (%r) in warnings.filters:\n %s" %
  367. (action, item))
  368. # Print message and context
  369. msg = WarningMessage(message, category, filename, lineno, source)
  370. _showwarnmsg(msg)
  371. class WarningMessage(object):
  372. _WARNING_DETAILS = ("message", "category", "filename", "lineno", "file",
  373. "line", "source")
  374. def __init__(self, message, category, filename, lineno, file=None,
  375. line=None, source=None):
  376. self.message = message
  377. self.category = category
  378. self.filename = filename
  379. self.lineno = lineno
  380. self.file = file
  381. self.line = line
  382. self.source = source
  383. self._category_name = category.__name__ if category else None
  384. def __str__(self):
  385. return ("{message : %r, category : %r, filename : %r, lineno : %s, "
  386. "line : %r}" % (self.message, self._category_name,
  387. self.filename, self.lineno, self.line))
  388. class catch_warnings(object):
  389. """A context manager that copies and restores the warnings filter upon
  390. exiting the context.
  391. The 'record' argument specifies whether warnings should be captured by a
  392. custom implementation of warnings.showwarning() and be appended to a list
  393. returned by the context manager. Otherwise None is returned by the context
  394. manager. The objects appended to the list are arguments whose attributes
  395. mirror the arguments to showwarning().
  396. The 'module' argument is to specify an alternative module to the module
  397. named 'warnings' and imported under that name. This argument is only useful
  398. when testing the warnings module itself.
  399. If the 'action' argument is not None, the remaining arguments are passed
  400. to warnings.simplefilter() as if it were called immediately on entering the
  401. context.
  402. """
  403. def __init__(self, *, record=False, module=None,
  404. action=None, category=Warning, lineno=0, append=False):
  405. """Specify whether to record warnings and if an alternative module
  406. should be used other than sys.modules['warnings'].
  407. For compatibility with Python 3.0, please consider all arguments to be
  408. keyword-only.
  409. """
  410. self._record = record
  411. self._module = sys.modules['warnings'] if module is None else module
  412. self._entered = False
  413. if action is None:
  414. self._filter = None
  415. else:
  416. self._filter = (action, category, lineno, append)
  417. def __repr__(self):
  418. args = []
  419. if self._record:
  420. args.append("record=True")
  421. if self._module is not sys.modules['warnings']:
  422. args.append("module=%r" % self._module)
  423. name = type(self).__name__
  424. return "%s(%s)" % (name, ", ".join(args))
  425. def __enter__(self):
  426. if self._entered:
  427. raise RuntimeError("Cannot enter %r twice" % self)
  428. self._entered = True
  429. self._filters = self._module.filters
  430. self._module.filters = self._filters[:]
  431. self._module._filters_mutated()
  432. self._showwarning = self._module.showwarning
  433. self._showwarnmsg_impl = self._module._showwarnmsg_impl
  434. if self._filter is not None:
  435. simplefilter(*self._filter)
  436. if self._record:
  437. log = []
  438. self._module._showwarnmsg_impl = log.append
  439. # Reset showwarning() to the default implementation to make sure
  440. # that _showwarnmsg() calls _showwarnmsg_impl()
  441. self._module.showwarning = self._module._showwarning_orig
  442. return log
  443. else:
  444. return None
  445. def __exit__(self, *exc_info):
  446. if not self._entered:
  447. raise RuntimeError("Cannot exit %r without entering first" % self)
  448. self._module.filters = self._filters
  449. self._module._filters_mutated()
  450. self._module.showwarning = self._showwarning
  451. self._module._showwarnmsg_impl = self._showwarnmsg_impl
  452. _DEPRECATED_MSG = "{name!r} is deprecated and slated for removal in Python {remove}"
  453. def _deprecated(name, message=_DEPRECATED_MSG, *, remove, _version=sys.version_info):
  454. """Warn that *name* is deprecated or should be removed.
  455. RuntimeError is raised if *remove* specifies a major/minor tuple older than
  456. the current Python version or the same version but past the alpha.
  457. The *message* argument is formatted with *name* and *remove* as a Python
  458. version (e.g. "3.11").
  459. """
  460. remove_formatted = f"{remove[0]}.{remove[1]}"
  461. if (_version[:2] > remove) or (_version[:2] == remove and _version[3] != "alpha"):
  462. msg = f"{name!r} was slated for removal after Python {remove_formatted} alpha"
  463. raise RuntimeError(msg)
  464. else:
  465. msg = message.format(name=name, remove=remove_formatted)
  466. warn(msg, DeprecationWarning, stacklevel=3)
  467. # Private utility function called by _PyErr_WarnUnawaitedCoroutine
  468. def _warn_unawaited_coroutine(coro):
  469. msg_lines = [
  470. f"coroutine '{coro.__qualname__}' was never awaited\n"
  471. ]
  472. if coro.cr_origin is not None:
  473. import linecache, traceback
  474. def extract():
  475. for filename, lineno, funcname in reversed(coro.cr_origin):
  476. line = linecache.getline(filename, lineno)
  477. yield (filename, lineno, funcname, line)
  478. msg_lines.append("Coroutine created at (most recent call last)\n")
  479. msg_lines += traceback.format_list(list(extract()))
  480. msg = "".join(msg_lines).rstrip("\n")
  481. # Passing source= here means that if the user happens to have tracemalloc
  482. # enabled and tracking where the coroutine was created, the warning will
  483. # contain that traceback. This does mean that if they have *both*
  484. # coroutine origin tracking *and* tracemalloc enabled, they'll get two
  485. # partially-redundant tracebacks. If we wanted to be clever we could
  486. # probably detect this case and avoid it, but for now we don't bother.
  487. warn(msg, category=RuntimeWarning, stacklevel=2, source=coro)
  488. # filters contains a sequence of filter 5-tuples
  489. # The components of the 5-tuple are:
  490. # - an action: error, ignore, always, default, module, or once
  491. # - a compiled regex that must match the warning message
  492. # - a class representing the warning category
  493. # - a compiled regex that must match the module that is being warned
  494. # - a line number for the line being warning, or 0 to mean any line
  495. # If either if the compiled regexs are None, match anything.
  496. try:
  497. from _warnings import (filters, _defaultaction, _onceregistry,
  498. warn, warn_explicit, _filters_mutated)
  499. defaultaction = _defaultaction
  500. onceregistry = _onceregistry
  501. _warnings_defaults = True
  502. except ImportError:
  503. filters = []
  504. defaultaction = "default"
  505. onceregistry = {}
  506. _filters_version = 1
  507. def _filters_mutated():
  508. global _filters_version
  509. _filters_version += 1
  510. _warnings_defaults = False
  511. # Module initialization
  512. _processoptions(sys.warnoptions)
  513. if not _warnings_defaults:
  514. # Several warning categories are ignored by default in regular builds
  515. if not hasattr(sys, 'gettotalrefcount'):
  516. filterwarnings("default", category=DeprecationWarning,
  517. module="__main__", append=1)
  518. simplefilter("ignore", category=DeprecationWarning, append=1)
  519. simplefilter("ignore", category=PendingDeprecationWarning, append=1)
  520. simplefilter("ignore", category=ImportWarning, append=1)
  521. simplefilter("ignore", category=ResourceWarning, append=1)
  522. del _warnings_defaults