Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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 2.2KB

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