Getting KeyError while iterating object names using locals()
Question
I have 5 objects, mac5_le()
, mac4_le
and so on. I am trying to extract some value from each of the objects as follows,
for i in range(5,-1,-1):
m = locals()['self.mac'+str(i)+'_le.text()']
print m
I am getting the error as KeyError: 'self.mac5_le.text()'.
Any Idea?
Solution
What the what?
m = getattr(self, 'mac%d_le' % i).text()
OTHER TIPS
Not sure why you would want to munge objects around that way, but you've definitely got your syntax wrong:
locals()['self.mac'+str(i)+'_le'].text()
should "work".
I see a few things wrong with what you're attempting. First, self.name
variables are not local scope. They're either part of the instance, or part of the class. Locals are variables that are accessible from your current function scope, but not the global scope. For instance, in the code below, you would see foo
and bar
, but not baz
:
baz = 1
def silly():
# These two variables are local
foo = 2
bar = 3
print locals()
Calling silly()
:
>>> silly()
{'foo': 2, 'bar': 3}
Secondly, the locals()
and globals()
dictionaries don't resolve the dot operator, nor will they call functions.
What you want to do is use something like getattr
, or create an api that works better for you (the code you're trying to write isn't very idiomatic Python). Here's what is might look like with getattr
:
for i in range(5,-1,-1):
m = getattr(self, 'mac'+str(i)+'_le').text()
print m
getattr
is will do all the right lookups underneath the hood to find macN_le
. Once you have a reference to the object, then you can call .text()
on it.
Hope that helps!