[Python-Dev] Extended Function syntax

Bernhard Herzog bh@intevation.de
03 Feb 2003 12:50:20 +0100


Alex Martelli <aleax@aleax.it> writes:

> be helpful too?  Meaning to use local variable <identifier> in lieu of
> the abstract _x -- for example in order to enable:
> 
> with myfile = auto_closing_file('blah.txt', 'rb'):
>     xx = myfile.read(23)
>    # rest of suite snipped
> 
> where auto_closing_file is a subclass of file defining useful __enter__
> (empty -- might be nice to have it optional...) and __exit__ = close
> synonyms (or file itself might grow __exit__ as a synonym for close).
> 
> How would I do this elegantly without the assignment...?

Just as you do with if:

myfile = auto_closing_file('blah.txt', 'rb')
with myfile:
    xx = myfile.read(23)
    # rest of suite snipped

Maybe not quite as elegant as allowing assignment in with but very
similar to the normal try...final version:

myfile = auto_closing_file('blah.txt', 'rb')
try:
    xx = myfile.read(23)
    # rest of suite snipped
finally:
    myfile.close()


   Bernhard

-- 
Intevation GmbH                                 http://intevation.de/
Sketch                                 http://sketch.sourceforge.net/
MapIt!                                           http://www.mapit.de/