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

Viewed 74423

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?

7 Answers

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

You can pass it in from outside:

mymod.init(mymod)

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

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

Related