Python Forum

Full Version: Multiple lambda functions in zipped list not executing
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to execute multiple functions that have different arguments when a condition is satisfied, but I never get any of them executed with the correct arguments:

conditions = [condition1, condition2, condition3]
functions = [lambda: self._f(), lambda x: self._f2(a), lambda x,y: self._f3(b, c)]

for condition, function in zip(conditions, functions):
    if condition:
        function() # execute the proper function with 0, 1 or 2 arguments
        break

def _f():
    print('function1 with no arguments')

def _f2(x):
    print(f'function2 with one argument {x}')

def _f3(x, y):
    print(f'function2 with two arguments {x} and {y}')
But when the condition is satisfied, the corresponding function is executed with wrong parameters so it fails and raises an error. What I am doing wrong??

Thank you in advance!!

Ok, I just had to delete the lambda arguments and works fine:

From:

functions = [lambda: self._f(), lambda x: self._f2(a), lambda x,y: self._f3(b, c)]
to:
functions = [lambda: self._f(), lambda: self._f2(a), lambda: self._f3(b, c)]