fork download
  1. import functools
  2.  
  3. funcs = {"Add": lambda a, b: a + b,
  4. "Subtract": lambda a, b: a - b,
  5. "Multiply": lambda a, b: a * b,
  6. "Divide": lambda a, b: a / b}
  7.  
  8. def do_operation(name, func, a, b):
  9. print(name, ":", func(a, b))
  10.  
  11. # As you can see, putting functions into a list like this does not work; it just calls the last function repeatedly.
  12. # This is because all of the lambdas are pointing to the same location for "name" and "func", which are overwritten
  13. # on each iteration until they have the values of the last item iterated.
  14. exec_list = []
  15. for name, func in funcs.items():
  16. exec_list.append(lambda: do_operation(name, func, 3, 5))
  17.  
  18. for e in exec_list:
  19. e()
  20.  
  21.  
  22. print()
  23. # You can avoid this by using the 'functools' library, which also offers a more comprehensible syntax, akin to a C++
  24. # 'std::bind' one.
  25. exec_list = []
  26. for name, func in funcs.items():
  27. exec_list.append(functools.partial(do_operation, name, func, 3, 5))
  28.  
  29. for e in exec_list:
  30. e()
Success #stdin #stdout 0.02s 27712KB
stdin
Standard input is empty
stdout
Subtract : -2
Subtract : -2
Subtract : -2
Subtract : -2

Divide : 0.6
Multiply : 15
Add : 8
Subtract : -2