Debian Codegraph @

django/utils/inspect.py

raw
1 import functools
2 import inspect
3 import threading
4 from contextlib import contextmanager
5
6 from django.utils.version import PY314
7
8 if PY314:
9 import annotationlib
10
11 lock = threading.Lock()
12 safe_signature_from_callable = functools.partial(
13 inspect._signature_from_callable,
14 annotation_format=annotationlib.Format.FORWARDREF,
15 )
16
17
18 @functools.lru_cache(maxsize=512)
19 def _get_func_parameters(func, remove_first):
20 parameters = tuple(signature(func).parameters.values())
21 if remove_first:
22 parameters = parameters[1:]
23 return parameters
24
25
26 def _get_callable_parameters(meth_or_func):
27 is_method = inspect.ismethod(meth_or_func)
28 func = meth_or_func.__func__ if is_method else meth_or_func
29 return _get_func_parameters(func, remove_first=is_method)
30
31
32 ARG_KINDS = frozenset(
33 {
34 inspect.Parameter.POSITIONAL_ONLY,
35 inspect.Parameter.KEYWORD_ONLY,
36 inspect.Parameter.POSITIONAL_OR_KEYWORD,
37 }
38 )
39
40
41 def get_func_args(func):
42 params = _get_callable_parameters(func)
43 return [param.name for param in params if param.kind in ARG_KINDS]
44
45
46 def get_func_full_args(func):
47 """
48 Return a list of (argument name, default value) tuples. If the argument
49 does not have a default value, omit it in the tuple. Arguments such as
50 *args and **kwargs are also included.
51 """
52 params = _get_callable_parameters(func)
53 args = []
54 for param in params:
55 name = param.name
56 # Ignore 'self'
57 if name == "self":
58 continue
59 if param.kind == inspect.Parameter.VAR_POSITIONAL:
60 name = "*" + name
61 elif param.kind == inspect.Parameter.VAR_KEYWORD:
62 name = "**" + name
63 if param.default != inspect.Parameter.empty:
64 args.append((name, param.default))
65 else:
66 args.append((name,))
67 return args
68
69
70 def func_accepts_kwargs(func):
71 """Return True if function 'func' accepts keyword arguments **kwargs."""
72 return any(p for p in _get_callable_parameters(func) if p.kind == p.VAR_KEYWORD)
73
74
75 def func_accepts_var_args(func):
76 """
77 Return True if function 'func' accepts positional arguments *args.
78 """
79 return any(p for p in _get_callable_parameters(func) if p.kind == p.VAR_POSITIONAL)
80
81
82 def method_has_no_args(meth):
83 """Return True if a method only accepts 'self'."""
84 count = len([p for p in _get_callable_parameters(meth) if p.kind in ARG_KINDS])
85 return count == 0 if inspect.ismethod(meth) else count == 1
86
87
88 def func_supports_parameter(func, name):
89 return any(param.name == name for param in _get_callable_parameters(func))
90
91
92 @contextmanager
93 def lazy_annotations():
94 """
95 inspect.getfullargspec eagerly evaluates type annotations. To add
96 compatibility with Python 3.14+ deferred evaluation, patch the module-level
97 helper to provide the annotation_format that we are using elsewhere.
98
99 This private helper could be removed when there is an upstream solution for
100 https://github.com/python/cpython/issues/141560.
101
102 This context manager is not reentrant.
103 """
104 if not PY314:
105 yield
106 return
107 with lock:
108 original_helper = inspect._signature_from_callable
109 inspect._signature_from_callable = safe_signature_from_callable
110 try:
111 yield
112 finally:
113 inspect._signature_from_callable = original_helper
114
115
116 def signature(obj):
117 """
118 A wrapper around inspect.signature that leaves deferred annotations
119 unevaluated on Python 3.14+, since they are not used in our case.
120 """
121 if PY314:
122 return inspect.signature(obj, annotation_format=annotationlib.Format.FORWARDREF)
123 else:
124 return inspect.signature(obj)