Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/traitlets/utils/warnings.py: 28%
32 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-20 06:09 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-20 06:09 +0000
1from __future__ import annotations
3import inspect
4import os
5import typing as t
6import warnings
9def warn(msg: str, category: t.Any, *, stacklevel: int, source: t.Any = None) -> None:
10 """Like warnings.warn(), but category and stacklevel are required.
12 You pretty much never want the default stacklevel of 1, so this helps
13 encourage setting it explicitly."""
14 warnings.warn(msg, category=category, stacklevel=stacklevel, source=source)
17def deprecated_method(method: t.Any, cls: t.Any, method_name: str, msg: str) -> None:
18 """Show deprecation warning about a magic method definition.
20 Uses warn_explicit to bind warning to method definition instead of triggering code,
21 which isn't relevant.
22 """
23 warn_msg = f"{cls.__name__}.{method_name} is deprecated in traitlets 4.1: {msg}"
25 for parent in inspect.getmro(cls):
26 if method_name in parent.__dict__:
27 cls = parent
28 break
29 # limit deprecation messages to once per package
30 package_name = cls.__module__.split(".", 1)[0]
31 key = (package_name, msg)
32 if not should_warn(key):
33 return
34 try:
35 fname = inspect.getsourcefile(method) or "<unknown>"
36 lineno = inspect.getsourcelines(method)[1] or 0
37 except (OSError, TypeError) as e:
38 # Failed to inspect for some reason
39 warn(
40 warn_msg + ("\n(inspection failed) %s" % e),
41 DeprecationWarning,
42 stacklevel=2,
43 )
44 else:
45 warnings.warn_explicit(warn_msg, DeprecationWarning, fname, lineno)
48_deprecations_shown = set()
51def should_warn(key: t.Any) -> bool:
52 """Add our own checks for too many deprecation warnings.
54 Limit to once per package.
55 """
56 env_flag = os.environ.get("TRAITLETS_ALL_DEPRECATIONS")
57 if env_flag and env_flag != "0":
58 return True
60 if key not in _deprecations_shown:
61 _deprecations_shown.add(key)
62 return True
63 else:
64 return False