[Python-Dev] Assignment expression and coding style: the while True case

Victor Stinner vstinner at redhat.com
Thu Jul 5 08:13:48 EDT 2018


2018-07-05 9:10 GMT+02:00 Tim Peters <tim.peters at gmail.com>:
> I'm all in favor of what Victor is doing:  looking at how this stuff will
> work in actual code.  That's a great antidote to the spread of theoretical
> fears.

FYI I'm trying to use assignment expressions on the stdlib because
*all* examples of the PEP 572 look artificial to me.

Like "group = re.match(data).group(1) if re.match(data) else None"
which is followed by "(TODO: Include Guido's evidence, and do a more
systematic search.)" I cannot find such inefficient code in the
stdlib. I'm not saying that nobody writes code like that, just that
developers with a good Python expertise would avoid to write such
code.

"filtered_data = [y for x in data if (y := f(x)) is not None]" also
seems artificial. In the 711,617 lines of Python code of the stdlib, I
only found *one* example:

    labels = [label.strip() for label
                            in self._file.readline()[1:].split(b',')
                            if label.strip()]

=> https://github.com/python/cpython/pull/8098/files

And I also only found a single for loop which can be converted to a
list comprehension thanks to assignement expression.

    lines = []
    for raw_line in raw_lines:
        match = line_pat.search(raw_line.strip())
        if match:
            lines.append(match.group(1, 2))

> Wholesale changes to the std lib are unlikely to happen regardless.  Broad
> patches just to spell things differently without _need_ are discouraged.

So PEP 572 is purely syntax sugar? It doesn't bring anything to the
stdlib for example?

My current 3 pull requests showing how assignment expressions can be
used in the stdlib:

while True: https://github.com/python/cpython/pull/8095/files
match/group: https://github.com/python/cpython/pull/8097/files
list comp: https://github.com/python/cpython/pull/8098/files

Right now, I'm still not really excited by the new code.

If you spotted other parts of the stdlib where assignment expressions
would be appropriate, please tell me and I will try to write more pull
requests :-)

Victor


More information about the Python-Dev mailing list