[Python-Dev] 'With' context documentation draft (was Re: Terminology for PEP 343

Terry Reedy tjreedy at udel.edu
Fri Jul 8 20:28:11 CEST 2005


"Nick Coghlan" <ncoghlan at gmail.com> wrote in message 
news:42CE8BEF.9050508 at gmail.com...
> Phillip J. Eby wrote:
>> I suggest changing this to something like this:
>>
>>     class tag(object):
>>         def __init__(self,name):
>>             self.name = name
>>         def __enter__(self):
>>             print "<%s>" % name
>>         def __exit__(self):
>>             print "</%s>" % name
>>
>>     with tag('html'):
>>         # ... etc.
>>
>> So that it's obvious where the implementation is coming from.
>> Otherwise, it looks altogether too magical.
>
> Done - included in the latest version on SF. [1]

Would this also work as a decorated generator?
(If I have understood correctly, something like..)

@contextmanager
def tag(name)
       print "<%s>" % name
       yield None
       print "</%s>" % name

If so, I suggest putting in both versions to make the correspondence clear.

To whoever invented this example: thanks.  It rang a bell with me so I 
could see this as a generally usefully feature rather than a specialized 
(though for some, important) 'close resource' feature.

The particularly neat thing is that it converts the indent-dedent method of 
showing structure to the alternative matched-fences method.   This is 
certainly not limited to HTML generation.

Terry J. Reedy





More information about the Python-Dev mailing list