Search code examples
pythonmayamel

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 = varClass()

But var doesn' exist the first time you create the window after opening Maya. How can i get this working?


Solution

  • 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.