Default Function Params in Python

This is how to write bug-free default parameters for your python functions.

Dynamic Defaults

A dynamic default is one that changes on each function invocation. An example would be a datetime parameter that is set to the current datetime if not explicit datetime is sent as an argument.

Not in Function Signature

If you want a dynamic default, do not define the default in the function signature! This looks good and is an intuitive place to put it, but it will not function as intended.

This is because python will only run the code for the default at the time the function is declared and interpreted.

The "dynamic" default will be the same for the whole running time of the program.

Define Default in the Function Body

Instead, define dynamic defaults in the function body. Check for the parameter to be set to something you know to be non-default. If not, calculate the default. Something like so:

import datetime from datetime
function do_time_stuff(now=None):
    if not now:
        now = datetime.now()