I want to get variables for work in function from dict.
Simple example
>>> def func(atrs):
... for k,v in atrs.items():
... exec(k '=v')
...
... # do smth here with vars
...
... print(locals()) # lets see that 'a' exists
... print(a) # lets use 'a'
And after I use this func I get the error.
>>> func({'a':1, 'b':5})
{'atrs': {'a': 1, 'b': 5}, 'k': 'b', 'v': 5, 'a': 1, 'b': 5}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in func
NameError: name 'a' is not defined
But we can see that 'a' exists in defined variables. What I doing wrong?
I see this and it works if we dont use functions. Convert dictionary entries into variables
But I need use functions.
CodePudding user response:
I strongly discouraged you to use this kind of method but you can use locals() (or vars()) to create variables dynamically:
def func(attrs):
for k, v in attrs.items():
locals()[k] = v
print(locals())
print(a)
print(b)
func({'a':1, 'b':5})
Output:
{'attrs': {'a': 1, 'b': 5}, 'k': 'b', 'v': 5, 'a': 1, 'b': 5}
1
5
If you want this variables exist out of the scope of func function, replace locals() or vars() by globals().
CodePudding user response:
Ok, I dont understand why, but it works if we define this vars like globals, not locals.
def func(attrs):
for k, v in attrs.items():
globals()[k] = v
# or we can use this instead of 'for' loop
# globals().update(attrs)
print(locals())
print(globals())
print(a)
print(b)
func({'a':1, 'b':5})
Output
{'attrs': {'a': 1, 'b': 5}, 'k': 'b', 'v': 5}
{'__name__': '__main__', ..., 'a': 1, 'b': 5}
1
5
