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

前端 未结 7 1716
逝去的感伤
逝去的感伤 2021-01-03 22:04

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

相关标签:
7条回答
  • Add it as a key to the object's internal dictionary __dict__

    my_object.__dict__['newattribute'] = 'attributevalue'
    
    0 讨论(0)
  • 2021-01-03 22:45

    Just set it.

    my_object = MyObject()
    my_object.my_custom_attribute = 'my_value'
    
    0 讨论(0)
  • 2021-01-03 22:52

    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')

    0 讨论(0)
  • 2021-01-03 23:00

    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)
    
    0 讨论(0)
  • 2021-01-03 23:00

    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
    
    0 讨论(0)
  • 2021-01-03 23:04

    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')
    
    0 讨论(0)
提交回复
热议问题