Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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

like image 938
Yaroslav Bulatov Avatar asked Mar 09 '26 13:03

Yaroslav Bulatov


1 Answers

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()
like image 148
warownia1 Avatar answered Mar 11 '26 03:03

warownia1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!