Function to import module to namespace

John Machin sjmachin at lexicon.net
Sun Jun 29 20:18:02 EDT 2008


On Jun 30, 9:52 am, bvdp <b... at mellowood.ca> wrote:
> Terry Reedy wrote:
>
>  >
>
>    <snip>
>
>  >
>  > Do you mean something like this?
>
>   <snip>
>
>  >  >>> math.__dict__.update(string.__dict__)
>  >  >>> dir(math)
>  > ['Formatter', 'Template', '_TemplateMetaclass', '__builtins__',
>
>   <snip>
>
> I think this is working.... First off, 2 module files:
>
> funcs.py
> def func1():
>      print "I'm func1 in funcs.py"
>
> more.py
> def func2():
>      print "I'm func2 in 'more.py'"
>
> and my wonderful main program:
>
> xx.py
> import funcs
> def addnewfuncs(p):
>      x = __import__(p)
>      funcs.__dict__.update(x.__dict__)
> funcs.func1()
> addnewfuncs('more')
> funcs.func2()
>
> The first problem I had was getting import to accept a variable. It
> doesn't seem to, so I used __import__(). Then, I had to remember to
> assign this to a variable ... and then it appears to work just fine.
>
> Did I miss anything in this???

You are updating with *everything* in the 'more' module, not just the
functions. This includes such things as __name__, __doc__, __file__.
Could have interesting side-effects.

One quick silly question: why do you want to do this anyway?

Sorry, *two* quick silly questions: are the add-on modules under your
control, or do you want to be able to do this with arbitrary modules?
[If under your control, you could insist that such modules had an
__all__ attribute with appropriate contents]

A third: why do you want to import into an existing namespace? Now
that you know about __import__, why just not call the functions where
they are?

Cheers,
John



More information about the Python-list mailing list