LoginSignup
4
4

More than 5 years have passed since last update.

Pythonのデフォルト引数の挙動には気をつけようと思った

Posted at

元エントリからの単なる転載

pythonのデフォルト引数の挙動は勘違いしそうで怖いので気をつけたい。

➜  ~ python
Python 2.7.11 (default, Feb  2 2016, 21:44:54)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def func(arg={}):
...     return arg
...
>>> foo = func()
>>> foo['a'] = 'foo'
>>>
>>> bar = func()
>>> bar['b'] = 'bar'
>>> print(foo)
{'a': 'foo', 'b': 'bar'}
>>> print(bar)
{'a': 'foo', 'b': 'bar'}

デフォルト引数はモジュールロード時の1度だけしか評価されないために、呼び出しの間で共有されている。
なんでこんな仕様にしたんだろうな・・・。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4