0

I use a python package which has a function should bind function(function name/address).
I create a config file and want to bind lots of functions in a loop. But find a problem like this:

def cus_print(func):
    func()


def main():
    a = []
    for i in range(2):
        a.append(lambda: print(i))

    for each in a:
        cus_print(each)

if __name__ == '__main__':
    main()

result

1
1

The easy way to solve problem?

  • use [`a.append(lambda i=i: print(i))`](https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result) – mozway Sep 23 '22 at 08:13
  • Thinks. After reading [Lambda in a loop [duplicate]], I find the answer. – SuiFengPiaoYang Sep 29 '22 at 02:06

0 Answers0