Python closure not working as expected

前端 未结 2 1102
北海茫月
北海茫月 2020-12-03 12:01

When I run the following script, both lambda\'s run os.startfile() on the same file -- junk.txt. I would expect each lambda to use the value \"f\" was set to when the lambd

2条回答
  •  温柔的废话
    2020-12-03 12:27

    One way is to do this:

    def main():
        files = [r'C:\_local\test.txt', r'C:\_local\junk.txt']
        funcs = []
        for f in files:
            # create a new lambda and store the current `f` as default to `path`
            funcs.append(lambda path=f: os.stat(path))
        print funcs
    
        # calling the lambda without a parameter uses the default value
        funcs[0]() 
        funcs[1]()
    

    Otherwise f is looked up when the function is called, so you get the current (after the loop) value.

    Ways I like better:

    def make_statfunc(f):
        return lambda: os.stat(f)
    
    for f in files:
        # pass the current f to another function
        funcs.append(make_statfunc(f))
    

    or even (in python 2.5+):

    from functools import partial
    for f in files:
        # create a partially applied function
        funcs.append(partial(os.stat, f))
    

提交回复
热议问题