I'm doing the following in the python interpreter and it works:
rhce=rhcsa=0
args=['rhce,'rhcsa']
for cert in args:
exec(cert+'+=1')
print(eval(cert))
>>> 1
>>> 1
As you may see the variable is incremented, whether you use print(rhce) or print(eval(cert)). But, when I put the precise same snippet of code inner a class characteristic, it now does not work. No exceptions are thrown, however, the variable never increments. It's like the exec isn't running:
def addCertUser(self,userid,args):
rhcsa=rhce=0
print(args)
try:
for cert in args:
exec(cert+'+=1')
print(eval(cert))
except for Exception as e:
print(e)
>>> ['rhce', 'rhcsa']
>>> 0
>>> 0
1 Replies
Its never a good idea to eval or exec code, 99 times out of 100 there is a better way to do it. In this case unless you have any other reason that really needs to use eval and exec you could achieve what your trying with a dict. it can hold a key ("name") used to reference or look up your value quite safely.
class MyClass:
def __init__(self):
self.my_counts = {
'rhce': 0,
'rhcsa': 0
}
def add_cert_user(self, userid, args):
print("start of function", self.my_counts)
for cert in args:
if cert in self.my_counts:
self.my_counts[cert] += 1
print("end of function", self.my_counts)
me = MyClass()
args = ['rhce','rhcsa']
me.add_cert_user("test", args)
me.add_cert_user("test", args)
me.add_cert_user("test", args)
OUTPUT
start of function {'rhce': 0, 'rhcsa': 0}
end of function {'rhce': 1, 'rhcsa': 1}
start of function {'rhce': 1, 'rhcsa': 1}
end of function {'rhce': 2, 'rhcsa': 2}
start of function {'rhce': 2, 'rhcsa': 2}
end of function {'rhce': 3, 'rhcsa': 3}