Importing a file into another module's namespace

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Apr 28 00:02:23 EDT 2009


On Mon, 27 Apr 2009 21:46:13 -0400, Gary Oberbrunner wrote:

> I have a module, foo.bar, that defines a number of functions and
> variables as usual.  Now after importing foo.bar, I'd like to load
> another file of code (say xyz.py), but *into* foo.bar's namespace.  So
> if xyz.py contains:
> 
> def XYZ(arg):
>   print "Aargh! ", arg
> ABC="abc"
> 
> then I'd like to be able to do this in my main python file:
> 
> import foo.bar
> m=sys.modules["foo.bar"] # or something like that
> load_module_into_namespace("xyz.py", m)
> foo.bar.XYZ("whatever")
> print foo.bar.ABC


import foo.bar
import xyz
foo.bar.XYZ = xyz.XYZ
foo.bar.ABC = xyz.ABC
del xyz

That gets a tad tedious if module xyz has many objects, so you can do 
this:


# (untested)
import foo.bar
import xyz
for name in dir(xyz):
    if not name.starts_with('_'):
        setattr(foo.bar, name, getattr(xyz, name))
del xyz


But perhaps the easiest thing to do is, if you control foo.bar, to just 
add a line to it:

"from xyz import *"

But I suppose if you controlled foo.bar you would have already done that.


-- 
Steven



More information about the Python-list mailing list