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)

network_utils.py:

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") ])
__builtins__.update(f)
del utils

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

#
# Import all the constants into the new namespace
#
f = dict([ (f, eval("main_const." + f)) for f in dir(main_const) if 
f.isupper() ])
constants.__dict__.update(f)
del main_const
f = dict([ (f, eval("srv_const." + f)) for f in dir(srv_const) if 
f.isupper() ])
constants.__dict__.update(f)
del srv_const
f = dict([ (f, eval("plg_const." + f)) for f in dir(plg_const) if 
f.isupper() ])
constants.__dict__.update(f)
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
'none'

it works, how come?

Thank you,
Gabriel




More information about the Python-list mailing list