[Discuss] A question for the Python gurus

Adam Parkin pzelnip at telus.net
Fri Jul 28 23:31:03 PDT 2006


Deryk Barker wrote:
> Ah, I blame C for this.

LOL.

> the structurally correct way is:
> 
> line = sys.stdin.readline ()
> while line:
>    # do something with line
>    line = sys.stdin.readline ()

Ick ick ick, code duplication! =8-p  Say you decide you don't want to 
read from stdin but rather stderr (or maybe some other file object). 
Now you have two lines you have to change and if the body of the while 
loop is large you could very easily remember one and not the other.

Or what happens when you're writing it at 3AM and you do something like:

line = sys.stdin.readline()
while line:
	# do something
	lines = sys.stdin.readline()

Ooops, misspelled a variable and because Python doesn't force you to 
declare a variable you now have an infinite loop (I've actually done 
something like this in Perl before I discovered "use strict").

That actually raises another thing I've often wondered about Python, is 
there any Python equivalent to the "use strict" statement in Perl which 
forces you to declare a variable with "my" before using it?  Like in 
Perl if you did something like:

use strict;

my $line = <STDIN>;
while ($line)
{
	# do something

	$lines = <STDIN>;
}

The interpreter will choke as you haven't "declared" $lines with a my 
directive.  Is there any such mechanism available in Python?

> it's what Michael Jackson (no, not that one) calls the read ahead and 
> ensures that you only enter the loop body when there is indeed something 
> to do.
> 
> It's only one line longer and will make the function call the same 
> number of times, but it's clearer by far - clearer IMHO than the C-style 
> while (line = ...) which I have never liked.

I agree that it's probably nicer than the C-style assignment, but I 
disagree that it's as nice as say something like (in Python-ish syntax):

while (not stdin.eof()):
	line = stdin.readline()

	# do something

Why is there no eof() method in the file object class in Python?
--
Adam Parkin
E-mail: pzelnip at telus.net
----------------------
...it's hard to test a program as a black box because all a tester can 
do is stuff things into the program and watch what pops out.  It's like 
trying to determine whether somebody is insane.  You ask questions; you 
listen to answers; and you make a judgment call.  In the end, you're 
never really sure because you don't know what's going on inside the 
other person's head.  You always wonder, "Did I ask enough questions? 
Did I ask the right questions?"

	-- Steve Maguire, Writing Solid Code


More information about the Discuss mailing list