A modest solution to the madness. Was: while (a=b()) ...

James Logajan JamesL at Lugoj.Com
Wed May 12 00:08:40 EDT 1999


Steven D. Majewski wrote:
> OK -- new suggested idiom for those folks who Really, Really have
> to have it all in one statement (It *could* be on one line, but you
> wouldn't be able to read it):
[Ugly code elided to protect "the children[tm]".]

I haven't waded through all the postings on this perennial discussion, so
perhaps this solution has been posted before, but in case it hasn't, what
(other than perhaps execution speed) is wrong with the following solution:
---------------------------------------------------------------------------
# Classic loop until EOF.
import sys

# Creative use of mutable list and dynamic typing to do assignment in while.
def Set(a, b):
    a[0] = b
    return b

a = [None]
while Set(a, sys.stdin.readline()):
    # Do something with a[0]. Here we just print it.
    print repr(a[0])

print "EOF:", repr(a[0])
----------------------------------------------------------------------------

Which yields what I would expect (dialogue cut and pasted; terminated with
control-d):

---------------------------------
Hey, does this thing work?
'Hey, does this thing work?\012'

'\012'
My god, it's full of stars!
"My god, it's full of stars!\012"
EOF: ''
---------------------------------




More information about the Python-list mailing list