[Python-ideas] Combining test and assignment

Nick Coghlan ncoghlan at gmail.com
Sun Jan 22 04:48:20 CET 2012


This suggestion (i.e. embedded assignment in while and if headers) has
been made several times, and always come to a grinding halt on one
simple problem: it isn't expressive enough.

The current idiom is this :

    x = EXPR
    if predicate(x):
        # Do something

Given a value and a predicate, this allows you to execute code
conditionally based on whether or not the predicate is true.

Simple embedded assignment, though, only works when the predicate is
just "bool" - as soon as the condition differs from the value you want
to access, you need to revert to the existing idiom *anyway*. Given
the non-trivial costs of adding new syntax, that gets the idea put
into the "not worth the hassle" bucket.

The obvious escalation of the suggestion is to adopt "(EXPR as NAME)"
as a general purpose embedded assignment expression. However, this
idea has problems of its own:

1. In with statements and exception handlers, 'as' does *not* denote
ordinary assignment. In the former case, the name is bound to the
result of the EXPR.__enter__() call, in the latter to the exception
instance that was actually caught. If assignment expressions were
added, these could become a rather subtle trap (especially since many
__enter__() methods just return self)

2. Generator expressions and the various forms of comprehension create
new scopes to avoid leaking iteration variables, so, if embedded
assignments were to do anything useful there, additional forms like
"(EXPR as nonlocal NAME)" and "(EXPR as global NAME)" would be needed.
(And, in the nonlocal case, would still require that the name already
be defined in the containing scope)

3. Adding assignment expressions would mean having two ways to perform
assignments at the statement level (either using the existing
statement form or using the new expression form)

To date, nobody has been interested enough in the latter idea to put
together a formal PEP and reference implementation for python-dev's
consideration, and the former idea has been informally rejected
several times due to the lack of generality.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list