[Python-Dev] Re: anonymous blocks
Guido van Rossum
gvanrossum at gmail.com
Wed Apr 27 23:50:10 CEST 2005
> >I'm not sure what the relevance of including a stack trace would be,
> >and why that feature would be necessary to call them coroutines.
> Well, you need that feature in order to retain traceback information when
> you're simulating threads with a stack of generators. Although you can't
> return from a generator inside a nested generator, you can simulate this by
> keeping a stack of generators and having a wrapper that passes control
> between generators, such that:
> def somegen():
> result = yield othergen()
> causes the wrapper to push othergen() on the generator stack and execute
> it. If othergen() raises an error, the wrapper resumes somegen() and
> passes in the error. If you can only specify the value but not the
> traceback, you lose the information about where the error occurred in
> So, the feature is necessary for anything other than "simple" (i.e.
> single-frame) coroutines, at least if you want to retain any possibility of
> debugging. :)
OK. I think you must be describing continuations there, because my
brain just exploded. :-)
In Python 3000 I want to make the traceback a standard attribute of
Exception instances; would that suffice? I really don't want to pass
the whole (type, value, traceback) triple that currently represents an
exception through __next__().
> Yes, it would be nice. Also, you may have just come up with an even better
> word for what these things should be called... patterns. Perhaps they
> could be called "pattern blocks" or "patterned blocks". Pattern sounds so
> much more hip and politically correct than "macro" or even "code block". :)
Yes, but the word has a much loftier meaning. I could get used to
template blocks though (template being a specific pattern, and this
whole thing being a non-OO version of the Template Method Pattern from
the GoF book).
> >An alternative that solves this would be to give __next__() a second
> >argument, which is a bool that should be true when the first argument
> >is an exception that should be raised. What do people think?
> I think it'd be simpler just to have two methods, conceptually
> "resume(value=None)" and "error(value,tb=None)", whatever the actual method
> names are.
Part of me likes this suggestion, but part of me worries that it
complicates the iterator API too much. Your resume() would be
__next__(), but that means your error() would become __error__(). This
is more along the lines of PEP 288 and PEP 325 (and even PEP 310), but
we have a twist here in that it is totally acceptable (see my example)
for __error__() to return the next value or raise StopIteration. IOW
the return behavior of __error__() is the same as that of __next__().
Fredrik, what does your intuition tell you?
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-Dev