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

P.J. Eby pje at telecommunity.com
Sun Mar 15 22:23:31 CET 2009

At 06:28 AM 3/16/2009 +1000, Nick Coghlan wrote:
>There are some practical hurdles to that idea (specifically, creating a
>callable which uses its parent's namespace rather than having its own),
>but the basic concept seems sound.

Actually, that bit's pretty simple -- they're just "nonlocal" 
variables.  But the cost of creating that function, and the cost of 
having cell variables in the surrounding function is potentially 
high.  (In CPython at least, function calls are optimized in certain 
ways when the function only has "fast" locals, and no "cell" locals.)

The cost of creating the function (though not the code object) could 
be held till runtime, since the interpreter could wait until it's 
sure there's a __with__ method before doing a MAKE_CLOSURE on the code object.

Of course, at that point, what's the difference between:

     with foo() as bar:


     def bar():

except for being slightly less verbose? (due to missing nonlocal 
statements, etc.)

More information about the Python-Dev mailing list