'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.
Solution 1:[1]
@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")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
