[Python-ideas] raising an exception type doesn't instantiate it until it gets caught

Cameron Simpson cs at zip.com.au
Mon Nov 7 21:05:29 CET 2011


I wrote, naively:
| > I presume StopIteration would get instantiated to a singleton, like
| > NoneType to None? Just asking.

On 07Nov2011 22:01, Nick Coghlan <ncoghlan at gmail.com> wrote:
| Even without the traceback issue Antoine mentioned, it's already the
| case that StopIteration isn't a singleton in 2.x. Various pieces of
| code (e.g. contextlib.contextmanager) rely on being able to tell
| whether they're getting a specific StopIteration instance back or a
| new one.

Interesting.

Off topic digression:

I've been slightly uncomfortable about exceptions as control flow for a
while, basicly when writing code like this:

  try:
    x = G.next()
  except StopIteration:
    # G is empty!

in that I don't entirely know that the StopIteration came from G of from
some buggy code deeper inside G that let a StopIteration out, eg by
mangling a try/except like the above. In most circumstances with other
exceptions, while you might _expect_ the exception to come from the
source you expect you don't care so much because it will indicate
failure of the operation anyway. Report or die, you don't proceed as if
the op was good. But with StopIteration one is reading "G is empty"
directly into the situation and acting as though it is normal (exit the
event loop or whatever it may imply).

On 07Nov2011 11:35, Antoine Pitrou <solipsis at pitrou.net> wrote:
| It is impossible to use singletons for exception instances now that the
| traceback is stored on them.

Ah. I had somehow thought the exception itself and the traceback were
distinct items, presented in a tuple.

On 07Nov2011 21:15, Steven D'Aprano <steve at pearwood.info> wrote:
| Are you asking about what it should be, or what it is?

The former.

| Either way:
| >>> a = StopIteration('spam')
| >>> b = StopIteration('ham')
| >>> a is b
| False

Since my question was about the proposed new behaviour when just a type
was raised, the above test wouldn't educate me. Though it does address the
behaviour of the type instantation in general.

Cheers,
-- 
Cameron Simpson <cs at zip.com.au> DoD#743
http://www.cskk.ezoshosting.com/cs/

Carpe Datum     - John Sloan <jsloan at ncar.ucar.edu>



More information about the Python-ideas mailing list