Globally scoped objects

Is it possible to persist variables / objects across scripts?

E.g. I have a gateway or client event script and I would like to access a variable each time that script runs. A simple example is a state machine where I need to ‘remember’ the state. Obviously I can write the state to a memory tag and read it on each script execution, but this has its drawbacks.

What I would really like to do is instantiate a Python class in the gateway scope to handle more complex functionality, but I need a way to access the class instance.

This is similar to the ‘chart’ scope in the SFC module, except the SFC module does not work for my use case.


Hi dfreilberger,

Yes, this can be done. Use a global variable.

Here’s an example. The following script is in the project.util Python module:

logger = system.util.getLogger("Incrementer")
total = 0
def increment(value):
	global total
	total += value"Current value: %s"% total)

Note that any variable that is assigned a value at module scope (outside function or class definitions) is a global variable. The “global” keyword just means that the global variable is to be modified instead of creating a new local variable with the same name.

I created a Gateway Timer Script that runs every 5 seconds that calls the project.util.increment function:


The result is that every 5 seconds the total global variable is incremented by 10 and output to the Gateway console. So the console looks like this after 30 seconds:

Current value: 10
Current value: 20
Current value: 30
Current value: 40
Current value: 50
Current value: 60


Careful with this approach.

  1. When you save and/or the script manager re-initializes, the global scopes will be initialized again and you’ll wipe out whatever state you had in there.
  2. This does not allow you to reach across Ignition scopes (i.e. stuff you do in gateway global isn’t visible to clients, stuff you do in one client is not visible in another, etc…)

Memory tags are the recommended approach.

Thank you Nick & Kevin. For now I guess I will stick with memory tags, but it is good to know about the global variable.