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

maya, python

Solution

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"

Problem

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() ```

Original source