[Python-Dev] Extended Function syntax

Samuele Pedroni pedronis@bluewin.ch
Sun, 2 Feb 2003 21:24:42 +0100


From: "Alex Martelli" <aleax@aleax.it>
>
> 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).

you're right, you would also get this idiom for iterators that support also the
'with' protocol:

with myfile = auto_closing_file('blah.txt', 'rb'):
  for line in myfile:
   ...