Return value of an assignment statement?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Feb 22 13:16:06 EST 2008


On Fri, 22 Feb 2008 08:19:07 -0800, Carl Banks wrote:

> (The perl example wasn't using an assignment operator.)

Hmmm... I see. Obviously I didn't pretend to understand Perl well enough.

(I assume you're ignoring the assignments $name = chop(\1) etc. Fair 
enough.)


[...]
> I can't help but to think that a lot of people's distaste for this
> natural way to write certain logic is simply defensiveness about one
> minor little thing that Python doesn't support (without workarounds).

But Python certainly does support set-and-test. You just have to separate 
the set from the test with a newline:

m = re.match(r"name=(.*)",line)  # set
if m:  # test
    name = m.group(1).strip()


This does the same thing as your proposed syntax

if m where m = re.match(r"name=(.*)",line):
    name = m.group(1).strip()

except that it doesn't create a new scope. I'm not sure that the benefit 
of having a new scope is worth the new keyword. Maybe it is, maybe it 
isn't.

I think I have a better idea of what you are trying to say. Despite first 
impressions, you weren't defending the proposed "assign-and-test" idiom 
suggested by Stephen Gross:

pat = re.compile('some pattern')
if m = pat.match(some_string):  # doesn't work in Python
    do_something(m)

on account of it needing an assignment expression, which is Bad. But you 
were defending the principle of set-and-test, if we can use something 
other than an assignment expression to do the set.

E.g. Perl's magic syntax "if /pattern/ { }" (everything in Perl is magic 
syntax), or your proposed "if m where m = expression".

Okay, I can agree with that, particularly since Python already supports 
it using the plain old boring, old fashioned idiom of "assign, then test".



-- 
Steven



More information about the Python-list mailing list