How to import a module so that the current globals are available to the module?

Dave Angel davea at ieee.org
Fri Apr 10 00:22:09 EDT 2009


mrstevegross wrote:
> I'm trying to import a module so that the globals() of the importer
> module are available to the imported module itself. Consider the
> following scenario:
>
> === mymod.py ===
> def go():
>   some_special_function(1,2)
>   # 'some_special_function' is a built-in function available in the
> scope of foo.py (see below)
>
> === foo.py ===
> some_special_function(3,4) # 'some_special_function' is a built-in
> function
> import mymod
> mymod.go()
> === EOF ===
>
> The problem is this: in foo.py, you can call 'some_special_function'
> all you want, because it's builtin. You can even 'print globals()' to
> verify that it is available.
>
> However, when mymod.py tries to invoke 'some_special_function', it
> fails because the function is NOT available in that scope.
>
> So, the question is: how can I make builtin functions available in the
> test.py scope available to the mymod.py scope?
>
> One awkward solution is to deliberately initialize mymod.py ilke so:
>
> === mymod.py ===
> globs=None
> def initialize(globs_): globs = globs_
> def go():
>   globs['some_special_function'] (1,2)
>
> === foo.py ===
> some_special_function(3,4) # 'some_special_function' is a built-in
> function
> import mymod
> mymod.initialize(globals())
> mymod.go()
> === EOF ===
>
> That will work, but it's a bit ugly. Plus, I have to repeat it for
> every module with the same problem (of which I have many!).
>
> Is there a way to use __import__ to make this work? Any ideas?
>
> Thanks,
> --Steve
>
>   
Your sample is very hard to follow, because you're mis-using the word 
built-in.  Built-ins are part of the Python implementation, and 
available everywhere, while you apparently just mean a function visible 
in foo.py, which may have been imported from somewhere else.

One solution would be that after importing mymod, you assign to its 
global space, as follows:

def some_special_function():
      .....
import mymod
mymod.some_special_function = some_special_function


You're adding a global name to the mymod namespace, and giving it a 
reference to a function in your own space.
Note that the two names don't have to be the same in the two files.  You 
could use, for example:
    import os
    mymod.some_special_function = os.path.join





More information about the Python-list mailing list