Class object scope issues

I am having some trouble with scoping in Ignition. I am trying to create a persistent class object that I can access from anywhere that is gateway scoped.

I have a script module with a class definition and a couple of functions defined (shared.Simulation):

class myclass:
Def init(self)
self.y=0
def startup():
shared.simulation.x=myclass()
def run():
z = shared.simulation.x.y

In a Data Type definition, I have a tag value change script that calls the run function:
shared.simulation.run()

The startup function needs to get called first.
If I put the call to startup (instantiates the object “x” in a memory tag (mytag) value change script, I get no error

However, if I instead put that same call to the startup in a Gateway Event script,(tag value change event) and assign the same memory tag (mytag), then I get an error that shared.Simulation has no attribute “x”, and globals() does not contain the class instance I created using the startup function call.

I thought that tag change event scripts were gateway scoped and so I don’t understand why the object does not seem to exist in the same memory space.

[quote=“dberry”]I am having some trouble with scoping in Ignition. I am trying to create a persistent class object that I can access from anywhere that is gateway scoped.[/quote]You are close. Don’t use a startup function. Simply instantiate the class at the top level of your module. (Modules are “initialized” by running them.) Like so:[code]class myclass:
def init(self)
self.y=0

x=myclass()

def run():
z = x.y[/code]You should be aware that this startup operation will happen any time any shared script module is edited and saved.
{ Also, use the “code” annotation in your posts so your readers can see the indents. }

Thank you for your helpful reply. This did the trick. And thanks for pointing out the “code” annotation.

I guess I still don’t understand why explicitly instantiating the class to the shared.Simulation module from within a function call doesn’t create the object in the same memory space? Does the object only persist until this function completes execution?

[quote=“dberry”]I guess I still don’t understand why explicitly instantiating the class to the shared.Simulation module from within a function call doesn’t create the object in the same memory space? Does the object only persist until this function completes execution?[/quote]Never really thought about it. Only by putting the assignment at the top level can you avoid races between your setup() and run(). A call to run() from outside the script module has to wait for the script module to fully load (execute top to bottom), but won’t necessarily wait for anything else.