recursion - Does Python allow a recursive __iter__ function? -


i'm trying write __iter__ function should traverse directory recursively (including subdirectories), , since structure arbitrary, thought recursive function way go. isn't working.

here's have:

class dummy(object):      def __init__(self, directory):         self.directory = directory      def _iterate_on_dir(self, path):         '''         internal helper recursive function.         '''         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 recursive call ignored.

how can accomplish this?

right when recursively call _iterate_on_dir you're creating generator object, not iterating on it.

the fix: self._iterate_on_dir(full_path) should become:

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

if you're using python 3, can replace with:

yield self._iterate_on_dir(full_path) 

Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -