Congrats to Chris for breaking his PEP curse

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Jul 3 21:59:46 EDT 2018


Congratulations to Chris Angelico for breaking the dreaded "any PEP 
written by Chris will be rejected" curse :-)

Guido has announced his intention to accept PEP 572 (assignment 
expressions) once the PEP has been cleaned up a bit.

https://www.python.org/dev/peps/pep-0572/

(The current version of the PEP doesn't quite match the proposal as 
nutted out over about a bazillion emails on two mailing lists starting in 
FEBRUARY!!!)


Summary:

Python 3.8 will allow an assignment-as-expression operator. The most 
common uses are expected to be if and while statements:

    condition = expression
    while condition:
        do_something()
        condition = expression

will become:

    while condition := expression:
        do_something()


Cascades of if statements, such as:

    # the dreaded arrowhead anti-pattern
    mo = re.match(pattern, text)
    if mo:
        ...
    else:
        mo = re.match(another_pattern, text):
        if mo:
            ...
        else:
            mo = re.match(third_pattern, text):
            if mo:
                ...


will become flatter and easier to read:

    if mo := re.match(pattern, text):
        ...
    elif mo := re.match(another_pattern, text):
        ...
    elif mo := re.match(third_pattern, text):
        ...


FAQs:

Q. Why Pascal's assignment operator := instead of regular = assignment?

A. To avoid the C bug magnet of mistakenly writing "if x = expr" when
   you intended to write "if x == expr".


Q. Why not use "as"?

A. There is an ambiguity due to with and except statements:

    with expr as name

    except Exception as name

   are already permitted and mean something different to ordinary
   assignment expressions.


Q. Oh no, Python is doomed! This is the end of the world!

A. That's not actually a question, is it?




-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson




More information about the Python-list mailing list