I have a need to add module attributes at run time. For example, when a module is loaded, it reads the file where the data is contained. I would like that data to be avail
A module attribute is a variable in the module global scope.
if you want to set an attribute from the module itself 'at runtime' the correct way is
globals()['name'] = value
(Note: this approach only works for globals, not for locals.)
if you want to set an attribute from the scope where the module has been imported just set it:
import myModule
setattr(myModule, 'name', 10)
Complete example:
#m.py
def setGlobal(name, value):
globals()[name] = value
--
#main.py
import m
m.setGlobal('foo', 10)
print(m.foo) #--> 10
#Moreover:
from m import foo
print(foo) #--> 10 (as Expected)
m.setGlobal('foo', 20)
print(m.foo) #--> 20 (also as expected)
#But:
print(foo) #--> 10