Mar-03-2022, 05:24 AM
(This post was last modified: Mar-03-2022, 05:24 AM by deanhystad.)
If you have an object you can set attributes for the object
I cannot fathom why you would ever want to do this. A variable is a convenient name you can use to access an object. Dynamically created names are not going to be convenient.
import junk for name, value in zip('abc', (1, 2, 3)): setattr(junk, name, value) print(junk.a, junk.b, junk.c)
Output:1 2 3
What I don't know is how to get the module for the file you are in. I suppose you could use locals() or globals().globals()['a'] = "I am a global a" locals()['b'] = "I am a global b" def func(): locals()['b'] = "I am local b" locals()['c'] = "I am local c" print(a) print(b) print(c) print(a) print(b) func()
Output:I am a global a
I am a global b
I am a global a
I am a global b
Traceback (most recent call last):
File "...", line 14, in <module>
func()
File "...", line 9, in func
print(c)
NameError: name 'c' is not defined
Looks like locals() doesn't create variables in the local scope of the function. Not surprising.I cannot fathom why you would ever want to do this. A variable is a convenient name you can use to access an object. Dynamically created names are not going to be convenient.