Python Antipattern : Impure(IO) Default Arguments
One of most liked features of python functions is default arguments . We use them
every day . But there is gotcha that you need to take care .
Function default arguments are evaluated at module load time rather than function invocation time .
Which helps with perfomance benefits when the default arguments are static and deterministic .
So if your function is non-deterministic or has side-effects, you could run into trouble.
As the example shows, the printed time is frozen; it was set once when the code was first evaluated.
# Antitpattern and buggy
def current_datetime(dt = datetime.datetime.now()):
print(dt)
>>> current_datetime()
2021-10-09 16:09:43.009959
>>> current_datetime()
2021-10-09 16:09:43.009959
# do this instead
def current_datetime(dt=None) :
if dt is None :
dt = datetime.datetime.now()
print(dt)
current_datetime()
>> 2022-07-24 16:07:16.435203
current_datetime()
>> 2022-07-24 16:08:16.635203
Top comments (0)