2

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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?
0
import other_module
for name in dir(other_module):
    globals()[name] = getattr(other_module, name)
del other_module

1 Comment

This will break if other_module has an attribute called other_module. You can add a special case for that if you need to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.