[Python-Dev] Extended Function syntax

Brett Cannon bac@OCF.Berkeley.EDU
Sun, 2 Feb 2003 14:07:38 -0800 (PST)


[Alex Martelli]

> On Sunday 02 February 2003 10:41 pm, Brett Cannon wrote:
>    ...
> > So if someone (read: Guido and Samuele =)

... or Alex.  =)

> > could implement a file that auto-closes once the iterator on the file
> > is exhausted with each suggestion I would *really* appreciate it.
> > And if there could even be code given that used what these things
> > returned by searching each returned line for the word "Python" would
> > be great as well.  That way we not only
>
> As I understood Samuele's "with" proposal (enhanced to allow assignment
> in the with, and to make __enter__ optional):
>
> class auto_closing_file(file):
>     __exit__ = file.close
>
> with myfile = auto_closing_file('blah.txt'):
>     for line in myfile:
>         if line.find('Python')>=0:
>             print line,
>
> If __enter__ were not optional, auto_closing_file would have to add one
> boilerplate line defining it:
>
> class auto_closing_file(file):
>     __exit__ = file.close
>     def __enter__(self): pass
>
> Actually, it would seem sensible, if we added this 'with', to extent built-in
> file by this tiny bit -- let it have __exit__ as a synonym of close (and if
> needed __enter__ as a no-operation method) so it can be used directly
> in what would then become a very common idiom:
>
> with myfile = open('blah.txt'):
>     for line in myfile:
>         if line.find('Python')>=0:
>             print line,
>

Now if ``__exit__()`` would be executed regardless of exceptions this
would probably eliminate a decent chunk of code that uses ``finally:``
such as::

 FILE = file('blah.txt', 'rb')
 try:
     for line in FILE:
         if line.find('Python')>=0:
             print line,
 finally:
     FILE.close()

Wouldn't this also allow one to code in a contract programming style ala
Icon (assuming I remember correctly how contract programming works)?  I
mean you have control over the enter and exit of the thunk (would this
still be called a thunk, or just syntactic sugar for calling
``__exit__()`` and ``__enter__()``; more like a thunk-ish protocol?) which
is what I thought was the focus of contract programming.

Either way this seems rather nice.  And if you can pass in arguments (as I
think ``FILE = file('blah.txt', 'rb'): (some_argument):`` is supposed to
implement) this would be really nice.  =)

Now we just need the ``do`` syntax example.

-Brett