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
Add it as a key to the object's internal dictionary __dict__
my_object.__dict__['newattribute'] = 'attributevalue'
Just set it.
my_object = MyObject()
my_object.my_custom_attribute = 'my_value'
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')
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)
The global scope of a module is the module itself, so just set a global.
# module.py
a = 1
# script.py
import module
print module.a
# 1
Create dynamic class 'Module' and add attributes dynamically using dictionary like :
attributes = {'attr1': 'attr1', 'attr2': 'attr2'}
module = type('Module', (), attributes)
OR Create only dynamic class 'Module'
module = type('Module', (), {})
and add attribute with setattr method like this:
setattr(module, 'attr3', 'attr3')
OR
import module
setattr(module, 'attr1', 'attr1')