Debian Codegraph @

lib-python/3/warnings.py

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