How to check that variable is a lambda function

前端 未结 2 1263
感情败类
感情败类 2021-01-17 11:27

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

相关标签:
2条回答
  • 2021-01-17 11:45

    If you prefer the typing module, use Callable:

    In [1]: from typing import Callable
    In [2]: isinstance(lambda: None, Callable)
    Out[2]: True
    
    0 讨论(0)
  • 2021-01-17 12:06

    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.

    0 讨论(0)
提交回复
热议问题