Custom Search

Saturday, April 16, 2011

python Be careful with mutable default arguments

Be careful with mutable default arguments

>>> def foo(x=[]):
... x.append(5)
... print x
...
>>> foo()
[5]
>>> foo()
[5, 5]
>>> foo()
[5, 5, 5]

Instead, you should use.

>>> def foo(x=None):
... if x is None:
... x = []
... x.append(5)
... print x
>>> foo()
[5]
>>> foo()
[5]

No comments:

Post a Comment