How to check that variable is a lambda function

前端 未结 2 1282
感情败类
感情败类 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 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__
    # 
    

    So, we put together both these checks like this

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

    As @Blckknght suggests, if you want to check if the object is just a callable object, then you can use the builtin callable function.

提交回复
热议问题