473,324 Members | 1,856 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

iterators: class vs generator

There is an interesting difference between how exceptions are handled
between iterators constructed from a class, and iterators constructed
from a generator. The following are "mostly equivalent":

class iterable_via_class:
def __iter__(self):
self._next = self._one
return self
def next(self):
return self._next()
def _one(self):
self._next = self._two
return "one"
def _two(self):
self._next = self._stop
return "two"
def _stop(self):
raise StopIteration()

def iterable_via_generator():
yield "one"
yield "two"

print "\nclass:"
for x in iterable_via_class():
print x

print "\ngenerator:"
for x in iterable_via_generator():
print x

However, when exceptions are involved, behavior can be different:

class iterable_via_class:
def __iter__(self):
self._next = self._one
return self
def next(self):
return self._next()
def _one(self):
self._next = self._raise
return "one"
def _raise(self):
self._next = self._two
raise Exception()
def _two(self):
self._next = self._stop
return "two"
def _stop(self):
raise StopIteration()

def iterable_via_generator():
yield "one"
raise Exception()
yield "two"

def test(itergen):
it = iter(itergen())
print it.next()
try:
ignore = it.next()
except:
pass
print it.next()

print "\nclass:"
test(iterablex)
print "\ngenerator:"
test(iterable)
Jul 18 '05 #1
2 2062
"Clark C. Evans" <cc*@clarkevans.com> writes:
There is an interesting difference between how exceptions are handled
between iterators constructed from a class, and iterators constructed
from a generator. The following are "mostly equivalent":
[...]
However, when exceptions are involved, behavior can be different:


(It would have been nice if you'd explained what the differences were
in your post, and given that you'd didn't if you'd made sure the
examples were correct -- got a NameError for iterable...)

Here's a better illustration:
def iterable_via_generator(): .... yield "one"
.... raise Exception()
.... yield "two"
.... i = iterable_via_generator()
i.next() 'one' i.next() Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in iterable_via_generator
Exception i.next() Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration

I agree this is surprising. I am vaguely aware of some effort being
put in to make generators "stick", i.e. this doesn't surprise me so
much:
def g(): .... yield 1
.... return
.... yield 2
.... i = g()
i.next() 1 i.next() Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration i.next()

Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration

I'd guess the behaviour you've noticed is an unintended consequence of
this. I'd also be willing to be persuaded that it's a bug, although
others might disagree, dunno. File an issue, anyway?

Cheers,
mwh

--
I would hereby duly point you at the website for the current pedal
powered submarine world underwater speed record, except I've lost
the URL. -- Callas, cam.misc
Jul 18 '05 #2
On Wed, 25 Aug 2004 11:24:41 GMT, Michael Hudson <mw*@python.net> wrote:

Here's a better illustration:
def iterable_via_generator(): .... yield "one"
.... raise Exception()
.... yield "two"
.... i = iterable_via_generator()
i.next() 'one' i.next() Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in iterable_via_generator
Exception i.next()

Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration

This is correct behaviour according to PEP 255:
"""
If an unhandled exception-- including, but not limited to,
StopIteration --is raised by, or passes through, a generator function,
then the exception is passed on to the caller in the usual way, and
subsequent attempts to resume the generator function raise
StopIteration. In other words, an unhandled exception terminates a
generator's useful life.
"""
Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
by: Francis Avila | last post by:
Below is an implementation a 'flattening' recursive generator (take a nested iterator and remove all its nesting). Is this possibly general and useful enough to be included in itertools? (I know...
2
by: Chris Lyon | last post by:
coming from a Vb'ish sort of background, issues like iterators and list comprehensions appear at first site to be a confusion. However since I have a great deal of respect for the large brains in a...
10
by: Steven Bethard | last post by:
So, as I understand it, in Python 3000, zip will basically be replaced with izip, meaning that instead of returning a list, it will return an iterator. This is great for situations like: zip(*)...
13
by: Bulba! | last post by:
Hello Mr Everyone, From: http://docs.python.org/tut/node11.html#SECTION0011900000000000000000 "Define a __iter__() method which returns an object with a next() method. If the class defines...
4
by: jhonyxxx | last post by:
I have the next programa in C++: #include <iostream.h> // C++ I/O routines #include <list.h> // The STL list class #include<stdio.h> #include <string.h> typedef struct { char nombre; int...
14
by: Jiri Kripac | last post by:
Languages such as Simula 67 contain a general concept of coroutines that allow the execution of a method to be suspended without rolling back the stack and then later resumed at the same place as...
2
by: Bernhard Mulder | last post by:
I have something like the following (using Python 2.5 syntax): class adapt(object): def __init__(self): self.iterator = self.generator() self.n = 0 def generator(self): while True: while...
6
by: gexarchakos | last post by:
Hi there, Please give me at least a hint... I have a problem implementing a function object with parameters two iterators. That is: A class 'node' produces messages using a routing policy....
7
by: Leslie Sanford | last post by:
My area of programming is DSP. I write things like filters, oscillators, envelopes, etc. I've been looking at STL iterators, and what's struck me is that if I can find ways to model my code using...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.