Can a python module hand over other module in case of self being imported?
2 Answers
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.
1 Comment
Michael Herrmann
Shouldn't the
sys.__modules__ in the first code snippet be sys.modules? Or is that for some Python version older than 2.6.6?import other_module
for name in dir(other_module):
globals()[name] = getattr(other_module, name)
del other_module
1 Comment
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.