[Python-Dev] PEP 377 - allow __enter__() methods to skip the statement body

Michael Foord fuzzyman at voidspace.org.uk
Sun Mar 15 21:16:53 CET 2009

Nick Coghlan wrote:
>> Note that using exceptions for control flow can  be bad for other
>> implementations of Python. For example exceptions on the .NET framework
>> are very expensive. (Although there are workarounds such as not really
>> raising the exception - but they're ugly).
> Is it that exceptions are expensive, or setting up a try/except block is
> expensive? The reason the SkipStatement idea is tenable at all (even in
> CPython) is that try/except is fairly cheap when no exception is raised.

It is the raising of the exception that is expensive.

> (In this specific case, my initial patch does slow things down a bit,
> since one side effect of the extra try/except block is to disallow a
> couple of stack based optimisations that are used in the current CPython
> implementation of the with statement)
>> Isn't it better practise for exceptions to be used for exceptional
>> circumstances rather than for control flow?
> This *is* an exceptional circumstance: a typical __enter__ method will
> just return or raise some other exception. I suppose you could use some
> kind of dedicated thread-local state instead of an exception to indicate
> that the underlying generator didn't yield, but a new control flow
> exception seemed like the most straightforward option.
> I'm somewhat intrigued by Glyph's idea though - if I can figure out a
> way to make it practical, it does offer very some interesting
> possibilities (and would, in effect, bring reusable embedded code blocks
> to Python...).
> Cheers,
> Nick.


More information about the Python-Dev mailing list