Skip to content Skip to sidebar Skip to footer

How To Check If Instance Exists If Variable Not Existing?

I have a button which imports a module with a class. The class (varClass) creates a window. If i click the button once again, i try this: if var: var.toggleUI() else : var

Solution 1:

You could catch the NameError exception:

try:
    var.toggleUI()
except NameError:
    var = varClass()

If you needed call toggleUI the first time too, just try the name itself:

try:
    var
except NameError:
    var = varClass()

var.toggleUI()

I'm not familiar with Maja, but if you can define the name elsewhere first and simply set it to None there, then your code would work too, if not better.

Solution 2:

Use Exceptions:

try:
    var.toggleUI()
except NameError:
    var = varClass()
    var.toggleUI()

Solution 3:

You could use the dir function

a=5
'a'indir()
'b'indir()

This will print

TrueFalse

So in your case

if'var'indir():
    var.toggleUI()
else :
    var = varClass()

Solution 4:

If you're doing this inside a button, you should offload the management of the var to the the module you're importing. Let the module handle the instantiation and the button lets the module do the heavy lifting. Rendundant imports dont hurt as long as the import has no side-effects (which it should not have if you're doing it right).

The module does something like this:

classSampleGui(object):
     # all sorts of good stuff here

_sample_gui_instance =None
def get_instance():
    _sample_gui_instance =sample_gui_instance orSampleGui()return _sample_gui_instance 

and the button just does

import SampleGuiModule
SampleGuiModule.get_instance().toggleUI()

This is the same check as the ones in everybody else's answer, but I think by delegating instance management to the module, instead of the button, you can have any level of complexity or initialization going on and share it between buttons, hotkeys or other scripts transparently.

I saved a few characters by using the or instead of if... is None; this will be tricky of for some reason a SampleGui truth tests as false. But it will only do that if you make force it to.

possibly useful: maya callbacks cheat sheet

Solution 5:

Default your var, and use it as a test:

var = None
ifvaris None:
  var = varClass()
var.toggleUI()

Post a Comment for "How To Check If Instance Exists If Variable Not Existing?"