[Python-Dev] PEP 343: Context managers a superset of decorators?

Eric Sumner kd5bjo at gmail.com
Mon Feb 13 17:42:30 CET 2006

On 2/13/06, Nick Coghlan <ncoghlan at gmail.com> wrote:
> Eric Sumner wrote:
> > I realize that I made an assumption that may not be valid;
> > namely, that a new scope is generated by the 'with' statement.
> The with statement uses the existing scope - its just a way of factoring out
> try/finally boilerplate code. No more, and, in fact, fractionally less (the
> 'less' being the fact that just like any other Python function, you only get
> to supply one value to be bound to a name in the invoking scope).

Ok.  These changes are more substantial than I thought, then.

> Trying to link this with the function definition pipelining provided by
> decorators seems like a bit of a stretch. It certainly isn't a superset of the
> decorator functionality - if you want a statement that manipulates the
> namespace it contains, that's what class statements are for :)

Several examples of how the 'with' block would be used involve
transactions which are either rolled back or confirmed.  All of these
use the transaction capabilities of some external database.  With
separate scopes, the '__exit__' function can decide which names to
export outwards to the containing scope.  Unlike class statements, the
contained scope is used temporarily and can be discarded when the
'with' statement is completed.  This would allow a context manager to
provide a local transaction handler.

To me, it is not much of a leap from copying data between scopes to
modifying it as it goes through, which is exactly what decorators do. 
The syntax that this provides for decorators seems reasonable enough
(to me) to make the '@' syntax redundant.  However, this is a larger
change than I thought, and maybe not worth the effort to implement.

  -- Eric

More information about the Python-Dev mailing list