How to get a reference to a module inside the module itself?
import sys
current_module = sys.modules[__name__]
If you have a class in that module, then the __module__
property of the class is the module name of the class. Thus you can access the module via sys.modules[klass.__module__]
. This is also works for functions.
One more technique, which doesn't import the sys module, and arguably - depends on your taste - simpler:
current_module = __import__(__name__)
Be aware there is no import. Python imports each module only once.