How to get a reference to a module inside the module itself?

PythonSelf Reference

Python Problem Overview


How can I get a reference to a module from within that module? Also, how can I get a reference to the package containing that module?

Python Solutions


Solution 1 - Python

import sys
current_module = sys.modules[__name__]

Solution 2 - Python

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.

Solution 3 - Python

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.

Solution 4 - Python

You can get the name of the current module using __name__

The module reference can be found in the sys.modules dictionary.

See the Python documentation

Solution 5 - Python

You can pass it in from outside:

mymod.init(mymod)

Not ideal but it works for my current use-case.

Solution 6 - Python

According to @truppo's answer and this answer (and PEP366):

Reference to "this" module:

import sys
this_mod = sys.modules[__name__]

Reference to "this" package:

import sys
this_pkg = sys.modules[__package__]

> __package__ and __name__ are the same if from a (top) __init__.py

Solution 7 - Python

If all you need is to get access to module variable then use globals()['bzz'] (or vars()['bzz'] if it's module level).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRam RachumView Question on Stackoverflow
Solution 1 - PythonmthurlinView Answer on Stackoverflow
Solution 2 - PythonUriView Answer on Stackoverflow
Solution 3 - PythonMichaelView Answer on Stackoverflow
Solution 4 - PythonpkitView Answer on Stackoverflow
Solution 5 - PythonSam WatkinsView Answer on Stackoverflow
Solution 6 - PythonBrandtView Answer on Stackoverflow
Solution 7 - PythonKaroliusView Answer on Stackoverflow