I never really understood why
yield from was useful. Last weekend, I wanted to use Python 3.5's new
os.scandir to explore a directory (and its subdirectories). Tragically,
os.scandir is not recursive, and I find
os.walks 3-tuple values obnoxious.
Lo and behold, while I was trying to implement a recursive version of
yield from use just popped right out!
[code lang=python] import os def rscandir(path): for entry in os.scandir(path): yield entry if entry.is_dir(): yield from rscandir(entry.path) [/code]
That's it! I have to admit that reads wonderfully. The Legacy Python (aka Python 2.x) alternative is quite a bit uglier:
[code lang=python] import os def rscandir(path): for p in os.listdir(path): yield p if os.path.isdir(p): for q in rscandir(p): yield q [/code]
Yuck. So, yet again: time to move away from Legacy Python! ;)