[Discuss] A question for the Python gurus

Brian Quinlan brian at sweetapp.com
Fri Jul 28 23:59:13 PDT 2006


Adam Parkin wrote:
> Well, the actual problem I was working on that lead me to ask was 
> reading from stdin.  I just think this code looks wrong/ugly to me:
> 
> while (1):
>     line = sys.stdin.readline()
>     if (not line):
>         break
> 
>     # now do something with line

Rewrite 1
---------

while 1:
     line = sys.stdin.readline()
     if not line:
         break

     # now do something with line

Rewrite 2
---------

for line in sys.stdin:
     # now do something with line

> I'd rather have something that looked like:
> 
> while (line = sys.stdin.readline())
>     # do something with line
> 
> but of course this isn't valid (assignment statements aren't 
> expressions, or so it would seem).

Right, because this is a common source of errors i.e. people writing 
assignment when they meant comparison

> So my thinking was to write a 
> function that would return true/false depending on whether or not EOF 
> was reached, and to modify its only argument with whatever was read from 
> stdin.

This is a bad idea. Just use normal Python idioms.

> One thing I don't understand though, why are strings in Python 
> immutable?  

For a few reasons:
1. they can only act as hash keys if they are immutable
2. since Python does pass-by-object, changing a string in one part of
    your program could unintentionally affect another part

> That seems to be a fairly significant limitation from an 
> efficiency standpoint as it means any kind of string processing involves 
> creating new strings repeatedly instead of just modifying in place. 

Actually, efficiency is another reason why strings are immutable:
1. the hash of a string need only every be calculated once (and cached)
2. identical strings can be (and are) pooled

I think that you mentioned before that you are a Perl programmer? Time 
to start getting used to immutable strings for Perl 6 :-)

Cheers,
Brian


More information about the Discuss mailing list