How can I add attributes to a module at run time?

Thanks @Dharmesh. That was what I needed. There is only one change that needs to be made. The module won't be importing itself so to get the module object I can do:

setattr(sys.modules[__name__], 'attr1', 'attr1')


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

If you don't know the attribute name until runtime, use setattr:

>>> import mymodule
>>> setattr(mymodule, 'point', (1.0, 4.0))
>>> mymodule.point
(1.0, 4.0)

Tags:

Python