Importing a file into another module's namespace
garyo at genarts.com
Wed Apr 29 00:26:22 CEST 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.
print "%s: Foo!"%x
# now the magic two lines:
exec f in m.__dict__
==== 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).
. . . . . . . . . . . . . . . . . . . . . . . . .
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