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:
def do_something(self, entry, date_time = datetime.datetime.now()):
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:
def do_something(self, entry, date_time = None):
if date_time is None:
date_time = datetime.datetime.now()
This is actually mentioned in the Python documentation.