首页 > 解决方案 > python默认dict参数在函数调用中被缓存

问题描述

我来自 js 世界,无法将这个小怪癖包装在我的脑海中。考虑这个简单的 python 程序:

库文件

def test(i, memo=dict()):
  memo[i] = i
  print(memo)
  return i

我从 repl 调用这个:

>>> import lib
>>> lib.test(1)
{1: 1}
1

>>> lib.test(2)
{1: 1, 2: 2}
2

>>> lib.test(3)
{1: 1, 2: 2, 3: 3}
3

也许我遗漏了一些关于 python 模块导入等的东西——我希望每次调用它时都会用新字典初始化备忘录,但它知道以前的调用。

标签: pythonpython-3.xmodule

解决方案


这样做:

def test(i, memo=None):
  memo = {} if memo is None else memo
  memo[i] = i
  print(memo)
  return i

https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments了解更多信息。


推荐阅读