[Tutor] recursive generator
Stefan Behnel
stefan_ml at behnel.de
Sun Mar 7 15:49:21 CET 2010
Steven D'Aprano, 07.03.2010 14:27:
> On Sun, 7 Mar 2010 11:58:05 pm spir wrote:
>> def __iter__(self):
>> ''' Iteration on (key,value) pairs. '''
>> print '*',
>> if self.holdsEntry:
>> yield (self.key,self.value)
>> for child in self.children:
>> print "<",
>> child.__iter__()
>> print ">",
>> raise StopIteration
>
>
> __iter__ should be an ordinary function, not a generator. Something like
> this should work:
>
> # Untested.
> def __iter__(self):
> ''' Iteration on (key,value) pairs. '''
> def inner():
> print '*', # Side effects bad...
> if self.holdsEntry:
> yield (self.key,self.value)
> for child in self.children:
> print "<",
> child.__iter__()
> print ">",
> raise StopIteration
> return inner()
That's just an unnecessarily redundant variation on the above. It's
perfectly ok if __iter__() is a generator method.
Stefan
More information about the Tutor
mailing list