[Python-Dev] Extended Function syntax

Alex Martelli aleax@aleax.it
Sun, 2 Feb 2003 20:35:03 +0100


On Sunday 02 February 2003 08:21 pm, Samuele Pedroni wrote:
   ...
> with <expr>:
>  <suite>
>
> would be possibly sugar for:
>
> _x = <expr>
> _x.__enter__()
> try:
>   <suite>
> finally:
>   _x.__exit__()

wouldn't a version:

with <identifier> = <expr>:
    <suite>

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...?


Apart from this I cannot, offhand, think of any case that your 'with'
(perhaps with some tweaks such as making __enter__ optional, as
above mentioned) could not handle elegantly and effectively.


Alex