First of all: what we call the global area in Python is actually a โmodularโ area (on the other hand, it reduces the โevilโ from using global vars).
Then, to dynamically create a global var, although I still can't figure out why this is better than using a module level dictionary, just do:
globals()[variable] = value
This creates a variable in the current module. If you need to create a modular variable in the module from which the method was called, you can look into the global dictionary from the callerโs frame using:
from inspect import currentframe currentframe(1).f_globals[variable] = name
Now this seems completely useless, since you can create a variable with a dynamic name, but you cannot access it dynamically (unless you use the global dictionary again)
Even in your test case, you create the variable "abc" by passing the string method, but then you need to access it using the hard code "abc" - the language itself is designed to prevent this (from here is the Javascript difference, where the array indices and object attributes are interchangeably, while in Python you have distinc matching objects)
My suggestion is that you use an explicit module level dictionary and create all your dynamic variables as key / value pairs:
names = {} class Test(object): def __init__(self): self.dict = {}
(on the side of the note, in Pyhton 2 your classes always inherit from the "object")
source share