Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: python closure is weird #587

Merged
merged 2 commits into from
Apr 17, 2024
Merged

Conversation

xgui3783
Copy link
Member

@xgui3783 xgui3783 commented Apr 17, 2024

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

@xgui3783 xgui3783 requested a review from AhmetNSimsek April 17, 2024 08:36
@xgui3783 xgui3783 merged commit 23238ac into maint_featurenames_and_cfdata Apr 17, 2024
13 of 26 checks passed
@xgui3783 xgui3783 deleted the fix_closure branch April 17, 2024 10:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants