arguments.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. # The inspect.formatargspec() function was dropped in Python 3.11 but we need
  2. # need it for when constructing signature changing decorators based on result of
  3. # inspect.getargspec() or inspect.getfullargspec(). The code here implements
  4. # inspect.formatargspec() base on Parameter and Signature from inspect module,
  5. # which were added in Python 3.6. Thanks to Cyril Jouve for the implementation.
  6. try:
  7. from inspect import Parameter, Signature
  8. except ImportError:
  9. from inspect import formatargspec
  10. else:
  11. def formatargspec(args, varargs=None, varkw=None, defaults=None,
  12. kwonlyargs=(), kwonlydefaults={}, annotations={}):
  13. if kwonlydefaults is None:
  14. kwonlydefaults = {}
  15. ndefaults = len(defaults) if defaults else 0
  16. parameters = [
  17. Parameter(
  18. arg,
  19. Parameter.POSITIONAL_OR_KEYWORD,
  20. default=defaults[i] if i >= 0 else Parameter.empty,
  21. annotation=annotations.get(arg, Parameter.empty),
  22. ) for i, arg in enumerate(args, ndefaults - len(args))
  23. ]
  24. if varargs:
  25. parameters.append(Parameter(varargs, Parameter.VAR_POSITIONAL))
  26. parameters.extend(
  27. Parameter(
  28. kwonlyarg,
  29. Parameter.KEYWORD_ONLY,
  30. default=kwonlydefaults.get(kwonlyarg, Parameter.empty),
  31. annotation=annotations.get(kwonlyarg, Parameter.empty),
  32. ) for kwonlyarg in kwonlyargs
  33. )
  34. if varkw:
  35. parameters.append(Parameter(varkw, Parameter.VAR_KEYWORD))
  36. return_annotation = annotations.get('return', Signature.empty)
  37. return str(Signature(parameters, return_annotation=return_annotation))