Using system.date.now() as default parameter

It seems to me like using system.date.now() as a default parameter in a function is bad practice because...

This is easy to see within the script console, but when you apply this concept to the script library, you could call a function much later than a few seconds and it will use the an earlier value. Saving your project will cause this variable to be re-evaluated. See this example in the script console.

from time import sleep

def test(date=system.date.now()):
	return date

for i in range(10):
	sleep(1)
	test() 

This is not a bug, it's working as intended.

Python named parameter values are evaluated once, when the function is defined, not every time the function is called.

2 Likes

Is the garbage collector the only condition that causes this value to need to be reevaluated?

No, GC is not relevant.

As far as Ignition goes, saving your project will cause it be re-evaluated because that's when all the script modules get loaded/executed and the function is defined.

1 Like

Try this if you really want a named parameter with a default value that is "live" each time:

def test(date=None):
	if not date:
		date = system.date.now()
5 Likes