views:

75

answers:

1

In a class method, I can add attributes using the built-in function:

setattr(self, "var_name", value).  

If I want to do the same thing within a module, I can do something like:

globals()["var_name"] = value

Is this the best way to do this, or is there a more pythonic solution?

+5  A: 

Your suggested approach

globals()["var_name"] = value

is indeed the most Pythonic way. In particular, it's significantly more Pythonic than using eval, which would be your main (though not only) alternative.

However, if you still want to use setattr, you may do so by using sys.modules to get a reference to the current module object with the current module's __name__ variable (explained here) as follows:

import sys
setattr(sys.modules[__name__], "var_name", value)
Eli Courtwright