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?
Your suggested approach
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: