May 252012
 

I can’t believe it’s taken me this long to learn this: Python’s default argument values are only evaluated once during runtime. I’ve never encountered this before because I don’t use default arguments very often, and when I do, it’s often to set something to a static value.

Today, I encountered a function definition where I wanted to default an argument to the current date/time:

Every time I ran the function, the value of date_time was the same: Whatever the date/time was when the method first ran. So, instead, I did something like this:

This is actually mentioned in the Python documentation.