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
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
no, you can not do that with pure lambda
expressions.
lambda x:[]
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.
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:
class FalseyFunction:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
def __bool__(self):
return False
>>> f = FalseyFunction(lambda x:[])
>>> f(0)
[]
>>> bool(f)
False
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.