while c = f.read(1)

Donn Cave donn at drizzle.com
Fri Aug 19 02:07:31 EDT 2005


Quoth "Greg McIntyre" <greg at puyo.cjb.net>:
| I have a Python snippet:
|
|   f = open("blah.txt", "r")
|   while True:
|       c = f.read(1)
|       if c == '': break # EOF
|       # ... work on c
|
| Is some way to make this code more compact and simple? It's a bit
| spaghetti.

Actually I'd make it a little less compact -- put the "break"
on its own line -- but in any case this is fine.  It's a natural
and ordinary way to express this in Python.

...
| But I get a syntax error.
|
|     while c = f.read(1):
|            ^
| SyntaxError: invalid syntax
|
| And read() doesn't work that way anyway because it returns '' on EOF
| and '' != False. If I try:

This is the part I really wanted to respond to.  Python managed
without a False for years (and of course without a True), and if
the introduction of this superfluous boolean type really has led
to much of this kind of confusion, then it was a bad idea for sure.

The condition that we're looking at here, and this is often the
way to look at conditional expressions in Python, is basically
something vs. nothing.  In this and most IO reads, the return
value will be something, until at end of file it's nothing.
Any type of nothing -- '', {}, [], 0, None - will test "false",
and everything else is "true".  Of course True is true too, and
False is false, but as far as I know they're never really needed.

You are no doubt wondering when I'm going to get to the part where
you can exploit this to save you those 3 lines of code.  Sorry,
it won't help with that.

| Is this related to Python's expression vs. statement syntactic
| separation? How can I be write this code more nicely?

Yes, exactly.  Don't worry, it's nice as can be.  If this is
the worst problem in your code, you're far better off than most
of us.

	Donn Cave, donn at drizzle.com



More information about the Python-list mailing list