[Python-Dev] More on contextlib - adding back a contextmanager decorator (original) (raw)

Guido van Rossum guido at python.org
Sun Apr 30 18:53:57 CEST 2006


On 4/30/06, Nick Coghlan <ncoghlan at iinet.net.au> wrote:

A few things from the pre-alpha2 context management terminology review have had a chance to run around in the back of my head for a while now, and I'd like to return to a topic Paul Moore brought up during that discussion.

I believe the context API design has gotten totally out of hand. Regardless of the merits of the "with" approach to HTML generation (which I personally believe to be an abomination), I don't see why the standard library should support every possible use case with a custom-made decorator. Let the author of that tag library provide the decorator.

I have a counter-proposal: let's drop context. Nearly all use cases have context return self. In the remaining cases, would it really be such a big deal to let the user make an explicit call to some appropriately named method? The only example that I know of where context doesn't return self is the decimal module. So the decimal users would have to type

with mycontext.some_method() as ctx: # ctx is a clone of mycontext ctx.prec += 2

The implementation of some_method() could be exactly what we currently have as the context method on the decimal.Context object. Its return value is a decimal.WithStatementContext() instance, whose enter() method returns a clone of the original context object which is assigned to the variable in the with-statement (here 'ctx').

This even has an additional advantage -- some_method() could have keyword parameters to set the precision and various other context parameters, so we could write this:

with mycontext.some_method(prec=mycontext.prec+2):

Note that we can drop the variable too now (unless we have another need to reference it). An API tweak for certain attributes that are often incremented or decremented could reduce writing:

with mycontext.some_method(prec_incr=2):

-- --Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-Dev mailing list