Python使用元组中大于所需参数量的参数调用函数

2024-10-03 09:15:23 发布

您现在位置:Python中文网/ 问答频道 /正文

补充说明:

我想要达到的是

call(function,(*args,*toomanyargs)) == (function(*args),*toomanyargs)
call(function_with_varargs,(*args))) == (function_with_varargs(*args))

有什么方法可以达到这个目的


Tags: 方法目的withargsfunctioncallvarargstoomanyargs
2条回答

通过访问.__code__.co_argcount属性,可以了解函数接受多少位置参数:

>>> function = lambda a, b, c: a+b+c
>>> function.__code__.co_argcount
3

但是,这并不尊重varargs:

>>> function = lambda *a: a
>>> function.__code__.co_argcount
0

所以更可靠的解决方案是使用^{}

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,)

一种方法是使用locals()Check the number of parameters passed in Python functionhttps://docs.python.org/3/library/functions.html#locals),并在每个函数体中进行一些数学运算,以计算出剩余(未使用)的参数数。然后可以返回一个结果,其中包含一个未使用参数的元组

相关问题 更多 >