←back to thread

317 points est | 6 comments | | HN request time: 1.238s | source | bottom
Show context
_Codemonkeyism ◴[] No.17448573[source]
The PEP is here: https://www.python.org/dev/peps/pep-0572/

"This is a proposal for creating a way to assign to variables within an expression using the notation NAME := expr."

replies(3): >>17448578 #>>17448590 #>>17448623 #
1. mci ◴[] No.17448623[source]
> x = y = z = 0 # Equivalent: (x := (y := (z := 0)))

This comment is false. It should say

  x = y = z = 0  # Equivalent: (z := (y := (x := 0)))
"...assigns the single resulting object to each of the target lists, from left to right." https://docs.python.org/3/reference/simple_stmts.html#assign...

Here is a demonstration of the difference:

  >>> class Node: pass
  ...
  >>> node = blue_node = Node()
  >>> red_node = Node()
  >>> node = node.next = red_node
  >>> blue_node.next is red_node
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
  AttributeError: Node instance has no attribute 'next'
replies(2): >>17450341 #>>17450932 #
2. jessaustin ◴[] No.17450341[source]
I don't see how that demonstrates anything about the order of the assignment. It seems to show that node and blue_node are no longer the same object? (I'm not sure I understand how that came to be either, but perhaps it's due to the PEP...) I'm not saying your general point is wrong, just that the REPL listing doesn't demonstrate your general point.
replies(1): >>17450789 #
3. jwilk ◴[] No.17450789[source]
"node" is initially blue, and then you do:

  node = node.next = red_node
If assignments were right-to-left, the .next attribute would be set on the blue node.

If they were left-to-right, it would be added to the red node.

The AttributeError exception shows it is the latter order.

replies(1): >>17451496 #
4. jwilk ◴[] No.17450932[source]
You are technicaly correct, but...

If x, y, z are just variables, the order of assignments doesn't make any practical difference.

OTOH, complex assignment targets (such as "a[i]" or "a.b") are not supported for := assignments.

5. fractalb ◴[] No.17451496{3}[source]
It doesn't say anything about the order of assignment. It just shows that `node.next` wasn't evaluated to anything. `node.next` needs to be evaluated before doing any assignments
replies(1): >>17453835 #
6. jjnoakes ◴[] No.17453835{4}[source]
Sure it does. Write out the example with both orders of assignments (convert it to single assignments only) and run it both ways.