0

Python: use vars() function in a method

my goal is to make a string into a variable inside a function. normally, i can do something like this: vars()["my_var"] = 10 print(my_var) # 10 but its become an error if i do it inside a method: def func(): vars()["my_var"] = 10 print(my_var) #error. my_var is not defined any help please?

3rd Mar 2018, 9:54 AM
Kevin AS
Kevin AS - avatar
2 Answers
+ 2
Well, dynamic variables is not a good idea, since it makes you work with a namespace you have to use special access to. It means, that if you make a "low level" assign to a variable, you have to access it the same way. def func(): vars()['my_var'] = 10 print(vars()['my_var']) func() will do the trick, but it is still a bad idea. Note: vars() without an argument is equivalent to locals(), so mind the scope.
3rd Mar 2018, 10:24 AM
strawdog
strawdog - avatar
+ 2
thanks for your help!đŸ€—đŸ€—đŸ€—
3rd Mar 2018, 10:37 AM
Kevin AS
Kevin AS - avatar