By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,290 Members | 1,666 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,290 IT Pros & Developers. It's quick & easy.

while c = f.read(1)

P: n/a
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.

This is what I would ideally like:

f = open("blah.txt", "r")
while c = f.read(1):
# ... work on c

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:

f = open("blah.txt", "r")
while (c = f.read(1)) != '':
# ... work on c

I get a syntax error also. :(

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

Thanks

Aug 19 '05 #1
Share this Question
Share on Google+
75 Replies


P: n/a
On 18 Aug 2005 22:21:53 -0700, "Greg McIntyre" <gr**@puyo.cjb.net> wrote:
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.

This is what I would ideally like:

f = open("blah.txt", "r")
while c = f.read(1):
# ... work on c
How about (untested):

for c in iter((lambda f=open('blah.txt', 'r'): f.read(1)), ''):
# ... work on c

("if c=='': break" functionality courtesy of iter(f, sentinel) form above)

Of course, reading characters one by one is not very efficient, so if the file
is reasonably sized, you might just want to read the whole thing and iterate
through it, something like

for c in open('blah.txt').read():
# ... work on c
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:

f = open("blah.txt", "r")
while (c = f.read(1)) != '':
# ... work on c

I get a syntax error also. :(

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

Yes, it is related as you suspect. I'll leave it to you to make
a chunk-buffering one-liner for huge files that iterates by characters,
if one-liners turn you on. Otherwise it is easy to write a generator that will do it.
Byt the time I post this, someone will probably have done it ;-)
Regards,
Bengt Richter
Aug 19 '05 #2

P: n/a
Greg McIntyre wrote:
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.


That's not spaghetti. Not even close.

In any case, is there a reason you are reading one character at a time
instead of reading the contents of the file into memory and iterating
over the resulting string?

f = open('blah.txt', 'r')
text = f.read()
f.close()

for c in f:
# ...

If you must read one character at a time,

def reader(fileobj, blocksize=1):
"""Return an iterator that reads blocks of a given size from a
file object until EOF.
"""
# Note that iter() can take a function to call repeatedly until it
# receives a given sentinel value, here ''.
return iter(lambda: fileobj.read(blocksize), '')

f = open('blah.txt', 'r')
try:
for c in reader(f):
# ...
finally:
f.close()

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Aug 19 '05 #3

P: n/a
Quoth "Greg McIntyre" <gr**@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, do**@drizzle.com
Aug 19 '05 #4

P: n/a
Greg McIntyre wrote:
I have a Python snippet:

f = open("blah.txt", "r")
while True:
c = f.read(1)
if c == '': break # EOF
That could read like this
if not c: break # EOF
# see below for comments on what is true/false
# ... work on c

Is some way to make this code more compact and simple? It's a bit
spaghetti.
Not at all, IMHO. This is a simple forward-branching exit from a loop in
explicable circumstances (EOF). It is a common-enough idiom that doesn't
detract from readability & understandability. Spaghetti is like a GOTO
that jumps backwards into the middle of a loop for no discernable reason.

This is what I would ideally like:

f = open("blah.txt", "r")
while c = f.read(1):
# ... work on c

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. >
You have a bit of a misunderstanding here that needs correcting:

In "if <blah>" and "while <blah>", <blah> is NOT restricted to being in
(True, False). See section 5.10 of the Python Reference Manual:

"""
In the context of Boolean operations, and also when expressions are used
by control flow statements, the following values are interpreted as
false: None, numeric zero of all types, empty sequences (strings, tuples
and lists), and empty mappings (dictionaries). All other values are
interpreted as true.
"""

.... AND it's about time that list is updated to include False explicitly
-- save nitpicking arguments about whether False is covered by
"numeric zero of all types" :-)
If I try:

f = open("blah.txt", "r")
while (c = f.read(1)) != '':
# ... work on c

I get a syntax error also. :(

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

Thanks


How about
for c in f.read():
?
Note that this reads the whole file into memory (changing \r\n to \n on
Windows) ... performance-wise for large files you've spent some memory
but clawed back the rather large CPU time spent doing f.read(1) once per
character. The "more nicely" factor improves outasight, IMHO.

Mild curiosity: what are you doing processing one character at a time
that can't be done with a built-in function, a standard module, or a
3rd-party module?
Aug 19 '05 #5

P: n/a
Bengt Richter wrote:
On 18 Aug 2005 22:21:53 -0700, "Greg McIntyre" <gr**@puyo.cjb.net> wrote:

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.

This is what I would ideally like:

f = open("blah.txt", "r")
while c = f.read(1):
# ... work on c


How about (untested):

for c in iter((lambda f=open('blah.txt', 'r'): f.read(1)), ''):
# ... work on c

:-)
Bengt, did you read on to the bit where the OP wanted to do it "more
nicely"? YMMV, but I think you've strayed into "pas devant les enfants"
territory.
(-:

Cheers,
John
Aug 19 '05 #6

P: n/a
On 18 Aug 2005 22:21:53 -0700
Greg McIntyre wrote:
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.


import itertools
f = open("blah.txt", "r")
for c in itertools.chain(*f):
print c
# ...

The "f" is iterable itself, yielding a new line from the file every time.
Lines are iterable as well, so the itertools.chain iterates through each
line and yields a character.

--
jk
Aug 19 '05 #7

P: n/a
<en**********@ospaz.ru> writes:
import itertools
f = open("blah.txt", "r")
for c in itertools.chain(*f):
print c
# ...

The "f" is iterable itself, yielding a new line from the file every time.
Lines are iterable as well, so the itertools.chain iterates through each
line and yields a character.


But that can burn an unlimited amount of memory if there are long
stretches of the file with no newlines. There's no real good way
around ugly code.
Aug 19 '05 #8

P: n/a
en**********@ospaz.ru wrote:
import itertools
f = open("blah.txt", "r")
for c in itertools.chain(*f):
print c
# ...

The "f" is iterable itself, yielding a new line from the file every time.
Lines are iterable as well, so the itertools.chain iterates through each
line and yields a character.


As far as I can tell, that code is just going to read the whole file in
when Python does the *arg expansion. What's the point?

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Aug 19 '05 #9

P: n/a
On 19 Aug 2005 03:43:31 -0700
Paul Rubin wrote:
<en**********@ospaz.ru> writes:
import itertools
f = open("blah.txt", "r")
for c in itertools.chain(*f):


But that can burn an unlimited amount of memory if there are long
stretches of the file with no newlines. There's no real good way
around ugly code.


I agree. Moreover, in fact, it is the same as just

for c in f.read():
# ...

--
jk
Aug 19 '05 #10

P: n/a
Op 2005-08-19, Donn Cave schreef <do**@drizzle.com>:
Quoth "Greg McIntyre" <gr**@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.
IMO the confusion is the result of True and False appearing late.

IMO having python interpret None, '', (), {} and [] as false in
a conditional context goes against the spirit of:

In the face of ambiguity, refuse the temptation to guess.
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",


But '', {}, [] and () are not nothing. They are empty containers.
And 0 is not nothing either it is a number. Suppose I have
a variable that is either None if I'm not registered and a
registration number if I am. In this case 0 should be treated
as any other number.

Such possibilities, make me shy away from just using 'nothing'
as false and writing out my conditionals more explicitly.

--
Antoon Pardon
Aug 19 '05 #11

P: n/a
Antoon Pardon wrote:
But '', {}, [] and () are not nothing. They are empty containers.
And 0 is not nothing either it is a number. Suppose I have
a variable that is either None if I'm not registered and a
registration number if I am. In this case 0 should be treated
as any other number.


This is why None is a singleton::

if registration_number is None:
# do one thing
else:
# do another

In the OP's case, if file.read() had happened to return None instead of
the empty string, he probably would've wanted to do the same thing.
OTOH, people on python-dev have said that the file.read() idiom of
returning '' when it's done should be replaced by a true iterator, i.e.
using StopIteration. (I don't know the details of exactly how things
would change, but I suspect this is something that will happen in Python
3.0.)

STeVe
Aug 19 '05 #12

P: n/a
In article <sl********************@rcpc42.vub.ac.be>,
Antoon Pardon <ap*****@forel.vub.ac.be> wrote:
....
But '', {}, [] and () are not nothing. They are empty containers.
Oh come on, "empty" is all about nothing.
And 0 is not nothing either it is a number. Suppose I have
a variable that is either None if I'm not registered and a
registration number if I am. In this case 0 should be treated
as any other number.

Such possibilities, make me shy away from just using 'nothing'
as false and writing out my conditionals more explicitly.


Sure, if your function's type is "None | int", then certainly
you must explicitly check for None. That is not the case with
fileobject read(), nor with many functions in Python that
reasonably and ideally return a value of a type that may
meaningfully test false. In this case, comparison (==) with
the false value ('') is silly.

Donn Cave, do**@u.washington.edu
Aug 19 '05 #13

P: n/a
Alright, everyone seems to have gone off on a tangent here, so I'll try
to stick to your code...
"""
This is what I would ideally like:
f = open("blah.txt", "r")
while c = f.read(1):
# ... work on c
But I get a syntax error.
while c = f.read(1):
^
SyntaxError: invalid syntax

"""

That's because you are using an assignment operator instead of a
comparison operator. It should have been written like this:

while c == f.read(1):

that would be written correctly, though I don't think that is your
intention.
Try this novel implementation, since nobody has suggested it yet.
-----------------
import mmap

f = open("blah.txt", 'r+') #opens file for read/write
c = mmap.mmap(f.fileno(),0) #maps the file to be used as memory map...

while c.tell() < c.size():
print c.read_byte()
---------------
That accomplishes the same thing.

Aug 19 '05 #14

P: n/a
On 2005-08-19, sp*****@gmail.com <sp*****@gmail.com> wrote:
Alright, everyone seems to have gone off on a tangent here, so I'll try
to stick to your code... """
This is what I would ideally like:
f = open("blah.txt", "r")
while c = f.read(1):
# ... work on c
But I get a syntax error.
while c = f.read(1):
^
SyntaxError: invalid syntax

"""

That's because you are using an assignment operator instead of a
comparison operator.


That's because he wants an assignment operator. He also wants
"c = f.read(1)" to be an expression that evalutates to the
value of c after the assignment operator.

--
Grant Edwards grante Yow! .. I'm IMAGINING a
at sensuous GIRAFFE, CAVORTING
visi.com in the BACK ROOM of a
KOSHER DELI --
Aug 19 '05 #15

P: n/a
On Fri, 19 Aug 2005 16:31:47 +1000, John Machin <sj******@lexicon.net> wrote:
Bengt Richter wrote:
On 18 Aug 2005 22:21:53 -0700, "Greg McIntyre" <gr**@puyo.cjb.net> wrote:

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.

This is what I would ideally like:

f = open("blah.txt", "r")
while c = f.read(1):
# ... work on c


How about (untested):

for c in iter((lambda f=open('blah.txt', 'r'): f.read(1)), ''):
# ... work on c

:-)
Bengt, did you read on to the bit where the OP wanted to do it "more
nicely"? YMMV, but I think you've strayed into "pas devant les enfants"
territory.
(-:

LOL. Mais non ;-) OTOH, I think this might cross the line:

f = open('blah.txt')
while [c for c in [f.read(1)] if c!='']:
# ... work on c

;-)

Regards,
Bengt Richter
Aug 19 '05 #16

P: n/a
sp*****@gmail.com wrote:
Alright, everyone seems to have gone off on a tangent here, so I'll try
to stick to your code...
"""
This is what I would ideally like:
f = open("blah.txt", "r")
while c = f.read(1):
# ... work on c
But I get a syntax error.
while c = f.read(1):
^
SyntaxError: invalid syntax

"""

That's because you are using an assignment operator instead of a
comparison operator. It should have been written like this:

while c == f.read(1):

that would be written correctly, though I don't think that is your
intention.
Try this novel implementation, since nobody has suggested it yet.
-----------------
import mmap

f = open("blah.txt", 'r+') #opens file for read/write
c = mmap.mmap(f.fileno(),0) #maps the file to be used as memory map...

while c.tell() < c.size():
print c.read_byte()
---------------
That accomplishes the same thing.


Dear Sir or Madam,
I refer you to your recent post -- the one that started with "d'oh".
Regards,
John
Aug 19 '05 #17

P: n/a
On 18 Aug 2005 22:21:53 -0700
Greg McIntyre wrote:
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.

This is what I would ideally like:

f = open("blah.txt", "r")
while c = f.read(1):
# ... work on c


for data in iter(lambda:f.read(1024), ''):
for c in data:
# ... work on c

--
jk
Aug 20 '05 #18

P: n/a
> for data in iter(lambda:f.read(1024), ''):
for c in data:


What are the meanings of Commands 'iter' and 'lambda', respectively? I
do not want you to indicate merely the related help pages. Just your
ituitive and short explanations would be enough since I'm really newbie
to Python.

-James

Aug 20 '05 #19

P: n/a
James wrote:
for data in iter(lambda:f.read(1024), ''):
for c in data:


What are the meanings of Commands 'iter' and 'lambda', respectively? I
do not want you to indicate merely the related help pages. Just your
ituitive and short explanations would be enough since I'm really newbie
to Python.


No sorry, that's not how the newsgroup works. You read the documentation
first, then come back with specific questions about what you didn't
understand or couldn't find.

http://www.catb.org/~esr/faqs/smart-questions.html

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Aug 20 '05 #20

P: n/a
Robert Kern wrote:
http://www.catb.org/~esr/faqs/smart-questions.html


Is it a *smart* way or *necessary* way?

Plus, my question was not for the detail description but for the
intuitive guide leading the beginner's further study.

I understand that too many repeated talks make cyberian tired. However,
over and over discussions of basic concepts is also very important for
technology enhancements. Thus, Commands 'iter' and 'lambda' should be
discussed over and over about their necessity and convenience in the
news-group as long as they are the principle keywords distinguished from
the conventional languages like c/c++, pascal, etc.

-James
Aug 20 '05 #21

P: n/a
James Kim wrote:
Robert Kern wrote:

http://www.catb.org/~esr/faqs/smart-questions.html
Is it a *smart* way or *necessary* way?

Of course it's not *necessary*. I mean, the world isn't going to come
to an end if it doesn't happen. There is no logical contingency making
it so. But, if everyone in the group adheres to the ESR "smart
questions" guide, what's the difference?
Plus, my question was not for the detail description but for the
intuitive guide leading the beginner's further study.

But, I'll try to answer your question the best I can. From a
quasi-sensory intuitive level, ``iter`` is red - kinda warm - and smells
a little like cinnamon, but not too strong. ``lambda`` on the other
hand is blue-green, sometimes grey, cooler, almost cold, has a damp feel
to it, and tastes like pork - not chicken, mind you - that's the ``for``
statement.
I understand that too many repeated talks make cyberian tired. However,
over and over discussions of basic concepts is also very important for
technology enhancements.
Here's the deal. If you have a general question about something, ask
it. But ask smartly. For example, "What is the benefit of using
``iter`` as opposed to something else? What are the alternatives to
using ``iter``?" Asking questions like "What are the meanings of
Commands 'iter' and 'lambda'" will not fly well here - and you may find
less so elsewhere. The reason is, it smells of laziness (I'm not saying
you *are* lazy - that's just the impression it leaves) and this group is
full of people who have reached for the docs, wrestled with them, and
have come away from it better informed programmers.
Thus, Commands 'iter' and 'lambda' should be
discussed over and over about their necessity and convenience
This is different from what you were asking. I quoted your exact words
above and it's different from what you're asking here. And I'm not so
sure I would put a *should* on your statement. I think usage
discussions of different functions, standard library modules, practices,
etc. *will* arise perpetually. But I don't think we *need* to
constantly bat around the necessity of X keyword or Y function or Z
module. Convenience - probably. Necessity - no.
in the
news-group as long as they are the principle keywords distinguished from
the conventional languages like c/c++, pascal, etc.

-James

So, if you have a question that's in line with Robert's advice, please
post it and it will have a much higher chance of getting answered. I
sincerely hope this helps.
Jeremy Jones
Aug 20 '05 #22

P: n/a
James Kim wrote:
Robert Kern wrote:
http://www.catb.org/~esr/faqs/smart-questions.html
Is it a *smart* way or *necessary* way?


It's the polite way. And probably the only way you're going to get your
questions actually answered.

Read the documentation. If you still don't understand something, come
back and ask a specific question about what you didn't understand. Then
we will respond to your politeness with our own polite answer.

Until then, your rudeness gets my rudeness in response.
Plus, my question was not for the detail description but for the
intuitive guide leading the beginner's further study.

I understand that too many repeated talks make cyberian tired. However,
over and over discussions of basic concepts is also very important for
technology enhancements. Thus, Commands 'iter' and 'lambda' should be
discussed over and over about their necessity and convenience in the
news-group as long as they are the principle keywords distinguished from
the conventional languages like c/c++, pascal, etc.


Then use Google Groups to see that they have been, in great detail, and
at a higher level than giving a newbie an "intuitive" rundown of the
features.

Now go read the documentation.

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Aug 20 '05 #23

P: n/a
Robert Kern <rk***@ucsd.edu> writes:
http://www.catb.org/~esr/faqs/smart-questions.html

Is it a *smart* way or *necessary* way?


It's the polite way. And probably the only way you're going to get
your questions actually answered.


I wonder if there's a way to killfile posts that contain that url.
They are cluttering up the newsgroup much more than repeated newbie
questions do.

Sheesh people, if you see a question that you don't feel like
answering, then don't answer.
Aug 20 '05 #24

P: n/a
On 2005-08-20, James <tx*********@hotmail.com> wrote:
for data in iter(lambda:f.read(1024), ''):
for c in data:
What are the meanings of Commands 'iter' and 'lambda', respectively? I
do not want you to indicate merely the related help pages.


Rude much?

If somebody is kind enough to point out the documentation that
answers your question you ought to read it.
Just your ituitive and short explanations would be enough
since I'm really newbie to Python.


What makes you think my "intuitive and short" explanation is
goign to be better than what's aready written? Why should I
take the time?

--
Grant Edwards grante Yow! People humiliating
at a salami!
visi.com
Aug 20 '05 #25

P: n/a
Paul Rubin wrote:
Robert Kern <rk***@ucsd.edu> writes:
http://www.catb.org/~esr/faqs/smart-questions.html

Is it a *smart* way or *necessary* way?
It's the polite way. And probably the only way you're going to get
your questions actually answered.


I wonder if there's a way to killfile posts that contain that url.
They are cluttering up the newsgroup much more than repeated newbie
questions do.


You can get a good start by killfiling me.
Sheesh people, if you see a question that you don't feel like
answering, then don't answer.


Same goes to you. You don't like the "smart-questions.html" response, so
why do you respond? Because you want to change people's behavior. Or
perhaps because it pleases you to express your displeasure about it
(regardless of any effect that expression might have on other people).

Coincidentally, those are exactly the reasons why I posted it in the
first place. I care not a whit about decluttering the newgroup, an
impossible task.

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Aug 20 '05 #26

P: n/a
On 19 Aug 2005 23:13:44 -0700, "James" <tx*********@hotmail.com> wrote:
for data in iter(lambda:f.read(1024), ''):
for c in data:


What are the meanings of Commands 'iter' and 'lambda', respectively? I
do not want you to indicate merely the related help pages. Just your
ituitive and short explanations would be enough since I'm really newbie
to Python.

Would you please read the above, as if you were someone else?
The above sounds to me like you think you're typing commands
to an enhanced google, or worse, to an abused employee or servant.

To say "I do not want you to ..." sounds so arrogantly presumptious
that I'm sure if that "works" for you IRL, you must be living in a very
pampered and sheltered environment.

The downside of such environments is that if simple demanding "works"
and you get things and services from people as if they were robots,
you lose out on the thing that draws most of us, I think, to c.l.p
and similar social spaces -- which is a feeling of shared consciousness
and contact with other humans within a sphere common interests.

You're welcome to try again ;-)

(BTW, sorry if "James" doesn't mean English is your mother tongue, and I have
misinterpreted your manner of expression. If so, this may still be a useful
indication to you of how wording can determine response ;-)

Regards,
Bengt Richter
Aug 20 '05 #27

P: n/a
Robert Kern 쓴 글:

Now go read the documentation.


Thanks to your comments, I read the corresponding helps searched by
Google. (Sorry to say a specific search engine here, but I must say that
it is really convinient.)

Now I realized that Command 'lambda' is a similar to Command 'inline' in
C++. In addition, Command 'iter' is something new but not much new to c
engineers, since it is related to 'for loops', e.g.,
s = 'abc'; it = iter(s); it.next()


I would want to express my appreciation to Paul, Robert, Jeremy, Grant,
and Bengt, who provide good guidelines to get the answers in newsgroups.

-James
Aug 21 '05 #28

P: n/a
James Sungjin Kim <ki***@mobile.snu.ac.kr> writes:
Now I realized that Command 'lambda' is a similar to Command 'inline'
in C++. In addition, Command 'iter' is something new but not much new
to c engineers, since it is related to 'for loops', e.g.,


Actually not related at all. Nothing like lambda or iter exist in
C++. They are a bit complicated to explain to newbies (unless you've
programmed in Lisp or in functional-programming languages), thus the
suggestion of looking in the docs. That's also the reason that
suggesting using lambda and iter that way was considered a bad answer
to "how do you write something like 'while c = f.read(1)'".

Anyway, quick explanation of lambda: it's a way of creating functions
without having to give then names. Example:

lambda x: x*x

is a function that computes the square of x. So you could say

n = (lambda x: x*x)(3)

which sets n = 9.

There is a faction on clpy which says lambda is bad and all functions
should have their own names. Others say they're useful for things
like callbacks, and requiring all functions to be named makes no more
sense than requiring all intermediate results in infix expressions to
be named.

You unfortunately happened to trip into a slightly contentious topic
on clpy and got flamed a bit as a result.

I won't explain iter here, since it's more complex than lambda.
Aug 21 '05 #29

P: n/a
John Machin wrote:
... AND it's about time that list is updated to include False explicitly
-- save nitpicking arguments about whether False is covered by
"numeric zero of all types" :-)


Done.
If I try:

f = open("blah.txt", "r")
while (c = f.read(1)) != '':
# ... work on c

I get a syntax error also. :(

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

Thanks


How about
for c in f.read():
?
Note that this reads the whole file into memory (changing \r\n to \n on
Windows) ... performance-wise for large files you've spent some memory
but clawed back the rather large CPU time spent doing f.read(1) once per
character. The "more nicely" factor improves outasight, IMHO.

Mild curiosity: what are you doing processing one character at a time
that can't be done with a built-in function, a standard module, or a
3rd-party module?


Don't forget

for line in f:
for c in line:
# do stuff

Reinhold
Aug 21 '05 #30

P: n/a
Reinhold Birkenfeld <re************************@wolke7.net> writes:
Don't forget

for line in f:
for c in line:
# do stuff


As mentioned before, that's careless programming, since it can read
the whole file into memory if the file contains no newlines.
Aug 21 '05 #31

P: n/a
Reinhold Birkenfeld wrote:
John Machin wrote:

... AND it's about time that list is updated to include False explicitly
-- save nitpicking arguments about whether False is covered by
"numeric zero of all types" :-)

Done.


Thanks -- those of us who actually read manuals salute you.

w about
for c in f.read(): [snip]

Don't forget

for line in f:
for c in line:
# do stuff


OK. I'll pay that one.
Aug 21 '05 #32

P: n/a
Paul Rubin wrote:
Reinhold Birkenfeld <re************************@wolke7.net> writes:
Don't forget

for line in f:
for c in line:
# do stuff

As mentioned before, that's careless programming, since it can read
the whole file into memory if the file contains no newlines.


I agree that there may be circumstances where this naiive approach is
sub-optimal. However, calling this careless programming is a bit over
the top. Reading files into memory is often the preferred approach
nowadays, and on a modern laptop (say) files several megabytes in size
will be processed perfectly happily.

Efficiency is good, but remember Kernighan and Plauger (elements of
Programming Style): First, make it work. Then (if it doesn't work fast
enough) make it work faster.

Most times the simple solution works for the problem under
consideration, and useless optimization work is avoided.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Aug 21 '05 #33

P: n/a
Op 2005-08-19, Donn Cave schreef <do**@u.washington.edu>:
In article <sl********************@rcpc42.vub.ac.be>,
Antoon Pardon <ap*****@forel.vub.ac.be> wrote:
...
But '', {}, [] and () are not nothing. They are empty containers.
Oh come on, "empty" is all about nothing.


No it is not. There are situation where False or None should
be treated differently from an empty sequence.

Empty can mean, "nothing yet" which should be treated
differently from "nothomg more".
And 0 is not nothing either it is a number. Suppose I have
a variable that is either None if I'm not registered and a
registration number if I am. In this case 0 should be treated
as any other number.

Such possibilities, make me shy away from just using 'nothing'
as false and writing out my conditionals more explicitly.


Sure, if your function's type is "None | int", then certainly
you must explicitly check for None.


The fact is that python doesn't know which type a function is.
So why does python guess that zero should be treated as false.
That is not the case with
fileobject read(), nor with many functions in Python that
reasonably and ideally return a value of a type that may
meaningfully test false. In this case, comparison (==) with
the false value ('') is silly.


No is is not. The comparison with the specific false value
makes it easier for the reader of the code to find out what
to expect. I also find the use of '' as false in this context
wrong. A read can be used on all kind of objects including
a network connection. Returning '' on a network read would
be IMO the most natural answer to say, the network connection
is still open but no data is available for the moment. '' here
would mean "nothing yet" while '' is now made into "nothing more"

--
Antoon Pardon
Aug 22 '05 #34

P: n/a
Okay, the 1st option seems more complicated and the 2nd option, while
simpler to my eye makes me worry about file descriptors, resource
management and memory running out.

My files are large, hence 1 character at a time, not f.read().

This is code from another employee and I'm just in the stages of going
through it and doing a basic clean-up before I get on to a proper
efficiency assessment, hence I don't want to change the way it works,
just make it as short and lucid as I can.

Your suggestion using the generator expression again seems more complex
than the original.

They're good suggestions though. Thank you! I'm just now catching up
with everybody's comments. Some of them seem quite entriguing.

Aug 22 '05 #35

P: n/a
The 2nd option has real potential for me. Although the total amount of
code is greater, it factors out some complexity away from the actual
job, so that code is not obscured by unnecessary compexity. IMHO that's
great practice.

I like it! Thank you! The assurance that the code was clear was good
too - that is also what I need to hear (decisively dismissing the quest
for something shorter and punchier will make me happy as much as
succeeding in it).

I'll read all the other suggestions first though.

Aug 22 '05 #36

P: n/a
Donn Cave wrote:
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.
Sorry that was patently untrue - as far as the while loop is concerned
'' and False both cause the loop to exit so for all intents and
purposes, in that context, '' may as well equal False.

I think True and False constants are a good idea. And I like the way it
worked. The reason I got confused though was because I cannot do this:

while c = f.read(1):
# ...

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.
I'm all in favour of logic that looks like:

if '' or 0 or {} or None:
# never gets done
else:
# always gets done

My confusion stems from the syntax error not from Python's boolean
logic. Sorry, my statement at the end regarding '' != False was a bit
of a red herring. :\

I'm also in the habit of doing things like this:

def f(dict=None):
dict = dict or {}
# ...

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.
Ah but if it helps me to understand why Python forces me to do it then
although it won't save 3 lines it will stop me from complaining and
posting naff newbie questions. ;)

| 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.


Okay well that is reassuring but a little disappointing.

Are there any plans (PEPs?) in the distant future to unify statements
and expressions in the Python syntax so I can generally do things like
this:

x = if aboolean:
<expression1>
else:
<expression2>

and

while c = f.read(1):
# ...

I couldn't find any general PEPs along these lines, only specific ones
(e.g. 308 re. an if-then-else expression). It does seem quirky given
Python's indentation syntax. :( However I notice I can already do some
things I wouldn't expect given a strict statement/expression
separation, such as:

x = y = z = 0

I suppose I have to learn these as special cases. (?)

Aug 22 '05 #37

P: n/a
I've always accepted the None vs. 0 as a cavaet of the added
convenience but I think it's ultimately worth it.

Sorry, I didn't want to start a
"nothing values evaluate to false" argument.

I'll go read python-dev archives a bit and see if there's anything
useful for me to know.

Thanks

Aug 22 '05 #38

P: n/a
"Greg McIntyre" <gr**@puyo.cjb.net> writes:
while c = f.read(1):
# ...

I couldn't find any general PEPs along these lines, only specific ones
(e.g. 308 re. an if-then-else expression).


I often end up doing something like this:

class foo:
def set(self, x):
self.x = x
return x
c = foo()

while c.set(f.read(1)):
# do stuff with c.x

In that file example, it's too much nuisance, but when you're
comparing some input against a series of regexps and you'd otherwise
need a multi-line construction for each one, this method comes in
quite handy.
Aug 22 '05 #39

P: n/a
John Machin wrote:
Is some way to make this code more compact and simple? It's a bit
spaghetti.
Not at all, IMHO. This is a simple forward-branching exit from a loop in
explicable circumstances (EOF). It is a common-enough idiom that doesn't
detract from readability & understandability. Spaghetti is like a GOTO
that jumps backwards into the middle of a loop for no discernable reason.


While that is true, I had high hopes that I could do this:

while c = f.read(1): # ...

And relative to that, it is more complex. And although I am nit-picking
to try to simplify this code, I wanted to understand why Python works
in this way (even if that's just "historical reasons"), and check to
see if there was not some shorter more modern Pythonic alternative.

I did actually like Robert Kern's suggestion which used an iterator and
a function to factor out the complexity of setting it up. I think that
is actually better code than the original.

It matches my philosophy in programming of pushing complexity *out* of
the code which does the actual job, even if it means writing a few
support functions/classes/whatever. I know they can be re-used and
refined and I know that it is the code that does the actual job that is
most likely to be rewritten in future revisions of the code with shifts
in requirements.

You have a bit of a misunderstanding here that needs correcting:

In "if <blah>" and "while <blah>", <blah> is NOT restricted to being in
(True, False). See section 5.10 of the Python Reference Manual:
I'm sorry! I realise that now and I'm sorry to have caused the traffic
I did. Thank you for pointing it out to me though - it's pretty
fundamental Python!

*Greg thumbtacks a note to his forehead*

How about
for c in f.read():
?
Note that this reads the whole file into memory (changing \r\n to \n on
Windows) ... performance-wise for large files you've spent some memory
but clawed back the rather large CPU time spent doing f.read(1) once per
character. The "more nicely" factor improves outasight, IMHO.
I would if only I had any kind of guarrantee on the file size but I
don't - this code is for reading a header out of a binary file which
uses delimiters and escape characters to mark out its fields. I didn't
design the format, but after cleaning up the code that deals with it, I
may *re*design it. ;)

Mild curiosity: what are you doing processing one character at a time
that can't be done with a built-in function, a standard module, or a
3rd-party module?


Our company is designing a new file type. *sigh*. Confidentiality
prevents me from saying any more, too. If that bugs you because it's
not open source, sorry I need a job. Don't worry though, I'm developing
an open source remote GUI for the code management system we're using
called Aegis (http://aegis.sf.net). It's not sufficiently implemented
yet to warrant posting publically (I'd describe its current state as
"framework") but if anybody reading this is interested then give me a
yell and it'll have a public project page or something overnight. ;)

Aug 22 '05 #40

P: n/a
That is both clever and useful! I never would have thought of doing
that.

This seems to me like a general way to "workaround" the Python
statement/expression separation woes I've been having, in cases where I
really really want it.

Now, where can I copy this out to so I will be able to find it when the
occasion arises? Hmm... *jot jot jot*

Thanks muchly! :-)

Aug 22 '05 #41

P: n/a
Greg McIntyre wrote:
The 2nd option has real potential for me. Although the total amount of
code is greater, it factors out some complexity away from the actual
job, so that code is not obscured by unnecessary compexity. IMHO that's
great practice.


Please quote the message you are replying to. We have no idea what "the
2nd option" is.

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Aug 22 '05 #42

P: n/a
Antoon Pardon wrote:
Op 2005-08-19, Donn Cave schreef <do**@u.washington.edu>:
In article <sl********************@rcpc42.vub.ac.be>,
Antoon Pardon <ap*****@forel.vub.ac.be> wrote:
...
But '', {}, [] and () are not nothing. They are empty containers.
Oh come on, "empty" is all about nothing.

No it is not. There are situation where False or None should
be treated differently from an empty sequence.

Empty can mean, "nothing yet" which should be treated
differently from "nothomg more".

And 0 is not nothing either it is a number. Suppose I have
a variable that is either None if I'm not registered and a
registration number if I am. In this case 0 should be treated
as any other number.

Such possibilities, make me shy away from just using 'nothing'
as false and writing out my conditionals more explicitly.


Sure, if your function's type is "None | int", then certainly
you must explicitly check for None.

The fact is that python doesn't know which type a function is.
So why does python guess that zero should be treated as false.

Python doesn't guess. There are a range of values that will be treated,
in a Boolean context (how perlish) as equivalent to False. If your
function is capable of validly returning any of these values then your
calls must be prepared to discriminate between (say) zero and False or
None. If not, the calling experession in the "if" can be simpler.
That is not the case with
fileobject read(), nor with many functions in Python that
reasonably and ideally return a value of a type that may
meaningfully test false. In this case, comparison (==) with
the false value ('') is silly.

No is is not. The comparison with the specific false value
makes it easier for the reader of the code to find out what
to expect. I also find the use of '' as false in this context
wrong. A read can be used on all kind of objects including
a network connection. Returning '' on a network read would
be IMO the most natural answer to say, the network connection
is still open but no data is available for the moment. '' here
would mean "nothing yet" while '' is now made into "nothing more"

Yes, but you are restricting the programmer's range of expression if you
promote this as a general rule. Sometimes it's important to discriminate
between "", (), [] and None, sometimes there is no possiblity that
confusion will arise.

When there's no possibility of confusion you arae just picking nits
(which I know your sense of intellectual tidiness encourages you to do ;-).

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Aug 22 '05 #43

P: n/a
Greg McIntyre wrote:
John Machin wrote:
Is some way to make this code more compact and simple? It's a bit
spaghetti.
Not at all, IMHO. This is a simple forward-branching exit from a loop in
explicable circumstances (EOF). It is a common-enough idiom that doesn't
detract from readability & understandability. Spaghetti is like a GOTO
that jumps backwards into the middle of a loop for no discernable reason.

While that is true, I had high hopes that I could do this:

while c = f.read(1): # ...

And relative to that, it is more complex. And although I am nit-picking
to try to simplify this code, I wanted to understand why Python works
in this way (even if that's just "historical reasons"), and check to
see if there was not some shorter more modern Pythonic alternative.

Guido explicitly decided he wanted a clear differentiation between
expressions and statements, and that assignment was to be a statement.
The logic behind this design decision is documented in
http://www.python.org/doc/faq/genera...-an-expression

which may have already been mentioned in this thread.
I did actually like Robert Kern's suggestion which used an iterator and
a function to factor out the complexity of setting it up. I think that
is actually better code than the original.
There are many elegant ways to express iterative solutions in Python,
and generator expressions are frequently useful in this context as well.
It matches my philosophy in programming of pushing complexity *out* of
the code which does the actual job, even if it means writing a few
support functions/classes/whatever. I know they can be re-used and
refined and I know that it is the code that does the actual job that is
most likely to be rewritten in future revisions of the code with shifts
in requirements.
You are likely to be happy with Python, then. Most Python programmers
are pragmatists.
You have a bit of a misunderstanding here that needs correcting:

In "if <blah>" and "while <blah>", <blah> is NOT restricted to being in
(True, False). See section 5.10 of the Python Reference Manual:

I'm sorry! I realise that now and I'm sorry to have caused the traffic
I did. Thank you for pointing it out to me though - it's pretty
fundamental Python!

Yes, but it's a common question from newcomers (hence its appearance in
the FAQ), and there's usually some interesting discussion when it comes
up. Fortunately c.l.py isn't the kind of place you will usually
experience "Read the FAQ!" abuse. We try to remember that Python's
popularity is growing so fast that about a third of readers at any time
are likely to be newbies to Python (albeit many of them are experienced
in other programming languages).
*Greg thumbtacks a note to his forehead*
Ouch!

How about
for c in f.read():
?
Note that this reads the whole file into memory (changing \r\n to \n on
Windows) ... performance-wise for large files you've spent some memory
but clawed back the rather large CPU time spent doing f.read(1) once per
character. The "more nicely" factor improves outasight, IMHO.

I would if only I had any kind of guarrantee on the file size but I
don't - this code is for reading a header out of a binary file which
uses delimiters and escape characters to mark out its fields. I didn't
design the format, but after cleaning up the code that deals with it, I
may *re*design it. ;)

If you *know* that the header is MAX characters maximum you could try

for c in f.read(MAX):
...
Mild curiosity: what are you doing processing one character at a time
that can't be done with a built-in function, a standard module, or a
3rd-party module?

Our company is designing a new file type. *sigh*. Confidentiality
prevents me from saying any more, too. If that bugs you because it's
not open source, sorry I need a job. Don't worry though, I'm developing
an open source remote GUI for the code management system we're using
called Aegis (http://aegis.sf.net). It's not sufficiently implemented
yet to warrant posting publically (I'd describe its current state as
"framework") but if anybody reading this is interested then give me a
yell and it'll have a public project page or something overnight. ;)

Good luck.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Aug 22 '05 #44

P: n/a
Op 2005-08-22, Steve Holden schreef <st***@holdenweb.com>:
Antoon Pardon wrote:
Op 2005-08-19, Donn Cave schreef <do**@u.washington.edu>:
In article <sl********************@rcpc42.vub.ac.be>,
Antoon Pardon <ap*****@forel.vub.ac.be> wrote:
...

But '', {}, [] and () are not nothing. They are empty containers.

Oh come on, "empty" is all about nothing.

No it is not. There are situation where False or None should
be treated differently from an empty sequence.

Empty can mean, "nothing yet" which should be treated
differently from "nothomg more".

And 0 is not nothing either it is a number. Suppose I have
a variable that is either None if I'm not registered and a
registration number if I am. In this case 0 should be treated
as any other number.

Such possibilities, make me shy away from just using 'nothing'
as false and writing out my conditionals more explicitly.

Sure, if your function's type is "None | int", then certainly
you must explicitly check for None.

The fact is that python doesn't know which type a function is.
So why does python guess that zero should be treated as false.

Python doesn't guess. There are a range of values that will be treated,
in a Boolean context (how perlish) as equivalent to False.


Yes it does. Python has no way to know what would be the most
usefull Boolean interpretation of these values in a particular
context. That it picks one out is guessing. Lisp imterprets
an empty list as false, scheme interprets it as true. So
both seem usable interpretations.
If your
function is capable of validly returning any of these values then your
calls must be prepared to discriminate between (say) zero and False or
None. If not, the calling experession in the "if" can be simpler.


But that doesn't seem to be accepted practice in this newsgroup.
Whenever someone shows code that does something like:

if var != []:
...

or

if var is True:

Someone else is almost bound to react that it is better to
write this as:

if var:
IMO it is the fact that python accepts almost anything as
true that may make it necessary to use "var is True"
That is not the case with
fileobject read(), nor with many functions in Python that
reasonably and ideally return a value of a type that may
meaningfully test false. In this case, comparison (==) with
the false value ('') is silly.

No is is not. The comparison with the specific false value
makes it easier for the reader of the code to find out what
to expect. I also find the use of '' as false in this context
wrong. A read can be used on all kind of objects including
a network connection. Returning '' on a network read would
be IMO the most natural answer to say, the network connection
is still open but no data is available for the moment. '' here
would mean "nothing yet" while '' is now made into "nothing more"

Yes, but you are restricting the programmer's range of expression if you
promote this as a general rule. Sometimes it's important to discriminate
between "", (), [] and None, sometimes there is no possiblity that
confusion will arise.

When there's no possibility of confusion you arae just picking nits
(which I know your sense of intellectual tidiness encourages you to do ;-).


IMO there is more possibility of confusion then you think off.

Sure if you restrict your attention to one specific part of code, you
can conclude that there is no possibility of confusion whether '' is
used as false or not. But maybe sometime in the future you would want
that piece of code to work with other pieces of code where it is not
usefull to have '' interpreted as false in a Boolean context.
Now suddenly whether '' is false or not depends on where it is coming
from and your code with no possibilty of confusion is part of
a project where it is contributing to the confusion.

--
Antoon Pardon
Aug 22 '05 #45

P: n/a
Op 2005-08-22, Steve Holden schreef <st***@holdenweb.com>:
Greg McIntyre wrote:
John Machin wrote:
Is some way to make this code more compact and simple? It's a bit
spaghetti.

Not at all, IMHO. This is a simple forward-branching exit from a loop in
explicable circumstances (EOF). It is a common-enough idiom that doesn't
detract from readability & understandability. Spaghetti is like a GOTO
that jumps backwards into the middle of a loop for no discernable reason.

While that is true, I had high hopes that I could do this:

while c = f.read(1): # ...

And relative to that, it is more complex. And although I am nit-picking
to try to simplify this code, I wanted to understand why Python works
in this way (even if that's just "historical reasons"), and check to
see if there was not some shorter more modern Pythonic alternative.

Guido explicitly decided he wanted a clear differentiation between
expressions and statements, and that assignment was to be a statement.
The logic behind this design decision is documented in

http://www.python.org/doc/faq/genera...-an-expression

which may have already been mentioned in this thread.


I can't help but find this a very poor reason for this decision.
Sure it is a hard to find bug. but that is not because the
assignment is also an expression but because the assigment operator
looks so much like an equality comparator. ':=' was already in use
as an assignment is a number of languages and using it would
have handled the typo problem just as well while still allowing
assignments in expressions. This answer gives me the impression
the matter wasn't thought through thoroughly.

--
Antoon Pardon
Aug 22 '05 #46

P: n/a
Antoon Pardon wrote:
Python doesn't guess. There are a range of values that will be treated,
in a Boolean context (how perlish) as equivalent to False.
Yes it does.


No it doesn't!
Python has no way to know what would be the most
usefull Boolean interpretation of these values in a particular
context.
It's hardly the task of the interpreter to try to do that.
That it picks one out is guessing.
No, it simply follows a well defined specification.
See http://docs.python.org/ref/Booleans.html
There is no guessing involved in that.
Lisp imterprets
an empty list as false, scheme interprets it as true. So
both seem usable interpretations.


You might argue that *Guido* was guessing when he decided what
the most useful behaviour of Python would be in this case, and
there's probably some truth in that, just as there is some
guesswork involved in most programming language design decisions,
but that's another thing. That's not Python guessing, it's
Guido using his excellent lanugage design skills. It seems most
Python programmers agree that he "guessed" right here, as usual.

(Perhaps you thought that "Python" was the name of the language
designer. It's not. Python's design is led by Guido van Rossum,
and the name Python comes from a (mostly) British comedy group.)

You might also argue that this behaviour is counter to the
Python dogma of "explicit is better than implicit". Python also
allows you to get a float out of an expression such as "2*3.1"
without forcing an explicit cast, as in "float(2)*3.1".

You should note that the first Python tenet is "Beautiful is
better than ugly" and that's probably what we have to blame here.

There seems to be close to a consensus, that "if users:" is more
beautiful than e.g. "if len(users) > 0:" or
"if (len(users)==0)==False" or for that matter
"if ((len(users)==0)==False)==True" or
"if (((len(users)==0)==False)==True)==True" etc.

What's true and false for Python, belongs to the few things you
actually have to learn, and I can appreciate that it's annoying
for a frequent schemer to remember that it's not the same in
Python, but it seems that very few people argue with the way
Python behaves in this respect.
Aug 22 '05 #47

P: n/a
"Greg McIntyre" <gr**@puyo.cjb.net> writes:
My files are large, hence 1 character at a time, not f.read().
There are alternatives between the two. You could read in a chunk of
reasonable size for your platform. Say 10meg on a recent workstation,
or 100meg on a current workstation.
This is code from another employee and I'm just in the stages of going
through it and doing a basic clean-up before I get on to a proper
efficiency assessment, hence I don't want to change the way it works,
just make it as short and lucid as I can.


Well, the thing that has been hinted around but not explicitly stated
is that doing thing one character at a time in Python is a "code
smell", by which I mean it's an indication that there could be a
better way to do things, and it's probably worthwhile spending a
little time looking for it. On the other hand, if you've already
planned another pass over the code, that might be the time to look
into this.

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Aug 22 '05 #48

P: n/a
Before leaving this topic, I wanted to make a rare visit
to the ruins of Google's USENET archive and pull out this
giant post on the subject of True and False, when they were
being considered for adoption into Python. There is some
stuff to ignore, where she addresses questions that didn't
go anywhere, but she goes on to write a well articulated
case that makes very interesting reading, and possibly has
had some effect on how people think about it around here.

http://groups-beta.google.com/group/...e5e1c8384c0360

Donn Cave, do**@u.washington.edu
Aug 22 '05 #49

P: n/a
Robert Kern wrote:
Paul Rubin wrote:
Robert Kern <rk***@ucsd.edu> writes:

>http://www.catb.org/~esr/faqs/smart-questions.html

Is it a *smart* way or *necessary* way?

It's the polite way. And probably the only way you're going to get
your questions actually answered.
I wonder if there's a way to killfile posts that contain that url.
They are cluttering up the newsgroup much more than repeated newbie
questions do.

You can get a good start by killfiling me.

*plonk* :-)
Sheesh people, if you see a question that you don't feel like
answering, then don't answer.

Same goes to you. You don't like the "smart-questions.html" response, so
why do you respond? Because you want to change people's behavior. Or
perhaps because it pleases you to express your displeasure about it
(regardless of any effect that expression might have on other people).

Coincidentally, those are exactly the reasons why I posted it in the
first place. I care not a whit about decluttering the newgroup, an
impossible task.

It's clear that you care not a whit about it. Unfortunately the only way
to preserve bandwidth on this (or any other) chanell is for those with
nothing to say to not say it.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

Aug 22 '05 #50

75 Replies

This discussion thread is closed

Replies have been disabled for this discussion.