python3: accessing the result of 'if'
donn at drizzle.com
Sun Jan 9 01:06:07 EST 2005
Quoth "Carl Banks" <invalidemail at aerojockey.com>:
| As a compromise, howabout:
| . if m > 20 where m=something():
| . do_something_with(m)
| In this case, the m=something() is NOT an assignment statement, but
| merely a syntax resembling it. The "where m=something()" is part of
| the if-statement, not the if-expression. It causes m to be visisble in
| the if-expression and the if-block.
If m=something() binds the function return to a name "m" for use
in other expressions, it sure IS an assignment. If it isn't an
assignment statement, it's only inasmuch as assignment has become
something other than a statement. Over whose dead body, I wonder.
In case it's of any interest, here's how "where" looks with "if"
in Haskell. It would take longer than you might imagine to explain
what that "return" is doing there, but part of it is that every "if"
must have an "else", and there is no such thing as "elif". Haskell's
layout (indent) structure is more flexible than Python's, there are
other ways this could look.
if a > 10
then putStrLn (show a)
else return ()
a = 5 + 6
FYI, I suppose the closest it comes to anything like "assignment as an
expression" is pattern matching -
case (regexp_group "^([^:]*): (.*)" line) of
Nothing -> f1 line
Just [a, v] -> f2 a v
-- This "unwraps" the return value of regexp_group, an imaginary
-- function of type (String -> String -> Maybe [String]). The
-- Maybe type has two values, Maybe a = Nothing | Just a.
| It (or your suggestion) could work with a while-loop too.
| . while line where line=f.readline():
| . do_something_with(line)
| The main problem here (as some would see it) is that you can't do
| something this:
| . if m > 20 where (def m(): a(); b()):
The way it made sense to me, "where" introduces a block. The whole
point is a private scope block. Actually kind of like the reverse
of a function, where instead of binding names to input parameters,
you in effect bind names to the scope for a sort of return-by-reference
effect. But never mind, the point is that you get a private block,
with one or more names exported to the surrounding scope in the left
hand side of the where clause. What you're trying to do here seems
to have almost nothing to do with that.
If Python 3 is going to get assignment-as-expression, it will be
because GvR accepts that as a reasonable idea. You won't bootleg it
in by trying to hide it behind this "where" notion, and you're not
doing "where" any good in trying to twist it this way either.
Donn Cave, donn at drizzle.com
More information about the Python-list