Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   Re: 2.2 <-> 2.3 surprise (http://www.velocityreviews.com/forums/t331551-re-2-2-2-3-surprise.html)

Shalabh Chaturvedi 05-31-2004 05:28 PM

Re: 2.2 <-> 2.3 surprise
 
Roman Suzi wrote:

> Hi!
>
> I really like python 2.3 but sometimes I write for 2.2 too.
>
> New cool feature of doing:
>
> f = open('file')
> for line in f:
> do_something(line)
>
> works strange in 2.2: I can't just quit first loop and do:
>
> for line in f:
> do_some_more(line)
>
> (I as skipping message header by first loop and processing body
> the the second).
>
> In 2.3 it works as intended! Of course, simple refacture made it one loop...
>
>
>
> Sincerely yours, Roman Suzi


This is probably the following change as described in
http://www.python.org/2.3/highlights.html

"File objects are now their own iterators. This makes multiple
interrupted iterations over the same file more reliable."

Something that *might* work in both 2.2 and 2.3 using multiple loops is
(not tested):

f = iter(open('file'))

....and then use f as before.

--
Shalabh




Duncan Booth 06-01-2004 10:07 AM

Re: 2.2 <-> 2.3 surprise
 
Shalabh Chaturvedi <shalabh@cafepy.com> wrote in
news:mailman.462.1086024331.6949.python-list@python.org:

> Something that *might* work in both 2.2 and 2.3 using multiple loops is
> (not tested):
>
> f = iter(open('file'))
>
> ...and then use f as before.


That is almost the correct idiom to use for code that must work in both 2.2
and 2.3. It helps though if you save both the file and the iterator in
variables otherwise you have no way to close the file when you are
finished. So something like:

theFile = open('file')
f = iter(theFile)

for line in f:
... do something and maybe break ...
for line in f:
... and so on ...

theFile.close()



All times are GMT. The time now is 10:10 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.