User Tools

Site Tools


default_arguments_in_python_are_evaluated_only_once

Default arguments in Python are evaluated only once

Python’s default arguments are evaluated once when the function is defined, not each time the function is called. Consider for example

% cat test_defaults.py 
import datetime
import time

def test_defaults(prefix, now=datetime.datetime.now()):
    print(prefix, now)

test_defaults('one')
time.sleep(1)

test_defaults('two')
time.sleep(1)

test_defaults('three', datetime.datetime.now())
time.sleep(1)

test_defaults('four')

which outputs:

% python3 test_defaults.py
one 2021-08-14 20:13:27.830082
two 2021-08-14 20:13:27.830082
three 2021-08-14 20:13:29.832481
four 2021-08-14 20:13:27.830082

Notice that 'one', 'two' and 'four' have the same time. It changes only when it is explicitly overridden.

References

default_arguments_in_python_are_evaluated_only_once.txt · Last modified: 2021/08/15 00:38 by raju