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?
For example
>>> 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
>>>
You need to use
types.LambdaType
ortypes.FunctionType
to make sure that the object is a function object like thisand then you need to check the name as well to make sure that we are dealing with a lambda function, like this
So, we put together both these checks like this
As @Blckknght suggests, if you want to check if the object is just a callable object, then you can use the builtin
callable
function.