gpt4 book ai didi

python - 导入带有上下文的模块

转载 作者:行者123 更新时间:2023-12-01 06:15:37 24 4
gpt4 key购买 nike

我有一个名为 module.py 的模块,它检查上下文中的全局变量。

module.py:
----------

if 'FOO' in globals():
print 'FOO in globals'
else:
print 'nah'


in python shell:
----------------

In [1]: FOO = True

In [2]: import module
nah

如何导入具有现有上下文的模块?

最佳答案

这是相当 hackish 的——不要在生产代码中依赖它,因为并非所有 Python 实现都有 inspect.getouterframes 函数。但是,这在 CPython 中有效:

import inspect
record=inspect.getouterframes(inspect.currentframe())[1]
frame=record[0]

if 'FOO' in frame.f_globals:
print 'FOO in globals'
else:
print 'nah'

% python
>>> import test
nah
>>>

% python
>>> FOO=True
>>> import test
FOO in globals
>>>

关于python - 导入带有上下文的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3479934/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com