recognizing empty iterators

Alan Kennedy alanmk at hotmail.com
Wed Jul 23 08:21:15 EDT 2003


Daniel Dittmar wrote:

> It shouldn't be too difficult to write an iterator wrapper class
> that does exactly what you want (not tested):
> 
> class IteratorWrapper:
>     def __init__ (self, iterArg):
>         iterArg = iter (iterArg)
>         try:
>             self.firstElement = iterArg.next ()
>             self.isEmpty = false
>             self.next = self.returnFirstElement
>             self.baseIter = iterArg
>         except StopIteration:
>             self.isEmpty = true
>             self.next = self.throwStopIteration
> 
>     def returnFirstElement (self):
>         self.next = self.baseIter.next
>         return self.firstElement
> 
>     def throwStopIteration (self):
>         throw StopIteration
          ^^^^^

Ahem, cough, I think, em, maybe you mean "raise"?

That java stuff polluting your mind, eh? ;-)

As an aside, I've got to hand it to Java for exception handling. Java
was the language that taught me how to do proper and robust exception
handling, by "rapping my knuckles" continually, and actually making me
think about the exception hierarchies I was generating and processing.
You can't just randomly define and generate new exceptions: you have
to change your method definition to declare that it can throw the new
exception. Which means you either have to handle the exception in the
calling method, or change *that* method signature to permit
re-throwing of the exception, and so on up the hierarchy. 

It's not very pythonic though.

regards,

-- 
alan kennedy
-----------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan:              http://xhaus.com/mailto/alan




More information about the Python-list mailing list