How to check that a variable is a lambda function

I am working on a project that contains several modules. To simplify the problem, there is some variable x. Sometimes it can be int or float or list. But it can be a lambda function, and it should be considered in different ways. How to check that the variable x is lambda?

for instance

>>> 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
>>> 
+4
source share
1 answer

You need to use types.LambdaTypeor types.FunctionTypeto make sure the object is a functional 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 also check the name to make sure that we are dealing with a lambda function, for example

x = lambda x: None
def y(): pass
print y.__name__
# y
print x.__name__
# <lambda>

So, we have collected both of these checks, such as

def is_lambda_function(obj):
    return isinstance(obj, types.LambdaType) and obj.__name__ == "<lambda>"

@Blckknght, , , callable .

+13

Source: https://habr.com/ru/post/1541922/


All Articles