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()
To check if a local variable exists in Python, use the in operator against the output of locals() function, which has a dictionary of a current local variables table. The “in operator” returns a boolean value. If a variable exists, it returns True otherwise, False.
Don't use self when:you want to call an instance method normally; referencing a class attribute inside the class definition but outside an instance method; you are inside a static method.
Checking Local Variable Existence in Python To check the existence of a variable locally we are going to use the locals() function to get the dictionary of the current local symbol table. It returns true if the variable is found in the local entry system else returns false.
Use the is not operator to check if a variable is not None in Python, e.g. if my_var is not None: . The is not operator returns True if the values on the left-hand and right-hand sides don't point to the same object (same location in memory).
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With