This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author terry.reedy
Recipients docs@python, terry.reedy
Date 2014-04-26.20:38:57
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1398544739.49.0.840910165962.issue21358@psf.upfronthosting.co.za>
In-reply-to
Content
https://docs.python.org/3/reference/simple_stmts.html#augmented-assignment-statements
"An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once."

As discussed and demonstrated as part of #21101 (see msg 215560) and following, this is not exactly true in current CPython. If the expression 'x' is 'y[k]', then the subscription is performed twice, once to get and once to set. Both y and k are still evaluated just once.

def ob():
   print('ob fetched')
   return d

def key():
   print('key called')
   return 0

d = [[]]
ob()[key()] += [1]
print(d)

# prints
ob fetched
key called
[[1]]

I suggest changing "x is only evaluated once." to something like

"x is usually only evaluated once. However, if x has the form y[k], y and k are evaluated once but the subscription may be done twice, once to get and once to set."

I intentionally said 'subscription may be' rather than 'subscription is' because implementations should remain free to do the subscription (and the whole expression x) just once -- by directly replacing the reference to the old value in the internals of the mapping structure with a reference to the new value.

#16701 discusses possible ambiguity in the next sentence, about 'in place'.
History
Date User Action Args
2014-04-26 20:38:59terry.reedysetrecipients: + terry.reedy, docs@python
2014-04-26 20:38:59terry.reedysetmessageid: <1398544739.49.0.840910165962.issue21358@psf.upfronthosting.co.za>
2014-04-26 20:38:59terry.reedylinkissue21358 messages
2014-04-26 20:38:57terry.reedycreate