[Python-ideas] Keyword same in right hand side of assignments (rev)

Steven D'Aprano steve at pearwood.info
Wed Mar 18 00:30:09 CET 2009


On Wed, 18 Mar 2009 12:21:46 am Jacob Holm wrote:

> I believe that as soon as the left-hand side stops being a simple
> variable and it is used in non-trivial expressions on the right-hand
> side, using the keyword would help clarify the intent.  What I mean
> is that the examples you should be looking at are more like:
>
> A[n+1] = same*same + 1
> B[2*j].foo = frobnicate(same, same+1)
> ...
>
> If you try expanding these into current python with minimal change in
> semantics you will end up with something like
>
> _1 = n+1
> _2 = A[_1]
> A[_1] = _2*_2 + 1
> del _1
> del _2
>
> _1 = B[2*j]
> _2 = _1.foo
> _1.foo = frobnicate(_2, _2+1)
> del _1
> del _2
>
> which is much less readable.

Of course it is, because it's obfuscated. What's with the leading 
underscore names? Inside a function, they're not accessible to outside 
callers, so the notion of "private" and "public" doesn't apply, and in 
module-level code you delete them at the end, so they won't be imported 
because they no longer exist. (BTW, there's no need to delete the names 
one at a time. "del _1, _2" does what you want.)

What's wrong with the clear, simple and obvious?

A[n+1] = A[n+1]**2 + 1

If you really care about calculating n+1 twice then just use a 
meaningful name instead of an obfuscated name. This clarifies the 
intent of the code, instead of hiding it:

index = n+1  # or even just i
A[index] = A[index]**2 + 1

Likewise:

tmp = B[2*j].foo
B[2*j].foo = frobnicate(tmp, tmp+1)

Or any combination of standard idioms. If you really insist, you can 
even delete the temporary names afterwards, but why would you bother 
inside a function?



-- 
Steven D'Aprano



More information about the Python-ideas mailing list