mardi 28 mai 2019

Lambda function not executed in dictionary with "if-else" values

I'm trying to define different lambda functions in a Python dictionary. I know that probably the best thing to do is to have only one lambda function in the "value" part of the dictionary item and manage subcases inside the definded function, but however I don't understand why this code is not working like I want:

def a():
    print('a')


def b():
    print('b')


def c():
    print('c')


def d():
    print('d')

condition = True

dict = {
        'foo': lambda: a() if condition else lambda: b(),
        'bar': lambda: c() if condition else lambda: d()
    }.get('foo', lambda: print('not found'))()

if we set condition = False, the code will not print b, it will not do anything (it seems)..why? Instead if we try with a dictionary without lambda function definitions, it seems to work as I expect:

dict2 = {
        'foo': 4 if condition else 5,
        'bar': 6 if condition else 7
    }.get('foo', -1)

dict2 will be 5.

Someone can explain to me why the definition returned in the first case is not working?

Thank you in advance!

Aucun commentaire:

Enregistrer un commentaire