proxy-like python module
Can a python module hand over other module in c开发者_StackOverflowase of self being imported?
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.
import other_module
for name in dir(other_module):
globals()[name] = getattr(other_module, name)
del other_module
精彩评论