Function to import module to namespace

Cédric Lucantis omer at no-log.org
Sun Jun 29 15:24:15 EDT 2008


Le Sunday 29 June 2008 21:08:36 bvdp, vous avez écrit :
> Is it possible to do this from a function: import a module and append
> the defs in that module to an existing module/namesapce.
>
> So, in my code I have something like:
>
> # main code
> import mods
>
> def loadmore(n):
>     import_module(n, mods)
>
> ....
> # end of main
>
> this will permit the addition of the the stuff in file 'n.py' to 'mods'.
>
> Assuming that foo1() is defined in newmod, I should now be able to do
> something like mods.foo1().
>

You can dynamically add objects to a module:

>>> import os
>>> os.foo = 'bar'
>>> os.foo
'bar'
>>> setattr(os, 'foo2', 'bar2')
>>> os.foo2
'bar2'

and for the loading part you can use the __import__ builtin or maybe execfile  
(see the 'built-in functions' chapter of the library reference for more about 
these).

-- 
Cédric Lucantis



More information about the Python-list mailing list