Python and Default Argument Values

I love Python as a programming language. For a sophisticated language it has very few gotchas and is mostly very intuitive. One confusing feature is that default argument values for functions or class methods are only evaluated once during the execution of a Python script. It is best to show this using an example:

>>> def my_function(arg1, arg2=[]):
...     arg2.append(arg1)
...     return arg2
...
>>> my_function(10)
[10]
>>> my_function(2)
[10, 2]
>>>

Note that during the second call to my_function() we get a list containing the argument from the previous call. This is not intuitive but is the expected behavior under Python. Python evaluates the default argument arg2 only once. On subsequent calls to the function it keeps using the previously evaluated default value even if it is modified. The lesson learned here is to never use mutable objects are default arguments to functions.. A better way to code the same function is:

>>> def my_function(arg1, arg2=None):
...     if arg2 is None:
...         arg2 = []
...     arg2.append(arg1)
...     return arg2
...
>>> my_function(10)
[10]
>>> my_function(2)
[2]

Much better.

This entry was posted in Python and tagged . Bookmark the permalink.

One Response to Python and Default Argument Values

  1. Pingback: ORLANDO

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>