←back to thread

317 points est | 1 comments | | HN request time: 0.206s | source
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 #
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 #
1. 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.