Importing a file into another module's namespace

Gary Oberbrunner garyo at genarts.com
Tue Apr 28 18:26:22 EDT 2009


----- "Steven D'Aprano" <steven at REMOVE.THIS.cybersource.com.au> wrote:

> On Mon, 27 Apr 2009 21:46:13 -0400, Gary Oberbrunner wrote:
> 
> > ...Now after importing foo.bar, I'd like to load
> > another file of code (say xyz.py), but *into* foo.bar's namespace. 
...
> 
> import foo.bar
> import xyz
> for name in dir(xyz):
>     if not name.starts_with('_'):
>         setattr(foo.bar, name, getattr(xyz, name))
> del xyz

Hi Steven (and MRAB), thanks for this idea.  This looks pretty straightforward and useful.  I also heard of another way via googling around; see what you think of this.  For example's sake this code just adds stuff to the os.path module (but I could pick any module not under my control).  For fun I have the code in a string rather than a file, but I think it works either way.

import sys
import os.path
 
f='''
def Foo(x):
  print "%s: Foo!"%x
Bar=123
'''

# now the magic two lines:
m=sys.modules['os.path']
exec f in m.__dict__ 

# test:
os.path.Foo("Gary")
print os.path.Bar

==== cut =================

What do you think?  Better or worse than looping over dir()?  Probably faster and less memory, certainly shorter, but on the other hand a lot more opaque (at least to me).

Comments welcome!

-- 
. . . . . . . . . . . . . . . . . . . . . . . . .
Gary Oberbrunner                garyo at genarts.com
GenArts, Inc.                   Tel: 617-492-2888
955 Mass. Ave                   Fax: 617-492-2852
Cambridge, MA 02139 USA         www.genarts.com 



More information about the Python-list mailing list