Default Parameters Values and Mutable/Callable Objects

2008 December 11
tags:
by Tzury Bar Yochay

Quoting from the python Language Reference[link]:

Default parameter values are evaluated when the function definition is executed.
This means that the expression is evaluated once, when the function is defined, and that that same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function, e.g. …

I was not aware of this. I have an excuse though, in previous versions of Python, language reference was described as “for language lawyers” [link]. Since I never liked lawyers, I never bothered reading it. I am happy though it was changed in current release and now it is described as “describes syntax and language elements”. I guess I have to read it now.

Below is an example for a bug I had caused by this feature and which made me aware of this issue.

>>> import time
>>> def now(t=time.time()):
...     print t
...
>>> now()
1228988224.36
>>> now()
1228988224.36
One Response leave one →
  1. 2009 March 1

    Just passing by.Btw, you website have great content!

    _________________________________
    Making Money $150 An Hour

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS