问题描述
我想知道是否有一种方法(给定包含lambda的变量)确定其中包含的lambda的参数数量.原因是,我希望根据参数的数量有条件地调用函数.
I am wondering if there is a way to determine (given a variable containing a lambda) the number of parameters the lambda it contains. The reason being, I wish to call a function conditionally dependent on the number of parameters.
我在寻找什么
def magic_lambda_parameter_counting_function(lambda_function):
"""Returns the number of parameters in lambda_function
Args:
lambda_function - A lambda of unknown number of parameters
"""
所以我可以做类似的事情
So I can do something like
def my_method(lambda_function):
# ...
# (say I have variables i and element)
parameter_count = magic_lambda_parameter_counting_function(lambda_function)
if parameter_count == 1:
lambda_function(i)
elif parameter_count == 2:
lambda_function(i, element)
推荐答案
我跳过了有关如何计算参数的部分,因为我不知道您想如何考虑varargs和关键字.但这应该可以帮助您入门.
I'm skipping the part about how to count the arguments, because I don't know how you want to consider varargs and keywords. But this should get you started.
>>> import inspect
>>> foo = lambda x, y, z: x + y + z
>>> inspect.getargspec(foo)
ArgSpec(args=['x', 'y', 'z'], varargs=None, keywords=None, defaults=None)
听起来像 inspect.getargspec早于 Python 3(感谢@JeffHeaton).推荐的解决方案使用 inspect.signature .结果的.parameters
成员包含各种结构,具体取决于相关函数的参数排列方式,但是我正在匹配上面Python 2示例中的函数.
It sounds like inspect.getargspec is deprecated as of Python 3 (thanks to @JeffHeaton). The recommend solution uses inspect.signature. The .parameters
member of the result contains a variety of structures depending on the arrangement of parameters to the function in question, but I'm matching my function from the Python 2 example above.
>>> import inspect
>>> foo = lambda x, y, z: x + y + z
>>> inspect.signature(foo).parameters
mappingproxy(OrderedDict([('x', <Parameter "x">), ('y', <Parameter "y">), ('z', <Parameter "z">)]))
这篇关于确定Lambda中的参数数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!