Visibility of global variables in imported modules

前端 未结 8 1932
梦毁少年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 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
    

提交回复
热议问题