two ideoms at one blow: line-reading and regexp-matching

Russell Nelson nelson at crynwr.com
Wed Feb 20 10:55:44 EST 2002


François Pinard writes:
 > [Russell Nelson]
 > 
 > > There are two Python ideoms that bother me:
 > 
 > >     while 1:
 > >         line = file.readline()
 > >         if not line: break
 > 
 > Hello, Russell.  Glad to see you here as well! :-)

Hello, François.  Yes, I discovered Python about a year ago, after
pining (for the fjords) for a language without silly syntactic sugar
around its blocks.  Software Practice & Experience had an article over
20 years ago that pointed out that a small set of indentation rules
made block syntax tokens unnecessary.  I thought that was a great idea
... and then much later I discovered Python using those rules.

 > For the above, I like writing:
 > 
 >     line = file.readline()
 >     while line:
 >         ...
 >         line = file.readline()

I agree that this is useful.  A "while line = file.readline()"
creates the expectation that all lines are read at that point.  Then
again, "for line in file:" creates a stronger expectation!

 > >     while line = file.readline():
 > 
 > I would rather not see Python accepting this, first because it makes the
 > code less explicit, but also because it would more easily allow the error
 > of miswriting `==' as `=' unnoticed by the Python code reader.

Yeah.  Perhaps if there was a built-in function which returned the
result of the previous test, but that has its own dangers of being
used in the wrong place.

 > > I just think it would be easier to read programs if they could be
 > > written like this.
 > 
 > Programs may get slightly easier to write, I doubt it would really make
 > them more legible, however.  My feeling is that the current situation is
 > better than alternatives, all considered.

Well, I was just struck by the consistency of allowing "variable =
boolean" in "if" and "while".  Sort of like this in assembly language:

	add ax,bx
	jc  got_overflow
	mov result, ax

You do your test, but you still have the results of the computation
available to you.  Seems like a Good Thing(tm), but I'm happy to be
talked out of it.

-- 
-russ nelson              http://russnelson.com | Crypto without a threat
Crynwr sells support for free software  | PGPok | model is like cookies
521 Pleasant Valley Rd. | +1 315 268 1925 voice | without milk.
Potsdam, NY 13676-3213  | +1 315 268 9201 FAX   | 




More information about the Python-list mailing list