Default Parameters Values and Mutable/Callable Objects

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
Advertisements

One Comment on “Default Parameters Values and Mutable/Callable Objects”

  1. Mike says:

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

    _________________________________
    Making Money $150 An Hour


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s