[Python-ideas] On evaluating features [was: Unpacking iterables for augmented assignment]

Jonathan Fine jfine2358 at gmail.com
Tue Aug 28 15:20:10 EDT 2018


Guido wrote

> Perhaps someone can do some research and unearth real code that contains
> series of += assignments that would become more readable by collapsing them
> into a single line using the proposed construct.

Here's some notes towards finding (or constructing) such examples.

First note that it's awkward to unpack

  a, b = b, a # swap values

because this simple solution does not work (as we need a temporary)

  a = b
  b = a

so perhaps our example should require unpacking, to avoid the use of temporarys.

Now consider, for example,

  wibble(4).wobble.cheese += 8

This has semantics

  tmp1 = wibble(4).wobble
  tmp2 = tmp1.cheese
  tmp1.cheese = tmp2 + 8

which is different to and harder to write than

  wibble(4).wobble.cheese = wibble(4).wobble.cheese + 8

so perhaps our example should involve an assignable expression, such
as wibble(4).wobble.cheese.

So here's a concocted example.

  ns.aaa.a, ns.bbb.b, += 2 * ns.bbb.b, 3 * ns.aaa.a

I describe this as a namespace-of-values, whose values change at least
logically all at the same time. In other words, it's something like

    vector = apply(matrix, vector)

This example can be expanded by first computing the values, and then
doing the assignment.

  tmp1, tmp2 = ns.bbb.b, ns.aaa.a
  ns.aaa.a += 2 * tmp2
  ns.bbb.b += 3 * tmp1

The following avoids the double lookup of ns.aaa.a (and of ns.bbb.b).

  tmp1, tmp2 = ns.bbb.b, ns.aaa.a
  ns.aaa.a = tmp1 + 2 * tmp2
  ns.bbb.b = tmp2 + 3 * tmp1

So far, this is the best artificial example I've come up with.

-- 
Jonathan


More information about the Python-ideas mailing list