What is the pythonic way to setattr() for a module?
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
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)
精彩评论