[Tutor] Iterating through a list of strings

Luke Paireepinart rabidpoobear at gmail.com
Mon May 3 12:18:41 CEST 2010


On Mon, May 3, 2010 at 3:50 AM, Stefan Behnel <stefan_ml at behnel.de> wrote:
> Luke Paireepinart, 03.05.2010 10:27:
>> What's this bizarre syntax?
>
> Look it up in the docs, it's called "with statement". Its purpose here is to
> make sure the file is closed after the execution of the statement's body,
> regardless of any errors that may occur while running the loop.
>
>
>> I thought they changed for loop interations so that if you did
>> for line in open('packages.txt'):
>>     .... etc...
>>
>> it would automatically close the file handle after the loop terminated.
>> Have I been wrong this whole time?
>
> Yes. The fact that the file is automatically closed after the loop is an
> implementation detail of CPython that does not apply in other Python
> implementations.
>

So why is it an implementation detail?  Why is it not universally like that?
You never have an explicit reference to the file handle.  When it gets
garbage-collected after the loop it should get rid of the file handle.

I mean, where is the line between 'implementation details' and
'language features'?  What reason is there to make lists mutable but
strings immutable?  Why aren't strings mutable, or lists immutable?

It all seems pretty arbitrary to me.

Also, the with syntax is kind of ugly.  So is the 'for/else' syntax.
They are not as intuitively clear as most of the other language
constructs to me.

-Luke


More information about the Tutor mailing list