I discovered today that Python 2's prohibition against performing readlines on a file being iterated over appears to have been lifted in Python 3. Is this intentional? If it is, should it be added to the What's New in the documentation? I haven't been able to find anything mentioning the change.

        with open("lines.txt") as fil:
            for line in fil:
                print(line[:-1])
                print(fil.readline())

produces a runtime error in 2.5 and 2.6 but not in 3.0 or 3.1 (and the output is as expected).

Also, I was surprised that nested "for line in file" that use the same file cause no problems in Python 2.5, 2.6, 3.0, or 3.1.

        with open("lines.txt") as fil:
            for line1 in fil:
                print(line1)
                if line1[0] == '1':
                    for line2 in fil:
                        print(line2[:-1])
                        if line2[0] == '2':
                            break
I would have expected the "for line in file" iterator to get confused by the file position having been moved out from under it, but I suppose all it has to do is just more readlines from wherever the file pointer is when it regains control. I mention this because apart from implementation considerations any reasoning that would discourage one from mixing line iterations with readlines might leave one thinking that nested line iterations wouldn't work either. But if it is intended that Python 3 allow mixing readlines with line iterations, there would be much less reason to suspect nested line iterations.

_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to