[Python-Dev] More on contextlib - adding back a contextmanager decorator

Nick Coghlan ncoghlan at gmail.com
Mon May 1 12:29:12 CEST 2006


Phillip J. Eby wrote:
> At 08:08 PM 4/30/2006 -0700, Guido van Rossum wrote:
>> If you object against the extra typing, we'll first laugh at you
>> (proposals that *only* shave a few characters of a common idiom aren't
>> all that popular in these parts), and then suggest that you can spell
>> foo.some_method() as foo().
> 
> Okay, you've moved me to at least +0 for dropping __context__.  I have 
> only one object myself that has a non-self __context__, and it doesn't 
> have a __call__, so none of my code breaks beyond the need to add 
> parentheses in a few places.  ;)

At least +0 here, too. I've just been so deep in this lately that it is taking 
a while to wind my thinking back a year or so. Still, far better to be having 
this discussion now than in 6 months time :)

It sure has been a long and winding road back to Guido's original version of 
PEP 343, though!

> As for decimal contexts, I'm thinking maybe we should have a 
> decimal.using(ctx=None, **kw) function, where ctx defaults to the 
> current decimal context, and the keyword arguments are used to make a 
> modified copy, seems like a reasonable best way to implement the 
> behavior that __context__ was added for.  And then all of the existing 
> special machinery can go away and be replaced with a single 
> @contextfactory.

'localcontext' would probably work as at least an interim name for such a 
function.

   with decimal.localcontext() as ctx:
       # use the new context here

This is really an all-round improvement over the current SVN approach, where 
the fact that a new decimal context object is being created by the existing 
decimal context object is thoroughly implicit and unobvious.

> (I think we should stick with @contextfactory as the decorator name, 
> btw, even if we go back to calling __enter__/__exit__ things context 
> managers.)

Agreed. And that decorator will still be useful for defining methods as well 
as functions.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-Dev mailing list