Result of an assignment

9 views
Skip to first unread message

Ka-Ping Yee

unread,
Jun 14, 1996, 3:00:00 AM6/14/96
to

I know that there are a lot of intelligent things in
Python, and i'm impressed by many of its features.
But there are still a couple things that bother me,
so if anyone could spare a moment to educate me i'd
appreciate it.

Could someone kindly explain why there is a good reason
for Python not to produce the result of an assignment
in expressions? It seems puzzling that you should be
able to do

x = y = z = 0

in Python but not

while (foo = sys.stdin.readline()):
...

The only method i can find to do the latter is

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

which seems rather ugly for such a simple operation.

Am i missing something here? What do you gain by
explicitly preventing assignments from producing a
value?

(Please cc followups to kr...@novice.uwaterloo.ca.)


Many thanks,


Ping

Glenn T. Colby

unread,
Jun 14, 1996, 3:00:00 AM6/14/96
to


On Fri, 14 Jun 1996, Ka-Ping Yee wrote:

> Could someone kindly explain why there is a good reason
> for Python not to produce the result of an assignment
> in expressions? It seems puzzling that you should be
> able to do

We had a similar discussion about a month ago and I believe it comes down
to programming style. There are those of us that believe that
expressions should not produce any internal side effects. An assignment
is an assignment, an expression is an expression, and never the twain
should meet.

I think this thread should stop here though. The discussions last month
pretty much covered this issue.

--Glenn

~~~~~~~~~~~~~~~~~~~~~~~~~
Glenn T. Colby
The Jackson Laboratory
<g...@informatics.jax.org>

Ka-Ping Yee

unread,
Jun 14, 1996, 3:00:00 AM6/14/96
to

I wrote:
>
> Could someone kindly explain why there is a good reason
> for Python not to produce the result of an assignment
> in expressions?

Skip Montanaro wrote:
>
> Simple. Assignment statements are not expressions. Now, write 100 times:
>
> Python is not C.

*sigh* I was afraid of getting an answer like this. Of course
i know that Python is not the same language as C. But this
does not constitute an explanation or rationale for the decision.

Glenn Colby wrote:
>
> We had a similar discussion about a month ago and I believe it comes down
> to programming style. There are those of us that believe that
> expressions should not produce any internal side effects. An assignment
> is an assignment, an expression is an expression, and never the twain
> should meet.

Really? Like

def foo(x): x[0] = 3; return x

x = [7,8,9]
y = [1,2,3]

z = foo(x) + y

has no side-effects?!

My question was whether we actually gain anything by explicitly
disabling Python in this respect. Adding the ability to use the
results of an assignment does not prevent you from personally
avoiding the practice; but the current method *prevents* writing

while (ipt = sys.stdin.readline()):
...

which (i think) is a helluva lot clearer and more concise than

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

The latter destroys the meaning of the "while" construct and
makes me feel like i am writing a series of gotos, while the
former clearly identifies the condition as sys.stdin.readline().

I was asking if (a) there's a better way to write this in the
current Python, and (b) if there is some advantage to writing
it the latter way that i can't see. Right now, i don't.


Ping

Skip Montanaro

unread,
Jun 14, 1996, 3:00:00 AM6/14/96
to


Could someone kindly explain why there is a good reason
for Python not to produce the result of an assignment
in expressions?

Simple. Assignment statements are not expressions. Now, write 100 times:

Python is not C.

When you are finished with that, I have some erasers for you to clean... :-)


Skip Montanaro | Today's Acronym: YAUWWWI (yow'-ee) Yet Another Useless
sk...@calendar.com | World-Wide Web Idea
(518)372-5583 | --- Check out Musi-Cal: http://concerts.calendar.com/

Mark Lutz

unread,
Jun 14, 1996, 3:00:00 AM6/14/96
to

>> for ipt in sys.stdin.readlines():
>>
>> [...]
>
> -- or if you are trying to make an interactive session! :)

Sure. But OTOH, this issue's been debated many times in the past.
A lot of "if...break" statements could be written in the time it
will take to debate it again :-).

YMMV,
Mark L.

Mark Lutz

unread,
Jun 14, 1996, 3:00:00 AM6/14/96
to

> [looking for an alternative to the while/if construct...]

You might try this:


for ipt in sys.stdin.readlines():
...

Consise, and often faster than a while/if. The only drawback - it
loads the entire file into memory all at once (into a list of strings),
which only is a factor for huge files, small machines, or pipes.

Mark L.

Steven D. Majewski

unread,
Jun 14, 1996, 3:00:00 AM6/14/96
to

On Fri, 14 Jun 1996, Chris Hoffmann wrote:

>
> Besides the philosophical purity issue, there is the fact that
> allowing assignments to act like expressions makes it easier to
> accidentally type
>
> while (ipt == sys.stdin.readline()):
>

Python still allows DIFFERENT sets of typo's, for example:

>>> n = 2
>>> a = b = n
>>> a,b,n
(2, 2, 2)

>>> a = n == n
>>> a,b,n
(1, 2, 2)

Or how about the difference between "(1)" and "(1,)" .
Python's got its own set of "gotcha's" -- that argument is
a red herring.

Rule #1: The *ONLY* way to reduce error is through redundancy.
[ Rule #2 is: "The ONLY way to reduce error is redundancy, really!" --
one of these days I'm going to get around to writing a long promised
essay on "How I learned Analytical Redundancy the hard way" ]

If you want to outlaw those sorts of typo's, the only effective way
I know of is thru strict and static type-checking.

---| Steven D. Majewski (804-982-0831) <sd...@Virginia.EDU> |---
---| Computer Systems Engineer University of Virginia |---
---| Department of Molecular Physiology and Biological Physics |---
---| Box 449 Health Science Center Charlottesville,VA 22908 |---
[ "The grass is always greener, except at t=0" - Stan Kelly-Bootle ]


Ka-Ping Yee

unread,
Jun 14, 1996, 3:00:00 AM6/14/96
to

Mark Lutz wrote:
>
> You might try this:
>
> for ipt in sys.stdin.readlines():
> ...
>
> Consise, and often faster than a while/if. The only drawback - it
> loads the entire file into memory all at once (into a list of strings),
> which only is a factor for huge files, small machines, or pipes.

-- or if you are trying to make an interactive session! :)

(Yes, i have already read all the language vs. language comparisons -- but
it's a bummer to have to write "while 1: // ipt = sys.stdin.readline() //
if not ipt: break" when you're used to "while (<>)".)


Ping

Skip Montanaro

unread,
Jun 14, 1996, 3:00:00 AM6/14/96
to

Steven D. Majewski writes:

Now, Skip -- He's not the one who brought up C, *you* are!
I know that's where most of the comments of this sort are comming
from, so I can excuse your "knee jerk" reaction, but what he
actually wrote is a more subtle criticism that what you seem to have
read -- no reference to C, but only to Python's own internal
consistency:

Jiminy Crickets, Pinoch! I guess I should have used more smileys...

:-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-)

There. I hope that's enough...

Steven D. Majewski

unread,
Jun 14, 1996, 3:00:00 AM6/14/96
to

On Fri, 14 Jun 1996, Skip Montanaro wrote:
>
> Could someone kindly explain why there is a good reason
> for Python not to produce the result of an assignment
> in expressions?
>
> Simple. Assignment statements are not expressions. Now, write 100 times:
>
> Python is not C.
>
> When you are finished with that, I have some erasers for you to clean... :-)
>

Now, Skip -- He's not the one who brought up C, *you* are!


I know that's where most of the comments of this sort are comming
from, so I can excuse your "knee jerk" reaction, but what he
actually wrote is a more subtle criticism that what you seem to have
read -- no reference to C, but only to Python's own internal
consistency:

On Fri, 14 Jun 1996, Ka-Ping Yee wrote:

> Could someone kindly explain why there is a good reason
> for Python not to produce the result of an assignment

> in expressions? It seems puzzling that you should be
> able to do
>

> x = y = z = 0
>
> in Python but not
>
> while (foo = sys.stdin.readline()):
> ...

The appearance is that the individual assignments in a chained
assignment does indeed have a value, that is used in the next
assignment in the chain. Perhaps there is another interpretation
implied in the grammar, but: [1] although I've used multiple assignment
in python, and I know it's in the tutorial, I couldn't find a
definition in the online reference manual; [2] All of the other
languages where I've ever seen multiple assignment of this sort
[Icon, Lisp, et.al.] use exactly that interpretation in their grammer.

For example, in list, 'setf' or 'print', besides having a side effect,
also have the value of their argument, so the lisp equivalent is:

( setf x ( setf y ( setf z 0 )))

And you can also insert print statements in for debugging without
altering the value of the expressions:

>( setf rmax ( max ( print ( normal-rand 4 ))))
(-0.805338971099848 -1.0270877024162064 0.4156351538329579
-0.20198461243397814)
0.4156351538329579 ;; << value of rmax


Note that this exception is not just for identifiers! You can also do:

coordinate = ( x, y, z ) = 0, 100, 20
coordinate = [x,y,z] = range(3)

> Am i missing something here? What do you gain by
> explicitly preventing assignments from producing a
> value?

I know the reason for this feature is Guido's desire to maintain the
distinction between statements and expressions, but I think it actually
produces more inconsistency and ambiguity.

In practice, I've managed to get used to the restriction.

My REAL nominee for the most anoying design decision/mistake to which
we are permanently bound to by backwards compatability is the use of
'+' for both addition and concatenation.

Donald Beaudry

unread,
Jun 15, 1996, 3:00:00 AM6/15/96
to

lu...@rmi.net (Mark Lutz) wrote,

> Sure. But OTOH, this issue's been debated many times in the past.

Ah, you just don't want your book to be out of date before it hits the
shelves :) Personally, I long for the good old days of endlessly
debating syntax. Not that it ever did any good mind you, but it was
fun. So, for old times sake, is anyone interested in discussing
"optionally required block delimiters" again ;)

--
Donald Beaudry Silicon Graphics
Digital Publishing/DMS 1 Cabot Road
do...@sgi.com Hudson, MA 01749
...So much code, so little time...

Guido van Rossum

unread,
Jun 15, 1996, 3:00:00 AM6/15/96
to

> > Could someone kindly explain why there is a good reason
> > for Python not to produce the result of an assignment
> > in expressions? It seems puzzling that you should be
> > able to do
> >
> > x = y = z = 0
> >
> > in Python but not
> >
> > while (foo = sys.stdin.readline()):
> > ...
>
> The appearance is that the individual assignments in a chained
> assignment does indeed have a value, that is used in the next
> assignment in the chain. Perhaps there is another interpretation
> implied in the grammar, but: [1] although I've used multiple assignment
> in python, and I know it's in the tutorial, I couldn't find a
> definition in the online reference manual; [2] All of the other
> languages where I've ever seen multiple assignment of this sort
> [Icon, Lisp, et.al.] use exactly that interpretation in their grammer.

Indeed, I put this in the language because "x = y = z = 0" seems to be
a common, harmeless idiom, but it does not use the grammar that C
uses to make this work: like in old Algol-60 (which had a:=b:=c:=0;),
the syntax is something like (variable =)* expression.

> I know the reason for this feature is Guido's desire to maintain the
> distinction between statements and expressions, but I think it actually
> produces more inconsistency and ambiguity.

Actually, in C, there's also a distinction between statements and
expressions (try using a for loop in an expression :-), but assignment
is classified as an expression operator instead of a separate category.

I like treating assignment as not an expression operator, to avoid
typos like if a = b: ...

> In practice, I've managed to get used to the restriction.

'nuff said about this topic.

> My REAL nominee for the most anoying design decision/mistake to which
> we are permanently bound to by backwards compatability is the use of
> '+' for both addition and concatenation.

After a discussion with the numerics people at the conference, I have
to agree that this is annoying. As you say, hard to fix now...

--Guido

Guido van Rossum

unread,
Jun 15, 1996, 3:00:00 AM6/15/96
to

> Python still allows DIFFERENT sets of typo's, for example:
[...]

And here's the most annoying one:

x == 0

> Python's got its own set of "gotcha's" -- that argument is
> a red herring.

This rebuttal seems to be a red herring by itself -- just because there
are gotcha's left (or other gotcha's) doesn't mean I shouldn't try to
reduce the number of painful gotcha's.

The real question, which seems unanswerable in practice except by
anecdotal evidence, is whether Python's approach (in this particular
matter) leads to fewer programming errors than C's approach. (Of
course, after factors like "most programmers are already used to C's
apprach" have been compensated for, and taking into account that Python
has other differences with C, such as indentation, and dynamic typing.)

--Guido

Tim Peters

unread,
Jun 16, 1996, 3:00:00 AM6/16/96
to

>> [someone whose identity this odd Win95 newsgroup interface won't reveal]
>> My REAL nominee for the most anoying design decision/mistake ...

>> is the use of '+' for both addition and concatenation.

> [guido, folding like a damp-- albeit diplomatic --napkin]


> After a discussion with the numerics people at the conference, I have
> to agree that this is annoying. As you say, hard to fix now...

That's enough of that kind of talk! I won't have it. Having resurrected
myself as a speech recognition guy, I no longer care about floating-
point, math libraries, IEEE-754, or numerics people one teensy whit any
more. Strings form a (non-Abelian) group under catenation, and "+" is a
fine symbol for any group's operator. Good Lord, if it's good enough for
adding vectors, matrices & quaternions, why not for strings?

So there.

meaner-than-ever<wink>-ly y'rs - tim

not speaking for Dragon Systems Inc
t...@dragonsys.com tim...@msn.com


PS: Would love to catch up, but not at the $2/hour this no-offline-mode
newsreader costs <arghghgh!>. Will cruise the homepage & come back prepared
to correct everyone's mistaken opinions <smile> ...

PPS: WONDERFUL to see Python still hanging in there! I've missed it. Great
to see so many old names, too -- this was & is a terrific group.

Mark Lutz

unread,
Jun 16, 1996, 3:00:00 AM6/16/96
to

>lu...@rmi.net (Mark Lutz) wrote,
>> Sure. But OTOH, this issue's been debated many times in the past.
>
>Ah, you just don't want your book to be out of date before it hits the
>shelves :)

Well, not really; I expect to be busy with periodic updates for years
to come (I look on this as an arguably-Good Thing :-).

[In fact, FWIW, the book already went through a fairly massive rewrite
cycle for Tk4.0/Python1.3, even before the first printing. Let's see;
what was that quote?... "Engineers love to change things!" :->]

>Personally, I long for the good old days of endlessly
>debating syntax. Not that it ever did any good mind you, but it was
>fun. So, for old times sake, is anyone interested in discussing
>"optionally required block delimiters" again ;)

<editorial comment deleted :-)>

Have fun,
Mark L.
---
lu...@rmii.com [home] 303-684-9565
Longmont, CO. [work] 303-684-9562 ext.239


Aaron Watters

unread,
Jun 16, 1996, 3:00:00 AM6/16/96
to

Guido van Rossum wrote:
> I like treating assignment as not an expression operator, to avoid
> typos like if a = b: ...
>
> > In practice, I've managed to get used to the restriction.
>
> 'nuff said about this topic.

Not quite :). This hits the nail on the head precisely.
It is SO SO nice that whenever I make the ``if a=b:'' typo Python
catches it for me. And I make it probably once per 100 lines or so.
This is my most common error in C and it
often causes bugs that occur under error legs that will
almost certainly never show up in testing, but only after the
product has been delivered.

For what it's worth I've adopted
the Python style in C (and even in the rare case that I have
to fix legacy Perl code). If I were God I'd roll back time and
remove assign-as-expression from C too, after all

ptr = fn(...)
if (!ptr) { error condition }

is precisely the same as

if (!(ptr=fn(...)) { error condition }

to an optimizing compiler. I'm even worse than this...
Sometimes you'll see

if (test() == value) {
variable = 1;
} else {
variable = 0;
}

(and similar) in my code in place of

variable = (value == test());

Try disassembling the result of these two fragments: the compiler
just doesn't give a &*^%, but I hope the previous is (painfully)
readable, and less likely to get garbled.

I'd be very upset if assignments-as-expressions appeared in Python.
To me the cost outways the benifits. -- Aaron Watters.
====
Ousterhouts theorem:
``The biggest improvement in performance is the
non-working-to-working transition.''
Roskinds Corellary:
``Don't optimize something that doesn't work yet, and
hasn't shown performance problems, you jerk.'' (paraphrased)
Trivial consequence:
``Fewer lines does not necessarily a better program make.''

Aaron Watters

unread,
Jun 16, 1996, 3:00:00 AM6/16/96
to

Ka-Ping Yee wrote:
>
> (Yes, i have already read all the language vs. language comparisons -- but
> it's a bummer to have to write "while 1: // ipt = sys.stdin.readline() //
> if not ipt: break" when you're used to "while (<>)".)
>
> Ping

Ahem. Let's raise the level of this discussion a bit. Have you considered using
a class structure for this kind of thing? Really, the embedded loop style of
programming common in the Perl world is not to my taste, and I think it tends to
encourage huge monolithic functions that rely heavily on global variables
and when you want to do something similar (but not quite identical)
in another program, cut-and-paste... yuck...

Here is a simple example of a virtual superclass with 3 specializations.
====
import sys
class FileIterator:
"""virtual superclass for iterating over lines of a file."""
def __init__(self, file=sys.stdin):
self.file = file
def process_all(self):
file = self.file
while 1:
ipt = file.readline()
self.process_line(ipt)
def process_line(self, line):
raise ValueError, "you need to define this in a subclass, this is a virtual fn"

class echo(FileIterator):
"""Just echo input file, designed for subclassing."""
outfile = sys.stdout
def process_line(self, line):
self.outfile.write(line)

from string import upper, lower

class lower(echo):
"""transform input to all lower case"""
transform = [lower] # aha! a class method
def process_line(self, line):
self.outfile.write( self.transform[0](line) )

class upper(lower):
"""transform input to all upper case"""
transform = [upper] # that's all folks!

# when called as a script default to uppercase stdin to stdout
if __name__ == "__main__":
u = upper()
u.process_all()
====
Once you've got some nice abstractions to your liking, you'll never need to
write anything as low level as ``while (<>)'' ever again! :).
-- Aaron Watters
===
Its nice to know that Oracle is reinventing the PCjr

Aaron Watters

unread,
Jun 16, 1996, 3:00:00 AM6/16/96
to

LAST POST WAS BUGGY!!! SORRY!!

Aaron Watters wrote:
> def process_all(self):
> file = self.file
> while 1:
> ipt = file.readline()

* if not ipt: break # INSERT! WHAT A MORON I AM!
> self.process_line(ipt)

BUT, of course the nice thing is that the bug has now been
excised from *all* *subclasses* of FileIterator. I didn't
mean to do this, but I managed to illustrate one of the advantages
of Python-subclassing (over, say, Perl cut-and-paste) by accident,
even if it was a little embarrassing.

NOTE: I know you don't need to use cut-and-paste in Perl, but
I know from painful experience that this is what almost everyone
does, and I seriously believe that the language tends to
encourage this (particularly thanks to the weird ways that
different types of objects are treated completely differently
by the language, which makes proper modularization more difficult
than it should be)...

After all, I have to modify Perl code on an almost daily
basis, frequently fixing the same bug in about 15 places.
I'm replacing it with Python whenever I can figure out
how the darn thing is supposed to work, when it does.

BTW I actually tested the previous post, but I just didn't notice
that it didn't terminate :). -- Aaron Watters
===
I understand that most of the employees at Netscape are the
smartest people they know.

Michael McLay

unread,
Jun 17, 1996, 3:00:00 AM6/17/96
to

This of course assumes that programmers are the most important
customers for Python. I believe Python will have a much larger
audiance with non-programmers who need to write programs to do there
work. The LLNL end users are a case in point. The non-programmers
who program out number the computer scientist/geek population by a
a wide margin. Also, new programmers who haven't been subjected to C
may find Python more appealing. For them, learning C will be akin to
learning assembly language. Cryptic, error prone, and to be avoided.


Ka-Ping Yee

unread,
Jun 18, 1996, 3:00:00 AM6/18/96
to

Michael McLay wrote:
>
> Guido van Rossum writes:
> > > Python still allows DIFFERENT sets of typo's, for example:
> > [...]
> >
> > And here's the most annoying one:
> >
> > x == 0
> >
> > > Python's got its own set of "gotcha's" -- that argument is
> > > a red herring.

Not like all this confusion couldn't have been eliminated by
simply using, say, ":=" and "==". I think this common typo
is just a consequence of the bad choice of operator symbols
in C, not really of the ability to put assignments in
expressions. But anyway...


Ping

Ka-Ping Yee

unread,
Jun 18, 1996, 3:00:00 AM6/18/96
to

Aaron Watters wrote:
>
> Ka-Ping Yee wrote:
> >
> > (Yes, i have already read all the language vs. language comparisons -- but
> > it's a bummer to have to write "while 1: // ipt = sys.stdin.readline() //
> > if not ipt: break" when you're used to "while (<>)".)
> >
> > Ping
>
> Ahem. Let's raise the level of this discussion a bit. Have you considered using
> a class structure for this kind of thing?
[...]

> Here is a simple example of a virtual superclass with 3 specializations.

This is very nice. But it is irrelevant to the issue i thought we were
discussing. Python can do a lot of nice things with its ability to pass
functions as first-class objects and ability to define classes. It wins
in many of those aspects (and that's why i like it). If you were to try
to evaluate Python "on the whole", summing the values of its features and
comparing it to an entire other language, you would take all these things
into account. But wrapping the example in these other features don't
make the issue of assignments in expressions go away.


Ping

Gary Capell

unread,
Jun 18, 1996, 3:00:00 AM6/18/96
to

Greg.Mc...@nms.otc.com.au (Greg McFarlane) writes:

>could I point out that using both "from string import lower" and "class
>lower", leads to code which may be hard to understand and difficult to debug.

Is this any different from having both "lower=10" and "class lower"?

>Ban "from foo import bar"!!

I think the problem is more to do with Python's general fluidness
than "from foo import bar" (which I quite like).
--
http://www.cs.su.oz.au/~gary/

Graham Clemo

unread,
Jun 18, 1996, 3:00:00 AM6/18/96
to

> I like treating assignment as not an expression operator, to avoid
> typos like if a = b: ...
>

This is only a problem if your language uses = for assignment.
If it used, say, := then this mistake would be more difficult to make.

"if a := b" - few people would type this by accident.

This is only a minor lexical decision though, and nothing worth losing
sleep over.

> 'nuff said about this topic.

Yes, you are probably right.

Steven D. Majewski

unread,
Jun 18, 1996, 3:00:00 AM6/18/96
to

On 16 Jun 1996, Tim Peters wrote:

> Strings form a (non-Abelian) group under catenation, and "+" is a
> fine symbol for any group's operator. Good Lord, if it's good enough for
> adding vectors, matrices & quaternions, why not for strings?

I got nothin' against strings, but using '+' for sequence
concatenation prevents using it for vectors & matrices if they
are represented as a type of sequence ( well, it doesn't actually
prevent it, but it does make it a bit confusing! )

On the subject of Gotcha's:

>>> [1] + [2]
[1, 2]
>>> (1) + (2)
3 # Oops! - what I meant was ...
>>> (1,) + (2,) # more typically, one of those operands was a
(1, 2) # function parameter and yielded a run-time error
>>> # instead of a wrong value.


Yes - I prefer Python's Gotcha's to C or C++ or [whatever's] Gotcha's.
I'm used to them by now, and I've even grown fond of a few of them.
But I think the *only* effective way to get rid of gotcha's is with
type checking. The horrible thing about C is that it makes you have
to bend to it's type system, and then it goes and lets something like
"if ( a = b )" through! If you're going to go through the trouble
of type checking, then conditionals ought to require a boolean type.


> So there.
>
> meaner-than-ever<wink>-ly y'rs - tim

Welcome back, Tim!


> PS: Would love to catch up, but not at the $2/hour this no-offline-mode
> newsreader costs <arghghgh!>. Will cruise the homepage & come back prepared
> to correct everyone's mistaken opinions <smile> ...

One of the threads you missed was "Where is Tim -- we miss his sigs!"


[ Some things never change: True to usual form, it took Yet Another
Syntax Discussion to simultaneously lure Tim Peters out of retirement,
and me out of "semi-retirement". If this didn't smoke him out, then
maybe the delimiters/whitespace thread would have done the trick! ]

Jim Fulton

unread,
Jun 19, 1996, 3:00:00 AM6/19/96
to

I hate to get involved with this, but I just thought I'd give a file
iterator that would, perhaps, better address the views of people
who like the simple perl mechanism for iterating through lines of a
file, and illustrate a little-known, but useful, feature of for loops:

class InputLines:
def __init__(self,file=sys.stdin):
self.file, self.index, self.data = file, -1, ''

def __getitem__(self,index):
i=self.index
if index == i: return self.data
if index == 0 and i > 0:
self.file.seek(0)
i=-1
while i < index:
l=self.file.readline()
if not l: raise IndexError, 'end of file'
i=i+1
self.index, self.data = i, l
return l

With this, you could process standard input with:

for line in InputLines():
... do stuff with line ...


for process a file with:

for line in InputLines(open('some_file','r')):
... do stuff with line ...


This takes advantage of the fact that for loops start indexing from 0
and increase the index until an index error occurs.
--
Jim Fulton Digital Creations
j...@digicool.com 540.371.6909

Tom Christiansen

unread,
Jun 21, 1996, 3:00:00 AM6/21/96
to

[courtesy cc of this posting sent to cited author via email]

In comp.lang.python,
Aaron Watters <a...@big.att.com> writes:
:... I managed to illustrate one of the advantages


:of Python-subclassing (over, say, Perl cut-and-paste) by accident,
:even if it was a little embarrassing.
:
:NOTE: I know you don't need to use cut-and-paste in Perl, but
:I know from painful experience that this is what almost everyone
:does, and I seriously believe that the language tends to
:encourage this (particularly thanks to the weird ways that
:different types of objects are treated completely differently
:by the language, which makes proper modularization more difficult
:than it should be)...

When you have a language that's snatched up by a million accidental
programmers for the last decade or so, first those doing system
administration, and now those doing web work like CGI and spiderbots, it's
no small wonder that you've got a lot of Perl code out there that looks
like as though it were written by someone who would have been more
comfortable writing in BASIC than in Modula.

That's because they *would* have been more comfortable with BASIC -- or
with not programming a single thing at all. These folks aren't
professional programmers, but they often must program nonetheless. You
wouldn't expect an industrial-strength bridge from a casual, garage-based
carpenter, so why do you expect beautiful, efficient, maintainable, and
structurally sound code from these accidental programmers?

Those of us who are trained (whether at university or as autodidacts) in
``real programming'' do tend to code things up a good bit differently than
those high school hackers upgrading their Amigas do.

--tom
--
Tom Christiansen Perl Consultant, Gamer, Hiker tch...@mox.perl.com

"With a PC, I always felt limited by the software available.
On Unix, I am limited only by my own knowledge." --Peter J. Schoenster

Jeff Templon

unread,
Jun 21, 1996, 3:00:00 AM6/21/96
to

In article <4qd0lb$7...@csnews.cs.colorado.edu> Tom Christiansen
<tch...@mox.perl.com> writes:

> When you have a language that's snatched up by a million accidental
> programmers for the last decade or so, first those doing system

[ ... ]

> no small wonder that you've got a lot of Perl code out there that looks
> like as though it were written by someone who would have been more
> comfortable writing in BASIC than in Modula.

[...]

> with not programming a single thing at all. These folks aren't
> professional programmers, but they often must program nonetheless. You

[...]

> Those of us who are trained (whether at university or as autodidacts) in
> ``real programming'' do tend to code things up a good bit differently than
> those high school hackers upgrading their Amigas do.

This is an interesting point. It's something that is echoed somewhat in
the current discussion about what to start using as the next-generation
scientific programming language. The (previous,current) language of
choice was Fortran, which has served us well since its model of the
computer is pretty close to what most non-computer-scientist types
would come up with for our own model. That's why it was so successful;
you didn't need to be a computer scientist to write a reasonable program.
That's not to say that there are not a lot of bad Fortran programs out
there, just that a small bit of educating yourself about Fortran was
sufficient to write a reasonable program.

One of the big contenders now for the future language is C++, which
I think is bad for precisely the reason Tom mentioned. One needs to
have a good understanding of what C++ is doing in order to write
a reasonable program, at least from what I can see. Most people I know
who are writing the scientific programs (and don't be insulted out there,
since these "most people" usually don't read comp.lang.anything) do
not have this professionalism, they are writing code only as a means
to help them do what they *are* professionals at, which is research.

This is one
reason why I like Python; one can start writing reasonable programs
right away, but it has enough power (and is modern enough) so that
one can do real work with it. I'm glad the world is not stuck with
only two choices, either a BASIC-style language (simple but not powerful
enough) or a Perl or C++ language, which is only really suited
for professionals.

JT


Steven D. Majewski

unread,
Jun 21, 1996, 3:00:00 AM6/21/96
to

On Sat, 22 Jun 1996, Ka-Ping Yee wrote:

> Jim Fulton wrote:
> >
> > This takes advantage of the fact that for loops start indexing from 0
> > and increase the index until an index error occurs.
>

> I noticed that while playing with the array of a for loop
> from within the loop one day.
>
> Is this guaranteed behaviour?

I'm not exactly sure what you mean by "guaranteed behaviour", but it
is implemented that way on purpose, if that's what you mean.

The original implementations of 'for' got the length of the sequence
and iterated over it for that length. A couple of us former Icon-ers
thought we couldn't live without our sequence generators, so Guido
very nicely made this slight change to allow iteration over sequences
of indefinite, infinite or unknown length without resorting to some
of the ugly hacks I had invented. ( Like forcing __len__ to always
return one more that the current item. )

Ka-Ping Yee

unread,
Jun 21, 1996, 3:00:00 AM6/21/96
to

Jim Fulton wrote:
>
> This takes advantage of the fact that for loops start indexing from 0
> and increase the index until an index error occurs.

I noticed that while playing with the array of a for loop
from within the loop one day.

Is this guaranteed behaviour?


Ping

Guido van Rossum

unread,
Jun 21, 1996, 3:00:00 AM6/21/96
to

Yes.

--Guido van Rossum (home page: http://www.python.org/~guido/)

Robin Friedrich

unread,
Jun 21, 1996, 3:00:00 AM6/21/96
to

>>>>> "Jeff" == Jeff Templon <tem...@studbolt.mit.edu> writes:
<snip>
Jeff> One of the big contenders now for the future language is
Jeff> C++, which I think is bad for precisely the reason Tom
Jeff> mentioned. One needs to have a good understanding of what
Jeff> C++ is doing in order to write a reasonable program, at
Jeff> least from what I can see. Most people I know who are
Jeff> writing the scientific programs (and don't be insulted out
Jeff> there, since these "most people" usually don't read
Jeff> comp.lang.anything) do not have this professionalism, they
Jeff> are writing code only as a means to help them do what they
Jeff> *are* professionals at, which is research.

Jeff> This is one reason why I like Python; one can start writing
Jeff> reasonable programs right away, but it has enough power (and
Jeff> is modern enough) so that one can do real work with it. I'm
Jeff> glad the world is not stuck with only two choices, either a
Jeff> BASIC-style language (simple but not powerful enough) or a
Jeff> Perl or C++ language, which is only really suited for
Jeff> professionals.

I can't agree with Jeff more! We in the engineering world have slung
Fortran around for years precisely because it didn't take an ICS
degree to get working code. Much programming was performed by "non-
professionals" and handed over to programming staff to maintain. Of
course over years this turns into a rats nest of goto statements and
becomes very expensive to maintain. There comes a time when the code
needs to be rewritten in a more maintainable/reusable fashion. This
means a full reevaluation of the domain functionality and
reimplimentation in a more modern design and language. C++ is indeed
all the rage (Java not withstanding) for doing scientific simulations
as it promises performance and reuse flexibility. Unfortunately, when
this is done the user(engineer/scientist) no longer can look at the
code and understand what's going on let alone detect implementation
flaws. We faced this very dilemma in a major project here at
NASA. Fortunately, we discovered Python and saw that it would make the
ideal user interface language on top of an object oriented domain
implementation in C++. It'll be the substitute drug given to calm
their fears of loosing Fortran. The reuse and ease of programming
characteristics of Python will hopefully hold up well under the
software abuse most non-computer scientists will dish out.

The recent conference at Lawrence Livermore highlights that nicely.
They will be using Python wherever a programmable interface to lower
level software is called for. I see Python as having a very bright
future in the technical/scientific fields. Python is a wonderfully
full featured language adaptable to a huge spectrum of
problems... (OK I'll stop now, I'm preaching to the choir.:-)

(btw. I'm not a computer scientist. I just play one on the net.)

Aaron Watters

unread,
Jun 23, 1996, 3:00:00 AM6/23/96
to

Tom Christiansen wrote:
>
> Those of us who are trained (whether at university or as autodidacts) in
> ``real programming'' do tend to code things up a good bit differently than
> those high school hackers upgrading their Amigas do.
>
> --tom

Tom. Sorry. The perl code I'm dealing with was written primarily by
people with masters degrees or higher in CS, EE or something close.
For some reason they don't behave as you suppose, especially under
pressure... I have my theories as to why this is the case, but I don't
want to get in trouble again. -- Aaron Watters
===
All this chitter chatter chitter chatter chitter chatter
About shmatter shmatter shmatter shmatter shmatter
I can't give-it-away on 7th avenue!
(Hoop Sheyoobee.) -- Mick Jagger.

Aaron Watters

unread,
Jun 25, 1996, 3:00:00 AM6/25/96
to

Robin Friedrich wrote:
> I can't agree with Jeff more! We in the engineering world have slung
> Fortran around for years precisely because it didn't take an ICS
> degree to get working code.
...

> (btw. I'm not a computer scientist. I just play one on the net.)

Just a note. In my experience some of the best programmers around
say they aren't real programmers. They just get the job done in the
cleanest way possible. I suspect Robin falls in this category.

Also, remember that HTTP (aka ``the Web'') that everyone is so crazy about was
initially used only by a bunch of physicists and engineers and biologists
and such as a convenient way to transfer data and technical notes...
There were absolutely no ``real'' computer scientists or Big Computer
Companies involved for the first years as far as I know (please correct
me if I'm wrong)... In view of this it's interesting that lots of
physicists and engineers and such are now turning to Python, because
it gets the job done and they don't really care that java automatically
detects tachion field emissions, or whatever...
-- Aaron Watters
====
Everybody have fun tonight. Everybody Wang Chung tonight.

Aaron Watters

unread,
Jul 1, 1996, 3:00:00 AM7/1/96
to

Niels Möller wrote:
> If I were a physicist, I'd be interested in almost anything detecting
> tachyons... ;-)

yes, but unfortunately this feature seems to be buggy in the sun
version. I understand the Microsoft java implementation may have
got it right, however... -aaron

Reply all
Reply to author
Forward
0 new messages