You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

inspect.py 1.7KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import inspect
  2. def get_func_args(func):
  3. sig = inspect.signature(func)
  4. return [
  5. arg_name for arg_name, param in sig.parameters.items()
  6. if param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
  7. ]
  8. def get_func_full_args(func):
  9. """
  10. Return a list of (argument name, default value) tuples. If the argument
  11. does not have a default value, omit it in the tuple. Arguments such as
  12. *args and **kwargs are also included.
  13. """
  14. sig = inspect.signature(func)
  15. args = []
  16. for arg_name, param in sig.parameters.items():
  17. name = arg_name
  18. # Ignore 'self'
  19. if name == 'self':
  20. continue
  21. if param.kind == inspect.Parameter.VAR_POSITIONAL:
  22. name = '*' + name
  23. elif param.kind == inspect.Parameter.VAR_KEYWORD:
  24. name = '**' + name
  25. if param.default != inspect.Parameter.empty:
  26. args.append((name, param.default))
  27. else:
  28. args.append((name,))
  29. return args
  30. def func_accepts_kwargs(func):
  31. return any(
  32. p for p in inspect.signature(func).parameters.values()
  33. if p.kind == p.VAR_KEYWORD
  34. )
  35. def func_accepts_var_args(func):
  36. """
  37. Return True if function 'func' accepts positional arguments *args.
  38. """
  39. return any(
  40. p for p in inspect.signature(func).parameters.values()
  41. if p.kind == p.VAR_POSITIONAL
  42. )
  43. def method_has_no_args(meth):
  44. """Return True if a method only accepts 'self'."""
  45. count = len([
  46. p for p in inspect.signature(meth).parameters.values()
  47. if p.kind == p.POSITIONAL_OR_KEYWORD
  48. ])
  49. return count == 0 if inspect.ismethod(meth) else count == 1
  50. def func_supports_parameter(func, parameter):
  51. return parameter in inspect.signature(func).parameters