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

Nick Coghlan ncoghlan at gmail.com
Mon May 1 14:24:58 CEST 2006


Greg Ewing wrote:
> Nick Coghlan wrote:
>> the context expression in the with statement produces a context 
>> manager with __enter__ and __exit__ methods which set up and tear down 
>> a managed context for the body of the with statement. This is very 
>> similar to your later suggestion of context guard and guarded context.
> 
> Currently I think I still prefer the term "guard",
> since it does a better job of conjuring up the same
> sort of idea as a try-finally.

See the other message I wrote while you were writing this one for the various 
reasons I now agree with you :)

> There's also one other issue, what to call the
> decorator. I don't like @contextfactory, because it
> sounds like something that produces contexts,
> yet we have no such object.

Agreed.

> With only one object, it should probably be named
> after that object, i.e. @contextmanager or
> @contextguard. That's if we think it's really
> worth making it easy to abuse a generator in this
> way -- which I'm not convinced about. It's not
> as if people are going to be implementing context
> managers/guards every day.

I suggested renaming it to "guardfactory" in my other message. Keeping the 
term 'factory' in the name emphasises that the decorator results in a callable 
that returns a context guard, rather than producing a context guard directly.

As for whether or not we should provide this ability, I think we definitely 
should. It allows try/finally boilerplate code to be replaced with a guarded 
context almost mechanically, whereas converting the same code to a manually 
written context guard could involve significant effort in changing from local 
variable based storage to instance attribute based storage. IOW, the feature 
is provided for the same reason that generator functions are provided: it is 
typically *much* easier to write a generator function than it is to write the 
same iterator manually.

Cheers,
Nick.

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


More information about the Python-Dev mailing list