Yaroslav Bulatov Yaroslav Bulatov - 3 months ago 10
Python Question

How to set sys.modules["m"]=<current module>

I have this structure:

merged.py:
everything

main.py:
import merged
sys.modules['othermodule'] = merged
othermodule.f()


If I merged this into single file
main.py
, is there any way to tell
othermodule
resolve to
main
while inside of
main.py
?

This situation happens when using amalgamate package to concat everything into single file, but the result is two files with structure like above, and I'm trying to get it down to one file

Answer
sys.modules['othermodule'] = sys.modules[__name__]

Gets the current module you are in and sets as othermodule. Now you can:

import othermodule
othermodule.f()

If you prefer to assign module to variable you can simply:

othermodule = sys.modules[__name__]
othermodule.f()