Why does python asyncio loop.call_soon overwrite data?

后端 未结 3 1585
暗喜
暗喜 2021-01-27 11:51

I created a hard to track down bug in our code, but do not understand why it occurs. The problem occurs when pushing the same async function multiple times to call soon. It d

3条回答
  •  天命终不由人
    2021-01-27 12:41

    Your problem actually has nothing to do with asyncio. The k and v in lambda: asyncio.ensure_future(self.do_something(k, v)) still refer to the variables in your outer scope. Their values change by the time you call your function:

    i = 1
    f = lambda: print(i)
    
    f()  # 1
    i = 2
    f()  # 2
    

    A common solution is to define your function and (ab)use default arguments to create a variable local to your function that holds the value of i at the time the function was created, not called:

    i = 1
    f = lambda i=i: print(i)
    
    f()  # 1
    i = 2
    f()  # 1
    

    You can use f = lambda x=i: print(x) if the naming confuses you.

提交回复
热议问题