1

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
cs95
  • 379,657
  • 97
  • 704
  • 746
David
  • 2,926
  • 1
  • 27
  • 61
  • Lambdas are just an alternative way to write functions. You can create a class that behaves as a function and is itself falsey, but it would not be a lambda function. – khelwood Mar 28 '19 at 08:57
  • So functions are always evaluated as true? – David Mar 28 '19 at 09:01
  • Functions are truthy by default, like nearly everything. You can create something customised, but it wouldn't be a lambda function. – khelwood Mar 28 '19 at 09:04

3 Answers3

3

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.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
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:

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
khelwood
  • 55,782
  • 14
  • 81
  • 108
1

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.

cs95
  • 379,657
  • 97
  • 704
  • 746