擅长:python、mysql、java
<p>它总是安全的。作为<a href="https://docs.python.org/3/reference/compound_stmts.html#function-definitions" rel="noreferrer">spec says</a></p>
<blockquote>
<p>If the form “**identifier” is present, it is initialized to a <strong>new</strong>
ordered mapping receiving any excess keyword arguments, defaulting to
a <strong>new</strong> empty mapping of the same type.</p>
</blockquote>
<p><em>增加了强调。</em></p>
<p>您总是可以保证在可调用的内部得到一个新的映射对象。看这个例子</p>
<pre><code>def f(**kwargs):
print((id(kwargs), kwargs))
kwargs = {'foo': 'bar'}
print(id(kwargs))
# 140185018984344
f(**kwargs)
# (140185036822856, {'foo': 'bar'})
</code></pre>
<p>因此,尽管<code>f</code>可以修改通过<code>**</code>传递的对象,但它不能修改调用方的<code>**</code>对象本身。</p>
<hr/>
<p><em>更新</em>:既然你问过角落里的案子,这里有一个特别的地狱给你,它实际上修改了来电者的<code>kwargs</code>:</p>
<pre><code>def f(**kwargs):
kwargs['recursive!']['recursive!'] = 'Look ma, recursive!'
kwargs = {}
kwargs['recursive!'] = kwargs
f(**kwargs)
assert kwargs['recursive!'] == 'Look ma, recursive!'
</code></pre>
<p>不过,在野外你可能看不到这个。</p>