Best practice for re-initializing Default parameters

Whats your take on the best practice for re-initializing default parameters (ie. resetting to the initial value)?

Consider the following minimal example:

function saved in count_times_executed.py

def count_times_executed(counter=[0]):
 counter[0] +=1
 print(counter[0])

main.py

from count_times_executed import count_times_executed    

count_times_executed()

counter will be re-initialized to 0 only when I go into the file count_times_executed.py and execute the fun def before running main.py

In the Spyder IDE, clicking on ‘Run File (F5)’ will automatically reinitialize counter.

count_times_executed.__ defaults__= ([0],) will re-initialize counter.

How do you handle re-initializing default parameters?

Thank you

This might not be the answer you expected.

Mutable default parameters lead mostly to confusion and require extra care to not fall into unexpected side-effect. For counters using small class or closure will be much more convenient and easier. From the start it will also allow creating multiple, separate counters.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.