When are modules and datasets loaded?

I am relatively new to ignition and Python, so pardon my simple question. I have programming experience in other languages though.

I am writing a script, which will run on the server. The scrip will be called from an OPC trigger.

If it use
from x import Y

When is the import done? My concern is speed of execution, since Python is interpreted. Does it load once, or every time the script is executed?

Also
I have data, in a database, which I will use as a lookup. I would like to load this into a python dataset once, and access it from memory, rather than accessing the DB each time the code runs. How do I scope this so that it behaves like global variables until I reload it.

Thanks

Start here:

2 Likes

Your entire script, including imports, is generally "compiled" once (by Ignition itself) into a callable Jython object that we then re-use until the next time you change the script definition. This actually allows Jython to run quite fast; the JVM is very well optimized.

Your options are system.util.getGlobals() or a memory tag, for shared global mutable state. Be careful to only put native Python data structures into globals; adding arbitrary classes you're defining in your own code can lead to memory leaks, because the JVM won't be able to recover all of the Jython scaffolding around your class.

Do you actually retain the outer callable? All of the code that needs to persist ends up in the PyModule's global PyStringMap.

Well, it varies across the platform, but the general pattern is to use an appropriate ScriptManager to "compile" into a ScriptManager.ScriptFunction that can be called with whatever args as appropriate.

Different modules do it differently. For instance, in Perspective everything extends from ScriptFunctionHelper which does the tricky scaffolding of all the required gateway scoped contextual stuff at invocation time.

Right, that is the new model for extension functions, where Ignition is supplying the def something(). But project library scripts can't be treated that way.

Related: