Reuseable iterators - which is better?

Diez B. Roggisch deets at nospam.web.de
Fri Jun 23 09:03:34 EDT 2006


zefciu schrieb:
> In the tutorial there is an example iterator class that revesrses the
> string given to the constructor.  The problem is that this class works
> only once, unlike built-in types like string.  How to modify it that it
> could work several times?  I have tried two approaches.  They both work,
> but which of them is stylistically better?
> 
> class Reverse: #original one
>     "Iterator for looping over a sequence backwards"
>     def __init__(self, data):
>         self.data = data
>         self.index = len(data)
>     def __iter__(self):
>         return self
>     def next(self):
>         if self.index == 0:
>             raise StopIteration
>         self.index = self.index - 1
>         return self.data[self.index]
> 
> class Reverse: #1st approach
>     "Reuseable Iterator for looping over a sequence backwards"
>     def __init__(self, data):
>         self.data = data
>         self.index = len(data)
>     def __iter__(self):
>         return self
>     def next(self):
>         if self.index == 0:
>             	self.index = len(self.data) #Reset when previous 								#
> iterator goes out
> 		raise StopIteration
>         self.index = self.index - 1
>         return self.data[self.index]
> 
> class Reverse: #2nd approach
>     "Reuseable Iterator for looping over a sequence backwards"
>     def __init__(self, data):
>         self.data = data
>     def __iter__(self):
> 	self.index = len(self.data) #Reset as a part of iterator 							# creation
>         return self
>     def next(self):
>         if self.index == 0:
>             raise StopIteration
>         self.index = self.index - 1
>         return self.data[self.index]



None. You don't reuse iterators! In the actualy example, reusage is 
possible due to the whole data being known & available. But there might 
be cases where this isn't possible - e.g. fetching data from a remote 
location which is too large to fit into memory for re-iteration.

So generally speakiing, if you need an iterator, construct it.

Regards,

Diez



More information about the Python-list mailing list