logoalt Hacker News

Chained Assignment in Python Bytecode

18 pointsby wenderenlast Saturday at 7:50 AM15 commentsview on HN

Comments

jp57today at 4:28 PM

The author's expectations seem strange. Take another example:

    a = b = random.random()
I would not expect a and b to get different values. It would be very strange if using `[]` had different behavior than a function call in the same place. Am I out of step here?
show 2 replies
selridgetoday at 7:46 PM

“Since Python 3.6, every Python instruction has been given an odd number of arguments (even if it doesn't need any) so that the byte offsets are always even.”

I don’t think this is true. I think something like it is true for CPython (an argument isn’t added but the byte is kept for functions w no arg) but it’s not a statement about Python.

KerrickStaleytoday at 6:12 PM

  a = b = []
has the same semantics here as

  b = []
  a = b
which I don't find surprising.
Twirrimtoday at 6:05 PM

I've seen stuff posted about chained assignment footguns in python regularly over the years, and it always surprises me. I don't think I've ever written them, or reviewed code that does. I don't think it'd occur to me to even think about writing a chained assignment.

Is chained assignment a pattern that comes from another language that people are applying to python?

kccqzytoday at 3:28 PM

Chained assignments are banned according to the style guide at my workplace. Too many opportunities for misuse. And if you insist on a one-liner assignment to two variables just use two statements separated by the semicolon. I challenge anyone to work out what this code does:

    a, b = b[a] = 1, [0, 1, 2, 3]
show 1 reply
mathisfun123today at 3:08 PM

> list object is constructed once and assigned to both variables

Ummm no the list is constructed once and assigned to b and then b is assigned to a. It would be crazy semantics if `a = b = ...` meant `a` was assigned `...`.

Edit: I'm wrong it's left to right not right to left, which makes the complaint in the article even dumber.

show 2 replies