[Python-Dev] Examples for PEP 572 (original) (raw)

Steven D'Aprano steve at pearwood.info
Wed Jul 4 15🔞32 EDT 2018


On Wed, Jul 04, 2018 at 08:32:32PM +0200, Sven R. Kunze wrote:

>>while total != (total := total + term): >>    term = mx2 / (i(i+1)) >>    i += 2 >>return total

This very example here caught my eye. Isn't total not always equal to total? What would "regular" Python have looked like?

Read the Appendix to the PEP:

https://github.com/python/peps/blob/master/pep-0572.rst

And no, total is not always not equal to total. When total and term are sufficiently different, total+term underflows to just total, and the loop exits.

py> total = 1.5e30 py> term = 12.5 py> total + term != total False

I read it as:

while total != updated total:
    do stuff

and find it easier to follow than having to juggle the extra book-keeping "old" variable in the original code.

YMMV.

-- Steve



More information about the Python-Dev mailing list