简体   繁体   English

Python是否允许递归的__iter__函数?

[英]Does Python allow a recursive __iter__ function?

I'm trying to write an __iter__ function that should traverse a directory recursively (including subdirectories), and since its structure is arbitrary, I thought a recursive function would be the way to go. 我正在尝试编写一个__iter__函数,该函数应该递归遍历一个目录(包括子目录),并且由于它的结构是任意的,我认为递归函数将是最佳选择。 But it isn't working. 但它没有用。

Here's what I have: 这就是我所拥有的:

class Dummy(object):

    def __init__(self, directory):
        self.directory = directory

    def _iterate_on_dir(self, path):
        '''
        Internal helper recursive function.
        '''
        for filename in os.listdir(path):
            full_path = os.path.join(path, filename)
            if os.path.isdir(full_path):
                self._iterate_on_dir(full_path)
            else:
                yield full_path

    def __iter__(self):
        '''
        Yield filenames
        '''
        return self._iterate_on_dir(self.directory)

Some print statements showed me that the recursive call is simply ignored. 一些print语句告诉我,递归调用被简单地忽略了。

How can I accomplish this? 我怎么能做到这一点?

Right now when you recursively call _iterate_on_dir you're just creating a generator object, not actually iterating over it. 现在当你递归调用_iterate_on_dir你只是创建一个生成器对象,而不是实际迭代它。

The fix: self._iterate_on_dir(full_path) should become: 修复: self._iterate_on_dir(full_path)应该变为:

for thing in self._iterate_on_dir(full_path):
    yield thing

If you're using Python 3, you can replace that with: 如果您使用的是Python 3,则可以将其替换为:

yield from self._iterate_on_dir(full_path)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM