How to do this in Python?

Jervis Whitley jervisau at gmail.com
Wed Mar 18 21:31:00 EDT 2009


> What I was wondering
> was whether a similar construct was considered for a while loop or even an
> if clause, because then the above could be written like this:
>
>  if open(filename, 'rb') as f:
>      while f.read(1000) as buf:
>          # do something with 'buf'
>

see here, and the associated bug tracker item.

http://www.python.org/dev/peps/pep-0379/

There is also a thread on python-ideas (sorry no links handy) that
deals with this issue, and the
difference between the use of 'as' and assignment.

This is the PEP that describes the 'with' statement and it goes into
the choice of the 'as' keyword.
http://www.python.org/dev/peps/pep-0343/

(from PEP 343) ..
   So now the final hurdle was that the PEP 310 syntax:

           with VAR = EXPR:
               BLOCK1

       would be deceptive, since VAR does *not* receive the value of
       EXPR.  Borrowing from PEP 340, it was an easy step to:

           with EXPR as VAR:
               BLOCK1

Cheers,

Jervis



More information about the Python-list mailing list