[Python-Dev] Proposed changes to PEP 343

Nick Coghlan ncoghlan at gmail.com
Fri Oct 7 14:38:19 CEST 2005

Fredrik Lundh wrote:
> Nick Coghlan wrote:
>>    9. Here's a proposed native context manager for decimal.Context:
>>        # This would be a new decimal.Context method
>>        @contextmanager
>>        def __with__(self):
> wouldn't it be better if the ContextWrapper class (or some variation thereof) could
> be used as a base class for the decimal.Context class?  using decorators on methods
> to provide "is a" behaviour for the class doesn't really feel pythonic...

That's not what the decorator is for - it's there to turn the generator used 
to implement the __with__ method into a context manager, rather than saying 
anything about decimal.Context as a whole.

However, requiring a decorator to get a slot to work right looks pretty ugly 
to me, too.

What if we simply special-cased the __with__ slot in type(), such that if it 
is populated with a generator object, that object is automatically wrapped 
using the @contextmanager decorator? (Jason actually suggested this idea 

I initially didn't like the idea because of EIBTI, but I've realised that "def 
__with__(self):" is pretty darn explicit in its own right. I've also realised 
that defining __with__ using a generator, but forgetting to add the 
@contextmanager to the front would be a lovely source of bugs, particularly if 
generators are given a default __exit__() method that simply invokes self.close().

On the other hand, if __with__ is special-cased, then the slot definition 
wouldn't look ugly, and we'd still be free to define a generator's normal with 
statement semantics as:

   def __exit__(self, *exc):


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list