Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that variable is a lambda function

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
>>> 
like image 569
rth Avatar asked May 25 '14 05:05

rth


1 Answers

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.

like image 99
thefourtheye Avatar answered Oct 06 '22 23:10

thefourtheye