RFC: Assignment in Conditional 
Author Message
 RFC: Assignment in Conditional

We all realize that assignment isn't an operator.  It's easy enough to chant
that when someone asks about why they can't do "if line = fp.readline():".
However, it seems fairly clear that this restriction results in kludges
like:

   while 1:
      line = fp.readline()
      if not line: break
      print line

In a language which is touted as being so clear, I'm kind of surprised that
this hasn't received more attention.

It would seem that one could set up a variable or possibly a set of variables
which would contain the value of the expression in the last executed
conditional:

   while fp.readline():
      if re.match(whileVar, r'^\s*(\S+)\s*=\s*(\S+)\s*$'):
         print 'Assignment "%s" = "%s"' % ( ifVar.group(1), ifVar.group(2) )

This has the benefit of allowing you to easily see the termination condition
for the while loop, instead of assuming it's infinite until you search
through (the possibly complex) body.

This would seem to eliminate the required kludge, while still keeping with the
basic spirit of Python.  However, before going through and making a patch for
Python, I wanted to see what comments folks had on this idea.

The next logical step I could see would be adding a variant to conditionals:

   while [ <word> = ] <expression>:

where if the optional [ <word> = ] part of the while statement were there it
would assign the expression value to <word> in addition to the whileVar.  But
then what would be the point of having the whileVar?

Is the only concern that this will be confused with the "==" comparison
operator?  In that case, would "while [ <word> assign_the_value_of ]
<expression>:" (or something similar) be more appropriate?  Or perhaps
even something along the lines of "<word> = while <expression>:"?
That feels a bit strange, but surely won't be mistaken for a comparator...

The only issue I see with this is the scope of the "whileVar".  Presumably
one could limit the scope by doing a "whileVar = None", or perhaps the
termination of a while would imply that?

Thanks,
Sean
--
 I used to think that the brain was the most wonderful organ in
 my body.  Then I realized who was telling me this.  -- Emo Phillips

URL: < http://www.*-*-*.com/ ; HP-UX/Linux/FreeBSD/BSDOS scanning software.



Sat, 09 Jun 2001 03:00:00 GMT  
 RFC: Assignment in Conditional

Quote:

> We all realize that assignment isn't an operator.  It's easy enough to chant
> that when someone asks about why they can't do "if line = fp.readline():".
> However, it seems fairly clear that this restriction results in kludges
> like:

>    while 1:
>       line = fp.readline()
>       if not line: break
>       print line

> In a language which is touted as being so clear, I'm kind of surprised that
> this hasn't received more attention.

It has. You can do the assignment inside a class instance and
iterate over this. Guido did this in a very elegant way.
Try this:

    import fileinput
    for line in fileinput.input():
        process(line)

It doesn't read the whole bunch but behaves like a sequence
and enumerates all the input lines by its __getitem__ method.

If you think you must, here is also a minimal example
how to wrap an assignment by a small class.

class remember:
    def __init__(self, func):
        self.func = func
    def __call__(self):
        self.line = self.func()
        return self.line

myline = remember(open('c:\\autoexec.bat').readline)
while myline():
    print myline.line

All in all it is no big deal and not necessary.

cao - chris

--

Applied Biometrics GmbH      :     Have a break! Take a ride on Python's
Kaiserin-Augusta-Allee 101   :    *Starship* http://starship.skyport.net
10553 Berlin                 :     PGP key -> http://pgp.ai.mit.edu/
     we're tired of banana software - shipped green, ripens at home



Sat, 09 Jun 2001 03:00:00 GMT  
 RFC: Assignment in Conditional


Quote:
>It has. You can do the assignment inside a class instance and
>iterate over this. Guido did this in a very elegant way.

With all due respect, if it's so elegant why does Guido recommend not
using it for performance reasons?  Search DejaNews if you're really
interested.

Quote:
>    import fileinput
>    for line in fileinput.input():
>        process(line)

This is one of the few places in the library where you can do something
similar to the above.  If you don't care about performance, you can also
do:

   for line in sys.stdin.readlines():
      process(line)

so why do you need fileinput at all?

The point is that fileinput is the only place you get that nice syntax
(what if I'm reading data from sockets or pipes?).  My proposal above
removes the need for kludges such as building classes so you can use
__getitem__.

Quote:
>If you think you must, here is also a minimal example
>how to wrap an assignment by a small class.

[Example replacing 3 lines of code with 9 deleted]

Quote:
>All in all it is no big deal and not necessary.

Perhaps so...  One could make the same argument for a number of features
which have been added to python (lambda, map, filter, multiple assignment
which may even tend to promote these discussions).  Yet amazingly this
issue continues to be brought up...

Sean
--
 Jackie Trehorn treats objects like women, man...
                 -- _The_Big_Lebowski_

URL: <http://www.tummy.com/xvscan> HP-UX/Linux/FreeBSD/BSDOS scanning software.



Sun, 10 Jun 2001 03:00:00 GMT  
 RFC: Assignment in Conditional


Quote:
>This comes up every few month (search in dejanews for 'assignment expression'
>and you'll find some answers).

At the risk of being monotonous, I'd like to repeat the first two lines of my
original post:

Quote:
>We all realize that assignment isn't an operator.  It's easy enough to chant
>that when someone asks about why they can't do "if line = fp.readline():".

What could I have done to make it more clear that I was talking about
changing the syntax for conditionals, *NOT* turning assignment into
an expression?

Sean
--
 A smart terminal is not a smart*ass* terminal, but rather a terminal
 you can educate.  -- Rob Pike

URL: <http://www.tummy.com/xvscan> HP-UX/Linux/FreeBSD/BSDOS scanning software.



Sun, 10 Jun 2001 03:00:00 GMT  
 RFC: Assignment in Conditional
[Sean Reifschneider]
Quote:
> We all realize that assignment isn't an operator.  It's easy
> enough to chant that when someone asks about why they can't do

 "if line = fp.readline():".

Quote:
> However, it seems fairly clear that this restriction results in kludges
> like:

>    while 1:
>       line = fp.readline()
>       if not line: break
>       print line

> In a language which is touted as being so clear, I'm kind of
> surprised that this hasn't received more attention.

It's received *enough* attention, though, that the very thought of replying
to yet another msg about it makes me a bit physically ill <0.7 wink>.

I've done more than my share of supplying stupid "workarounds", so I guess I
deserve that.  In real life I always use the "kludge" you listed above.

Quote:
> It would seem that one could set up a variable or possibly a set
> of variables which would contain the value of the expression in the
> last executed conditional:

>    while fp.readline():
>       if re.match(whileVar, r'^\s*(\S+)\s*=\s*(\S+)\s*$'):
>          print 'Assignment "%s" = "%s"' % ( ifVar.group(1),
>                ifVar.group(2) )
> This has the benefit of allowing you to easily see the
> termination condition for the while loop, instead of assuming it's
> infinite until you search through (the possibly complex) body.

Actually, when I see

    while 1:

I assume the opposite:  that it's a finite loop and I'll find an "if ...:
break" one or two lines down.  I'm rarely disappointed <wink>.

Quote:
> This would seem to eliminate the required kludge, while still
> keeping with the basic spirit of Python.  However, before going
> through and making a patch for Python, I wanted to see what comments
> folks had on this idea.

Frankly, I hate it.  Vars with magic names that change bindings as a result
of magical side-effects sounds more Perlish than Pythonish to me.  The only
thing Python has like that now is the one-character "_" as a convenience in
interactive mode.

Believe it or not, I *do* sympathize with your complaint -- while I'm used
to it now, I've never *liked* writing "while 1:" (for the very reasons you
state), and think it would be peachy to peel the conditional banana.

Quote:
> The next logical step I could see would be adding a variant to
> conditionals:

>    while [ <word> = ] <expression>:

> where if the optional [ <word> = ] part of the while statement
> were there it would assign the expression value to <word> in addition
> to the whileVar.

Ack, no -- this is almost certainly what Guido was trying to *avoid*, i.e.
the ridiculous subtle bugs that pop up in C from writing

    while (x = f()) { ... }

by mistake when

    while (x == f()) { ... }

was intended.  God knows, just last week I tracked down what turned out to
be a

    assert(n = 1);

bug in C++ (that assert is a self-fulfilling prophecy <snarl>).

Every post-C language except the no-choice-in-the-matter C++, and Perl (&
now Ruby too, alas), has moved heaven and earth to avoid propagating this
miserable design error.

Quote:
> But then what would be the point of having the whileVar?

Absolutely none -- which is good <wink>.  I've said before that I favor

    while x := f():

i.e. use the currently-unused ":=" to mean binding-as-expression.

Quote:
> Is the only concern that this will be confused with the "==" comparison
> operator?

It's a major concern, yes.  Whether it's Guido's only concern "in theory" I
don't know.  Based on his well-known fear of lexical scoping <wink>, he
could also harbor some terror about abuses like:

    while (sum := (x := f()) + (y := g()) + (z := h())) < (lim := i()):
        print "sum", sum, "<", lim, "prod", x*y*z

But I think the best way to encourage clean code is to ridicule newbie code
postied to c.l.py <wink>.

Quote:
> In that case, would
>     while [ <word> assign_the_value_of ] <expression>:
> (or something similar) be more appropriate?

Definitely, if it flies at all.

Quote:
> Or perhaps even something along the lines of
>     <word> = while <expression>:

> That feels a bit strange, but surely won't be mistaken for
> a comparator...

This appears to be an instance of the ever-popular yet never-successful
c.l.py meta-strategy that when you can't get Guido to adopt a reasonable
suggestion, try an insane one <0.98 wink>.

Quote:
> The only issue I see with this is the scope of the "whileVar".  Presumably
> one could limit the scope by doing a "whileVar = None", or perhaps the
> termination of a while would imply that?

while e1():
    while e2():
         # what does whileVar mean here -- e1 or e2? e2, I guess.
         # any way to get at e1?
    # what does whileVar mean *here*?  None?  or is there some magical
    # stack of whileVars and the binding to e1 got restored when the
    # inner while terminated?
    if whileVar in ('End', 'Quit'):
        break
# and now what?  I can't get at the value that caused the loop to break?

All of those irksome questions (& many more) are sidestepped cleanly by
letting the user bind their own vars explicitly when & as they feel they
need to.

the-most-disagreeble-supporter-you're-likely-to-find<wink>-ly y'rs  - tim



Mon, 11 Jun 2001 03:00:00 GMT  
 RFC: Assignment in Conditional
Tim Peters quoted:

Quote:
>[Sean Reifschneider]
>> We all realize that assignment isn't an operator.  It's easy
>> enough to chant that when someone asks about why they can't do
> "if line = fp.readline():".
>> However, it seems fairly clear that this restriction results in kludges
>> like:

>>    while 1:
>>       line = fp.readline()
>>       if not line: break
>>       print line

        IMHO the problem isn't not being able to do assignments, or
get the result of some expression, inside a while.  It's that Python
only has 'while', and no do..while:

do:
    line = fp.readline()
while not line

  This is one of my few problems with the language, and though I've
gotten used to writing 'while 1'...'if something: break', it still
gives me a twinge of annoyance every time I do it.

(Aside: didn't someone suggest generalizing do...while once by
allowing conditions inside the block?  Can't pull it up in Dejanews,
though.)

--
A.M. Kuchling                   http://starship.skyport.net/crew/amk/
    >VERY cool mod, Peter. I'll be curious to see GvR's reaction to your
syntax.
    Hm.
    -- Nick Seidenman and Guido van Rossum, 1 Aug 1996



Mon, 11 Jun 2001 03:00:00 GMT  
 RFC: Assignment in Conditional
Before I go, here's a potential way out.  Perhaps there could be an
alternate assignment operator, <-, which *is* allowed in expressions.
You could then write

    while line <- fp.readline():
        ...process line...

I'm not sure I like it myself, but it would sure avoid the confusion
betwee = and ==, and I don't think that much confusion between < and
<- is likely.

Just a thought for the holidays,

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



Mon, 11 Jun 2001 03:00:00 GMT  
 RFC: Assignment in Conditional

Quote:
> do:
>     line = fp.readline()
> while not line

But what if you want to do more with the line?  Algol-68 had something
like this:

    do:
        ...some code...
    while condition:
        ...more code...

(except they also combined it with the for loop in some way).

PS Andrew: I won't be in today; happy Holidays,

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



Mon, 11 Jun 2001 03:00:00 GMT  
 RFC: Assignment in Conditional
Hi All, & Merry Christmas!

Quote:

> Before I go, here's a potential way out.  Perhaps there could be an
> alternate assignment operator, <-, which *is* allowed in expressions.
> You could then write

>     while line <- fp.readline():
>         ...process line...

> I'm not sure I like it myself, but it would sure avoid the confusion
> betwee = and ==, and I don't think that much confusion between < and
> <- is likely.

> Just a thought for the holidays,

Eeeeuuwww.  Sorry.  The devil made me say it.  But I *much* prefer Uncle
Timmy's ``:='' operator.

<- is-to- := -as-slugs-are-to-snails-ly y'rs,
Ivan
----------------------------------------------
Ivan Van Laningham
Callware Technologies, Inc.

http://www.pauahtun.org
----------------------------------------------



Mon, 11 Jun 2001 03:00:00 GMT  
 RFC: Assignment in Conditional

Quote:
>Before I go, here's a potential way out.  Perhaps there could be an
>alternate assignment operator, <-, which *is* allowed in expressions. You
>could then write

>    while line <- fp.readline():
>        ...process line...

Cool, but wouldn't that collide with code like

    while x<-2:
        do_something()
        x = x - 1
?

In other words, isn't there ambiguity between "while x < -2" and "while x <-
2"? If so, how will it be resolved?

+  Zephyr Falcon | Storm Seeker | Hans Nowak
+  Homepage (under construction): http://www.cuci.nl/~hnowak/
+  You call me a masterless man. You are wrong. I am my own master.
+  May Grandma Moses cheat on your fiance with your cream and sour onion chips!



Mon, 11 Jun 2001 03:00:00 GMT  
 RFC: Assignment in Conditional
[Guido van Rossum]

Quote:
> Before I go, here's a potential way out.  Perhaps there could be an
> alternate assignment operator, <-, which *is* allowed in expressions.
> You could then write

>     while line <- fp.readline():
>         ...process line...

That's the one I keep suggesting, although I've spelled it := for backward
compatibility (e.g. "while i<-3:" already means something else; ":=" is
never legit now), and because that digraph does mean assignment in several
other languages Python would not be ashamed to eat dinner with.  Note that
the colon here won't confuse pymode (or other simple but not braindead
regexp-based parsers) either.

Quote:
> I'm not sure I like it myself, but it would sure avoid the confusion
> between = and ==, and I don't think that much confusion between < and
> <- is likely.

Trust me:  you'll never *really* like it, because it opens a door to all
sorts of obfuscated abuse.  But you *would* like it in tasteful code that
you and I write, and we can bully everyone else into playing nice too by
merciless public shaming of bad taste <wink>.

"if m := regexpobject(match):"-dreaming-ly y'rs  - tim



Mon, 11 Jun 2001 03:00:00 GMT  
 RFC: Assignment in Conditional

Quote:


> >Before I go, here's a potential way out.  Perhaps there could be an
> >alternate assignment operator, <-, which *is* allowed in expressions. You
> >could then write

> >    while line <- fp.readline():
> >        ...process line...

> Cool, but wouldn't that collide with code like

>     while x<-2:
>         do_something()
>         x = x - 1
> ?

> In other words, isn't there ambiguity between "while x < -2" and "while x <-
> 2"? If so, how will it be resolved?

Significance of whitespace--another mechanism courtesy of 'The Amazing Guido".


Mon, 11 Jun 2001 03:00:00 GMT  
 RFC: Assignment in Conditional


Quote:
>> do:
>>     line = fp.readline()
>> while not line

>But what if you want to do more with the line?  Algol-68 had something
>like this:

>    do:
>        ...some code...
>    while condition:
>        ...more code...

>(except they also combined it with the for loop in some way).

I'm just a python nobody, but I have to say that I *REALLY*, *REALLY* like
this. It's completely general, easy to understand, and lets us avoid the
damn assignment morass. The only down side is the new keyword. Well, maybe
Python 1.6?

This is similar to something from my obscure computer languages collection.
Anyone out there remember Basic-09? This was a language that combined the
best of Basic and Pascal (kinda like VB combines the worst <G>). There was a
control structure there that worked like this:

    do
        .... some stuff ...
        exitif condition
            ... stuff on exit ...
        endexit
        .... more stuff ....
    loop

This worked very well in practice, although I never saw a real reason for
the ... stuff on exit ... section.

-Chris



Mon, 11 Jun 2001 03:00:00 GMT  
 
 [ 32 post ]  Go to page: [1] [2] [3]

 Relevant Pages 

1. No Assignment in Conditional/PROPOSAL: Assignment expression

2. "multiple assignment in conditional"

3. conditional signal assignment

4. Conditional assignments using generate

5. Conditional Signal Assignments inside Processes?

6. inline assignments in conditionals

7. Against assignment in conditional nor while

8. module for pop3: rfc 1939 (and may be AUTH: rfc 1734)

9. RFC: Creating a "STEP" Site

10. RFC: SUnit under ObjectStudio 5.2

11. RFC

12. Form-based file upload (RFC 1867)

 

 
Powered by phpBB® Forum Software