dynamically adding some of one module's functions to another

Gabriel Rossetti gabriel.rossetti at arimaz.com
Tue Aug 26 16:41:10 CEST 2008

Hello everyone,

I'm trying to import some modules into another's namespace (network_utils)


import utils
import constants as main_const
from services import constants as srv_const
from plugins import constants as plg_const

# Import all the message creation functions
f = dict([ (f, eval("utils." + f)) for f in dir(utils) if 
f.startswith("create") ])
del utils

# Create a virgin namespace
class constants:
    An aggragation of L{constants},
    L{services.constants}, &

# Import all the constants into the new namespace
f = dict([ (f, eval("main_const." + f)) for f in dir(main_const) if 
f.isupper() ])
del main_const
f = dict([ (f, eval("srv_const." + f)) for f in dir(srv_const) if 
f.isupper() ])
del srv_const
f = dict([ (f, eval("plg_const." + f)) for f in dir(plg_const) if 
f.isupper() ])
del plg_const

now, if I import network_utils somewhere, and try to call 
network_utils.myFunction() I get :

 >>> import network_utils
 >>> network_utils.myFunction
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'module' object has no attribute 'myFunction'

but if I try to access the constants class:

 >>> from network_utils import constants
 >>> constants.NO_DATA_TYPE

it works, how come?

Thank you,

More information about the Python-list mailing list