Yield in a recursive function

后端 未结 9 506
独厮守ぢ
独厮守ぢ 2021-01-30 10:49

I am trying to do something to all the files under a given path. I don\'t want to collect all the file names beforehand then do something with them, so I tried this:

<         


        
9条回答
  •  梦如初夏
    2021-01-30 11:00

    Iterators do not work recursively like that. You have to re-yield each result, by replacing

    explore(path)
    

    with something like

    for value in explore(path):
        yield value
    

    Python 3.3 added the syntax yield from X, as proposed in PEP 380, to serve this purpose. With it you can do this instead:

    yield from explore(path)
    

    If you're using generators as coroutines, this syntax also supports the use of generator.send() to pass values back into the recursively-invoked generators. The simple for loop above would not.

提交回复
热议问题