Default argument evaluation in python

python

Default argument is evaluated at module load time

I write a celery task which accepts a date argument default to the current day. But when scheduled, the value is fixed, see:

@celery.task
def daily_task(run_date:date = date.today():
	print("running task at:", run_date);

The date is evaluated once at module loaded time. Thus, the value is fixed as it's only loaded once.

To fix this, you should set the date at runtime inside the function:

@celery.task
def daily_task(run_date: Optinal[date] = None):
    if run_date is None:
        run_date = date.today()
    print("running task at:", run_date)