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

前端 未结 7 1717
逝去的感伤
逝去的感伤 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条回答
  • 2021-01-03 23:05

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