自封装函数参数检索
import inspect class CheckParams: def __init__(self, fn): self.fn_params = inspect.signature(fn).parameters @property def get_required_kw_args(self): # 必须存在的关键字参数 args = [] for name, param in self.fn_params.items(): if param.kind == inspect.Parameter.KEYWORD_ONLY and param.default == inspect.Parameter.empty: args.append(name) return tuple(args) @property def get_named_kw_args(self): # 有名字的关键字参数 args = [] for name, param in self.fn_params.items(): if param.kind == inspect.Parameter.KEYWORD_ONLY: args.append(name) return tuple(args) @property def get_required_args(self): # 位置参数(必须存在的) args = [] for name, params in self.fn_params.items(): if params.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD: args.append(name) return tuple(args) def foo(a, b, *args, c, request, d=None, e, **kwargs): pass checker = CheckParams(foo) print(checker.get_named_kw_args) # ('c', 'request', 'd', 'e') print(checker.get_required_args) # ('a', 'b') print(checker.get_required_kw_args) # ('a', 'b')