Techiio-author
Started by Gibson DavidsonNov 3, 2021

Open
Incrementing integer using variable name string

2 VIEWES 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 2 VIEWES SHARE

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

Techiio-commentatorBruno Fernandez replied 4 months ago0 likes0 dislikes

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}
You must be Logged in to reply
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance