LoginSignup
2
1

More than 5 years have passed since last update.

Python > default argumentにおいてmutableなobject (例: list)を初期化しない / 定義時に初期化されるため

Last updated at Posted at 2017-03-30

@ Introducing Python: Modern Computing in Simple Packages by Bill Lubanovic
(No. 2550 / 12833)

Default argument values are calculated when the function is defined, not when it is run.
A common error with new (and sometimes not-so-new) Python programmers is to use a mutable data type such as a list or dictionary as a default argument.

例として
http://ideone.com/66DaME

def buggy(arg, result=[]):
    result.append(arg)
    print(result)

buggy('a')
buggy('b')
結果
['a']
['a', 'b']

以下のようにするとのこと。

def nobuggy(arg, result=None):
    if result is None:
        result = []
    result.append(arg)
    print(result)

nobuggy('a')
nobuggy('b')
結果
['a']
['b']

参考?: 引数の解釈と値の構築

「デフォルト引数」としては標準ドキュメントで検索できなかった。

2
1
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
2
1