C-like assignment expression?

Kay Schluehr kay.schluehr at gmx.net
Thu May 22 00:25:11 EDT 2008


On 21 Mai, 19:56, sturlamolden <sturlamol... at yahoo.no> wrote:
> On May 21, 11:38 am, boblat... at googlemail.com wrote:
>
> > if (match = my_re1.match(line):
> >   # use match
> > elsif (match = my_re2.match(line)):
> >   # use match
> > elsif (match = my_re3.match(line))
> >   # use match
>
> > ...buy this is illegal in python.
>
> Assignment expressions is disallowed in Python to protect against a
> very common bug in C/C++ programs, the (accidental) confusion of
>
>    if (match = my_re1.match(line))
>
> with
>
>    if (match == my_re1.match(line))
>
> or vice versa.

This is just a syntactical issue. But what is the *value* of an
assigment? In Python it is always None: assigments are statements, not
expressions.

However Guido and team have found a *pragmatic* solution for this at
another place:

with open("myFile") as f:
    BLOCK

Compare this with a possible syntactical form of an if-statement:

if EXPR as NAME:
    BLOCK

This isn't ugly syntax-wise. It's just a bit harder to understand the
semantics of an if-statement. It might read like this:

"Evaluate EXPR and compute bool(EXPR). If this value is True assign
EXPR to NAME and execute BLOCK. Otherwise refuse both assigment and
BLOCK execution."

Maybe assignment can be performed unconditionally as in the C case.
I'm not sure about this.



More information about the Python-list mailing list