Checking if a Variable Exists in Python - Doesn't work with self

13,953

Solution 1

I think you want hasattr(self,'locList')

Although, you're usually better off trying to use an attribute and catching the AttributeError which gets raised if it isn't present:

try:
    print self.locList
except AttributeError:
    self.locList = "Initialized value"

Solution 2

Answering from a bit of a different perspective. Try ... catch, getattr or dir is the way to go if you just want the code to work.

The call locals() returns a dictionary of local scope. That is it includes self. However, you are asking for the child of self (self.locList). The child is simply not in the dictionary. The closest thing to what you are doing would be:

if 'locList' in dir(self):
    print 'it exists'

function dir being the generic way to query items of objects. But as noted in the other posts, it does not make much sense to query objects' attributes from a speed standpoint.

Solution 3

You can use try/except or getattr with a default value, but those things don't make sense with your code. The __init__ method is there to initialize the object:

def __init__(self):
    self.locList = []

It makes no sense to allow locList not to exist. A zero length list is an object without locations.

Share:
13,953
Vii
Author by

Vii

Updated on June 04, 2022

Comments

  • Vii
    Vii about 2 years

    Before you down rep this post, it hasn't been asked anywhere that I can find.

    I'm checking for the existence of a list by using

    if 'self.locList' in locals():
        print 'it exists'
    

    But it doesn't work. It never thinks it exists. This must be because I'm using inheritance and the self. to reference it elsewhere, I don't understand what's happening.

    Can anyone shed some light please?

    Here is the full code:

    import maya.cmds as cmds
    
    class primWingS():
        def __init__(self):
            pass
        def setupWing(self, *args):
            pass
        def createLocs(self, list):
            for i in range(list):
        if 'self.locList' in locals():
            print 'it exists'
                else:
                    self.locList = []
                loc = cmds.spaceLocator(n = self.lName('dummyLocator' + str(i + 1) + '_LOC'))
                self.locList.append(loc)
                print self.locList
    
    
    p = primWingS()