Skip to content Skip to sidebar Skip to footer

Can A Lambda Function Have A Bool Value Of False?

Is it possible, that a lambda function can return a False value, when given to the bool function? This lambda function for example yields True: bool(lambda x:[]) True

Solution 1:

no, you can not do that with pure lambda expressions.

lambdax:[]

is of the type

<class'function'>

and as the documentation says, there is nothing of that type that will turn out to be falsy - so it will come out truthy; i.e. passing it to bool will return True.

if you want a funtion (a callable) that evaluates to False i would exactly do what is described in khelwood's answer.

Solution 2:

Lambdas are just an alternative way to write functions. Like nearly everything, they are truthy by default. You can create a class whose instances behave as functions and are themselves falsey. They wouldn't be lambda functions, but there's no reason that should be a problem.

For instance:

classFalseyFunction:
    def__init__(self, func):
        self.func = func
    def__call__(self, *args, **kwargs):
        return self.func(*args, **kwargs)
    def__bool__(self):
        returnFalse>>> f = FalseyFunction(lambda x:[])
>>> f(0)
[]
>>> bool(f)
False

Solution 3:

Only the objects specified in Truth Value Testing in the docs, as well as objects whose __bool__ or __len__ methods return False or 0 respectively, are falsy objects.

Everything else (yes, this includes any lambda) is truthy.

Post a Comment for "Can A Lambda Function Have A Bool Value Of False?"