inspect.py 4.4 KB

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