views:

30

answers:

2

I have a module named module.py, which checks a global variable in 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?

A: 

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( ) )
katrielalex
+1  A: 

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
>>> 
unutbu
+1 for sheer ickiness!
katrielalex
this shouldn't be needed and isn't recommended.
Gabi Purcaru