import inspect
def call(function, args):
# count the positional arguments
params = inspect.signature(function).parameters.values()
if any(param.kind == inspect.Parameter.VAR_POSITIONAL for param in params):
arg_count = len(args)
else:
POSITIONAL_KINDS = {inspect.Parameter.POSITIONAL_ONLY,
inspect.Parameter.POSITIONAL_OR_KEYWORD}
arg_count = sum(1 for param in params if param.kind in POSITIONAL_KINDS)
# take as many arguments as the function accepts
remainder = args[arg_count:]
args = args[:arg_count]
return (function(*args),) + tuple(remainder)
演示:
>>> function = lambda a, b, c: a+b+c
>>> args = range(5)
>>> call(function, args))
(3, 3, 4)
>>>
>>> function = lambda a, b, c, *d: a+b+c
>>> args = range(5)
>>> call(function, args))
(3,)
通过访问
.__code__.co_argcount
属性,可以了解函数接受多少位置参数:但是,这并不尊重varargs:
所以更可靠的解决方案是使用^{} :
演示:
一种方法是使用
locals()
(Check the number of parameters passed in Python functionhttps://docs.python.org/3/library/functions.html#locals),并在每个函数体中进行一些数学运算,以计算出剩余(未使用)的参数数。然后可以返回一个结果,其中包含一个未使用参数的元组相关问题 更多 >
编程相关推荐