How to check that variable is a lambda function
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
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>"
As @Blckknght suggests, if you want to check if the object is just a callable object, then you can use the builtin callable
function.
If you prefer the typing
module, use Callable
:
In [1]: from typing import Callable
In [2]: isinstance(lambda: None, Callable)
Out[2]: True