如何检查变量是否为lambda函数 [英] How to check that variable is a lambda function
问题描述
我正在一个项目中,该项目包含几个模块.为简化问题,有一些变量x.有时它可能是int或float或list.但这可能是lambda函数,应该以不同的方式对待.如何检查变量x是lambda?
I'm working on a project, which contains several modules. Simplifying the problem, there is some variable x. Sometimes it may be int or float or list. But it may be a lambda function, and should be treated in different way. How to check that variable x is a lambda?
例如
>>> x = 3
>>> type(x)
<type 'int'>
>>> type(x) is int
True
>>> x = 3.4
>>> type(x)
<type 'float'>
>>> type(x) is float
True
>>> x = lambda d:d*d
>>> type(x)
<type 'function'>
>>> type(x) is lambda
File "<stdin>", line 1
type(x) is lambda
^
SyntaxError: invalid syntax
>>> type(x) is function
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'function' is not defined
>>>
推荐答案
您需要使用 types.LambdaType
或types.FunctionType
来确保该对象是像这样的功能对象
You need to use types.LambdaType
or types.FunctionType
to make sure that the object is a function object like this
x = lambda d:d*d
import types
print type(x) is types.LambdaType
# True
print isinstance(x, types.LambdaType)
# True
,然后您还需要检查名称,以确保我们正在处理这样的lambda函数
and then you need to check the name as well to make sure that we are dealing with a lambda function, like this
x = lambda x: None
def y(): pass
print y.__name__
# y
print x.__name__
# <lambda>
所以,我们将这两个检查放在一起
So, we put together both these checks like this
def is_lambda_function(obj):
return isinstance(obj, types.LambdaType) and obj.__name__ == "<lambda>"
正如@Blckknght所建议的,如果要检查对象是否只是可调用对象,则可以使用内置的
As @Blckknght suggests, if you want to check if the object is just a callable object, then you can use the builtin callable
function.
这篇关于如何检查变量是否为lambda函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!