Python’s Default Argument Values are Sticky

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.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.