Python と Ruby、デフォルト引数の評価の違い
Python のチュートリアルで勉強している。
その中の 4.7.1 Default Argument Values に、気になる記述があった。
The default values are evaluated at the point of function definition in the defining scope
Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes.
つまり、Python における、関数のデフォルト引数は:
- 関数が定義された時点で
- 最初の1回のみ評価される
というわけだ。
早速、チュートリアルにあるサンプルを python で実行してみる。
% python
>>> def f(a, l=[]):
... l.append(a)
... return l
...
>>> print f(1)
[1]
>>> print f(2)
[1, 2]
>>> print f(3)
[1, 2, 3]
たしかに、関数 f のデフォルト引数 l には定義した時点での [] が、そのまま保持されているようだ。
では、同様のサンプルを今度は Ruby で試してみる。
% irb
irb(main):001:0> def f(a, l=[])
irb(main):002:1> l << a
irb(main):003:1> end
=> nil
irb(main):004:0> f(1)
=> [1]
irb(main):005:0> f(2)
=> [2]
irb(main):006:0> f(3)
=> [3]
実行結果のとおり、Ruby のデフォルト引数は Python とは異なり、関数を実行するたびに評価される。
Python 2.5 をインストール
冬休み。お勉強の一環として Python を考えている。
現時点の最新版は 2.5、一方、Mac OS X Tiger に標準インストールされているのは 2.3.2。 というわけでダウンロードページから Python 2.5 のソースコードをダウンロードして、インストール。
% curl -O http://www.python.org/ftp/python/2.5/Python-2.5.tgz
% tar xvzf Python-2.5.tgz
% cd Python-2.5
% ./configure
% make
% sudo make install
特に問題なくインストールできた。
% python -V
Python 2.5
お約束通り、Hello, World で幕開け。
% python
Python 2.5 (r25:51908, Jan 1 2007, 17:41:26)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print "Hello, World!"
Hello, World!