Importing a file into another module's namespace

MRAB google at
Tue Apr 28 04:23:03 CEST 2009

Gary Oberbrunner wrote:
> Hi; my first time posting here.  I have a somewhat tricky problem I'd
> like some help with.
> I have a module,, that defines a number of functions and
> variables as usual.  Now after importing, I'd like to load
> another file of code (say, but *into*'s namespace.  So
> if 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
> m=sys.modules[""] # or something like that
> load_module_into_namespace("", m)
> print
> As you can see it's the middle two lines that have me stumped.  Anyone
> have any ideas?  Oh yes, this needs to work in python 2.2 or so (earlier
> is even better).
> Here's a tantalizing snippet from the Python "import" doc:
> "...If a file is found, it is parsed, yielding an executable code block.
> If a syntax error occurs, SyntaxError is raised. Otherwise, an empty
> module of the given name is created and inserted in the module table,
> and then the code block is executed in the context of this module."
> That's kind of what I want to do, except get an existing module and then
> execute my file's code block in the context of that module, I
> think.  Any help would be much appreciated!
How about:

import xyz
for x in dir(xyz):
     if not x.startswith("__"):
         setattr(, x, getattr(xyz, x))

More information about the Python-list mailing list