Default value for optional parameters unexpected behaviour?

Shashank Singh shashank.sunny.singh at gmail.com
Sun Jun 26 14:39:18 EDT 2011


On Sun, Jun 26, 2011 at 11:58 PM, Marc Aymerich <glicerinu at gmail.com> wrote:
> Hi,
> I'm trying to define a function that has an optional parameter which
> should be an empty list whenever it isn't given. However, it takes as
> value the same value as the last time the function was executed. What
> is the reason of this behaviour? How does python deal with default
> values (i.e. when are they assigned/created)?

This has been discussed before in this list, quite a few times
http://mail.python.org/pipermail/python-list/2010-March/1239044.html

A solution is to accept default value as None assign to [] by checking
for None inside the function

def f(a=None):
  if a is None: a = []



-- 
Regards
Shashank Singh
http://rationalpie.wordpress.com



More information about the Python-list mailing list