If I wanted to get the current module, e.g. to reload it, I would do:
import sys
sys.modules[__name__]
Is there a better way to do this (e.g. not involving __name__
)? Better in this context means more idiomatic, more portable, more robust, or more...any of the other things we usually desire in our software.
I use python 2, but answers for python 3 will no doubt be useful to others.
There is no more idiomatic method to get the current module object from sys.modules
than what you used.
__name__
is set by Python on import, essentially doing:
module_object = import_py_file(import_name)
module_object.__name__ = import_name
sys.modules[import_name] = module_object
so the __name__
reference is exactly what you want to use here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With