TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Understanding Python's augmented assignment (a += b)

72 点作者 ceronman超过 10 年前

7 条评论

icebraining超过 10 年前
Nice article, though I already understood the matter. Thanks for the link to PEP 463[1], though; I can see it cleaning up some of our code. Do you know if there have been any developments into implementing it?<p>[1] <a href="http://legacy.python.org/dev/peps/pep-0463/" rel="nofollow">http:&#x2F;&#x2F;legacy.python.org&#x2F;dev&#x2F;peps&#x2F;pep-0463&#x2F;</a>
评论 #9050124 未加载
danbruc超过 10 年前
What this article says about C++ is not true.
评论 #9050772 未加载
评论 #9050916 未加载
aftbit超过 10 年前
Why couldn&#x27;t Python do something like:<p><pre><code> &gt;&gt;&gt; _tmp = getitem(t, 0) &gt;&gt;&gt; setitem(t, 0, _tmp) &gt;&gt;&gt; try: &gt;&gt;&gt; _tmp2 = _tmp.__iadd__([2]) &gt;&gt;&gt; except AttributeError: &gt;&gt;&gt; _tmp2 = _tmp.__add__([2]) &gt;&gt;&gt; setitem(t, 0, _tmp2) </code></pre> Then if the first setitem raises, the rest of the code will be skipped. Obviously this isn&#x27;t perfect:<p>1. If setitem has strange side-effects, this will cause them to happen twice. 2. If setitem raises based on the value (rather than the key), this won&#x27;t notice that.<p>But otherwise, it seems like a pretty straightforward improvement, no?
danbruc超过 10 年前
The example look ill-conceived to begin with. If you want to extend the list that is the first element of the tuple just use t[0].extend([1]). Using an augmented assignment operator makes no sense if the left hand side can not be assigned to. I don&#x27;t know Python well enough to tell why it does not check if the left hand side can be assigned to before evaluating the right hand side, i.e. why it dos not check that __setitem__ is present. This would make the behavior more similar to a compiled statically typed language where this would be a compile time error and the right hand side would never get evaluated.
评论 #9051474 未加载
peterderivaz超过 10 年前
I ran into this when computing PSNR comparisons using a Numpy function that returned a numpy integer type:<p><pre><code> &gt;&gt;&gt; import numpy &gt;&gt;&gt; x=0 &gt;&gt;&gt; y=numpy.int32(2*10**9) &gt;&gt;&gt; x+=y &gt;&gt;&gt; x+=y &gt;&gt;&gt; x -294967296 </code></pre> In later versions of Python this gives a RuntimeWarning so this is less likely to cause problems now.
评论 #9051830 未加载
cagriaksay超过 10 年前
Official FAQ is easier to understand. I recommend reading that first before the article.
zrail超过 10 年前
This is a wonderful explanation of a deeply confusing situation. Thank you for posting.