Reason for globals() in Python?

前端 未结 8 848
北荒
北荒 2020-12-12 12:43

What is the reason of having globals() function in Python? It only returns dictionary of global variables, which are already global, so they can be used anywhere... I\'m ask

相关标签:
8条回答
  • 2020-12-12 13:10

    Not really. Global variables Python really has are module-scoped variables.

    # a.py
    print(globals())
    
    import b
    b.tt()
    
    # b.py
    def tt():
        print(globals())
    

    run python a.py, at least two output of globals()['__name__'] is different.

    Code here in cpython on Github shows it.

    0 讨论(0)
  • 2020-12-12 13:18

    It might be useful if you like to import module you just have built:

    a.py

    [...]
    
    def buildModule():
        [...code to build module...]
        return __import__("somemodule")
    
    [...]
    

    b.py

    from a import buildModule
    
    def setup():
       globals()["somemodule"] = buildModule()
    
    0 讨论(0)
提交回复
热议问题