简体   繁体   中英

Dynamically setting variables within a function with exec()

This is just a skeleton of what I'm trying to do, mostly it'll be used for taking a global variable on a function call to store to disk current operational state, but instead of a massive static block of code, I'm trying to use a function call to create needed storage state and set its contents, for the desired object/variable in active use.

colorlist = ["AliceBlue","#F0F8FF","AntiqueWhite","#FAEBD7","Aqua"]
tmpobj = None

def chgState(objname):
    global tmpobj
    exec(f"global {objname}")
    exec(f"tmpobj = {objname}")
    print(f"{objname} {type(**tmpobj**)}\n") #**'s only to show step point, they are not in the code
    print(f"{obj}")
    #file storage junk.. blah blah

chgState("colorlist")

I keep getting tmpobj undefined , but if I step through the code, tmpobj that's in the code will show the correct contents before erroring out.

Would be preferred to be able to utilize some of the globals but even in a local context would be nice.

I've even attempted using __local[{objname}] in the exec block but once again tmpobj undefined .

@Barmar's comment nailed it:

colorlist = ["AliceBlue","#F0F8FF","AntiqueWhite","#FAEBD7","Aqua"]
tmpobj = None

def chgState(objname):
    global tmpobj
    exec(f"global {objname}")
    tmpobj = globals()[objname] # Magic here - thanks again
    print(f"{objname} {type(tmpobj)}\n")
    print(f"{tmpobj}")
    #file storage junk.. blah blah

chgState("colorlist")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM