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 lambd
If you prefer the typing
module, use Callable
:
In [1]: from typing import Callable
In [2]: isinstance(lambda: None, Callable)
Out[2]: True
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.