Importing module with context
I have a module named module.py, which checks a global variable in开发者_StackOverflow context.
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
how can I import modules with existing context?
This is rather hackish -- don't rely on this for production code since not all implementations of Python have a inspect.getouterframes
function. However, this works in 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
>>>
Calling globals
in module.py
will yield the global variables in the module's scope. I assume you want it to look at the globals in the scope of the interpreter? The short answer is that you can't do that, and you shouldn't want to. If it needs an option, set that option deliberately, but don't refer to a magic global.
If you must, you can pass the interpreter's globals with
modules.update_config( globals( ) )
精彩评论