如何访问父模块的Globals()到子模块? [英] How to access Globals() of parent module into a sub-module?
问题描述
我在子模块中有一个函数需要操作来自父/解释器Globals(断言,验证)的变量,如下所示:
import mymodule
mymodule.fun_using_main_interpreter_globals1()
如果我这样做,它有效:
mymodule.fun_using_main_interpreter_globals1(explicit_pass = globals())
但是,如果我不通过explictely globals(),我怎样才能访问解释器/父globals()进入我的子模块?
在IPython中,它可以放在配置文件设置中。
caller_globals = dict(inspect.getmembers(inspect.stack()[1] [0]))[f_globals]
inspect
module允许您访问python解释器堆栈等。第二个元素(使用 [1]
访问)是调用者,堆栈帧是元组的第一个元素(使用 [0] <访问/ code>)它包含该上下文的当前全局字典的成员(名为
f_globals
)。
<请注意,这会返回调用者的
globals()
,而不是被调用函数是子模块的模块之一。我认为这是不可能的,因为相同的模块可以是不同模块的子模块(子模块只是模块中的全局模块,并且不同模块可能共享相同的子模块对象)。 I have a function in a sub-module which needs to manipulate the variables from parent/interpreter Globals (assertion, validation) like this:
import mymodule
mymodule.fun_using_main_interpreter_globals1()
If I do this, it works:
mymodule.fun_using_main_interpreter_globals1(explicit_pass= globals() )
But, If I dont pass explictely globals(), how can I get access to interpreter/parent globals() into my sub-module ?
In IPython, it can be put in profile settings.
I never went for real in this territory, but looking at the documentation this should do it:
caller_globals = dict(inspect.getmembers(inspect.stack()[1][0]))["f_globals"]
inspect
module allows you to access, among other things, the python interpreter stack. The second element (accessed with [1]
) is the caller, the stack frame is the first element of the tuple (accessed with [0]
) and it contains as member the current global dictionary for that context (named f_globals
).
Note that this returns the globals()
of the caller, not the one of the module of which the called function is a sub-module. That in general I think is not possible because the same module can be a sub-module of different modules (a sub-module is just a global in a module and it's possible that different modules share the same sub-module object).
这篇关于如何访问父模块的Globals()到子模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!