<p>现在3.8已经正式发布了,还有一些例子和基本原理。</p>
<blockquote>
<p>Naming the result of an expression is an important part of programming, allowing a descriptive name to be used in place of a longer expression, and permitting reuse. Currently, this feature is available only in statement form, making it unavailable in list comprehensions and other expression contexts.</p>
</blockquote>
<p>来源:<a href="https://old.reddit.com/r/programming/comments/dhwtvt/python_38_released/f3rlzxt/" rel="nofollow noreferrer">LicensedProfessional's reddit comment</a></p>
<blockquote>
<p>Handle a matched regex</p>
</blockquote>
<pre><code>if (match := pattern.search(data)) is not None:
# Do something with match
</code></pre>
<blockquote>
<p>A loop that can't be trivially rewritten using 2-arg iter()</p>
</blockquote>
<pre><code>while chunk := file.read(8192):
process(chunk)
</code></pre>
<blockquote>
<p>Reuse a value that's expensive to compute</p>
</blockquote>
<pre><code>[y := f(x), y**2, y**3]
</code></pre>
<blockquote>
<p>Share a subexpression between a comprehension filter clause and its output</p>
</blockquote>
<pre><code>filtered_data = [y for x in data if (y := f(x)) is not None]
</code></pre>