How to check that variable is a lambda function

Question:

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
>>> 
Asked By: rth

||

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.

Answered By: thefourtheye

If you prefer the typing module, use Callable:

In [1]: from typing import Callable
In [2]: isinstance(lambda: None, Callable)
Out[2]: True
Answered By: crypdick

Can consider the following:

type(x) == type(lambda x:x)
Answered By: user21445566
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.