Visibility of global variables in imported modules

前端 未结 8 1707
梦毁少年i
梦毁少年i 2020-11-22 11:22

I\'ve run into a bit of a wall importing modules in a Python script. I\'ll do my best to describe the error, why I run into it, and why I\'m tying this particular approach t

相关标签:
8条回答
  • 2020-11-22 12:04

    Since globals are module specific, you can add the following function to all imported modules, and then use it to:

    • Add singular variables (in dictionary format) as globals for those
    • Transfer your main module globals to it .

    addglobals = lambda x: globals().update(x)

    Then all you need to pass on current globals is:

    import module

    module.addglobals(globals())

    0 讨论(0)
  • 2020-11-22 12:04

    Since I haven't seen it in the answers above, I thought I would add my simple workaround, which is just to add a global_dict argument to the function requiring the calling module's globals, and then pass the dict into the function when calling; e.g:

    # external_module
    def imported_function(global_dict=None):
        print(global_dict["a"])
    
    
    # calling_module
    a = 12
    from external_module import imported_function
    imported_function(global_dict=globals())
    
    >>> 12
    
    0 讨论(0)
提交回复
热议问题