Re: Function to import module to namespace



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
.



Relevant Pages

  • Re: Function to import module to namespace
    ... Terry Reedy wrote: ... bvdp wrote: ... the defs in that module to an existing module/namesapce. ... import_module(n, mods) ...
    (comp.lang.python)
  • Re: Function to import module to namespace
    ... bvdp wrote: ... the defs in that module to an existing module/namesapce. ... import_module(n, mods) ...
    (comp.lang.python)
  • Function to import module to namespace
    ... Is it possible to do this from a function: import a module and append the defs in that module to an existing module/namesapce. ... import_module(n, mods) ... Assuming that foo1is defined in newmod, I should now be able to do something like mods.foo1. ...
    (comp.lang.python)