FZJ-INM1-BDA / siibra-python

Software interfaces for interacting with brain atlases - Python client
Apache License 2.0
46 stars 8 forks source link

fix: python closure is weird #587

Closed xgui3783 closed 2 months ago

xgui3783 commented 2 months ago

fix closure bug

see a simplified reproduction:


from concurrent.futures import ThreadPoolExecutor
from functools import partial

def call_fn(fn):
    fn()

def main():
    arr = []
    for i in range(10):
        def fn(j):
            print(j)
        arr.append(
            partial(fn, i)
        )

    with ThreadPoolExecutor(4) as ex:
        list(ex.map(
            call_fn,
            arr
        ))

def faulty():

    arr = []
    for i in range(10):
        def fn():
            print(i)
        arr.append(fn)

    with ThreadPoolExecutor(4) as ex:
        list(ex.map(
            call_fn,
            arr
        ))

if __name__ == "__main__":
    print("faulty")
    faulty()
    print("main")
    main()

prints

faulty
9
9
9
9
9
9
9
9
9
9
main
0
1
3
4
5
2
9
7
8
6