tags:

views:

35

answers:

2

Can a python module hand over other module in case of self being imported?

A: 
import other_module
for name in dir(other_module):
    globals()[name] = getattr(other_module, name)
del other_module
BG
This will break if other_module has an attribute called other_module. You can add a special case for that if you need to.
BG
+1  A: 

You can sort of do it (in the normal CPython anyway):

# uglyhack.py

import sys
import othermodule

sys.__modules__[__name__]= othermodule

then:

>>> import uglyhack
>>> uglyhack
<module 'othermodule' from '...'>

This relies on the assignment of the global for the module in the importing script/module happening after the body of imported module has finished executing, so by the time the import assignment happens, the sys.modules lookup has been sabotaged to point at another module.

I wouldn't use this in proper code for anything other than (maybe) debugging. There should almost always be a better way for whatever it is you're up to.

bobince