Calling the globals() function inside an arbitary imported function?

时间:2019-04-17 02:11:29

标签: python global-variables local python-module global-scope

I am trying to call globals() inside a function imported from another file, to retrieve the globally defined values of the program.

However, the dictionary it gives is different from the dictionary when called outside of the function.

I know this is meant to happen since here it says:

The globals table dictionary is the dictionary of the current module (inside a function, this is a module where it is defined, not the module where it is called).

But is there any trick, or another function, which makes globals() behave as if it were called in __main__?

This problem can be recreated easily. For example, in foo.py put:

def get_globals():
    return globals()

Then in the main program:

from foo import get_globals()

main_globals = globals()

foo_globals = get_globals()

main_globals == foo_globals
Out [1]: False

However, is there any way to get this last line to read:

main_globals == foo_globals
Out [2]: True

Thank you in advance for the help :)

1 个答案:

答案 0 :(得分:1)

可能会引起争议,但是您就可以了。

import inspect

def fun(): #some function in another module
    caller_globals = inspect.stack()[1][0].f_globals
    #do what you want 

基于Getting a variable from the caller's globals. What is a frame object?