Reputation: 4806
Can a python module hand over other module in case of self being imported?
Upvotes: 2
Views: 492
Reputation: 536567
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.
Upvotes: 2
Reputation: 1
import other_module
for name in dir(other_module):
globals()[name] = getattr(other_module, name)
del other_module
Upvotes: 0