Does Python provide a __iter__ recursive function?

I am trying to write a function __iter__that must pass recursively (including subdirectories), and since its structure is arbitrary, I thought that a recursive function would be a way. But it does not work.

Here is 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 operators printshowed me that a recursive call is simply ignored.

How can i do this?

+4
source share
1 answer

Right now, when you recursively call _iterate_on_dir, you are just creating a generator object, not iterating it.

Correction: self._iterate_on_dir(full_path) should become:

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

Python 3, :

yield from self._iterate_on_dir(full_path)
+5

Source: https://habr.com/ru/post/1584600/


All Articles