178
votes

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?

6
I suspect you might be asking this question because you have a variable in module scope (e.g., BLAH=10 outside a function or class), then a class/function variable named BLAH, and you want to differentiate. A valid question here is: Is this necessary? Scope rules are notoriously prone to mistake, especially by the 'idiot' who picks up your code after you (i.e., you, 6 months later). Tricks like this are rarely necessary; I attempt to avoid them completely because they're so often confusing and wrongly modified later. - Kevin J. Rice
@KevinJ.Rice "the 'idiot' who picks up your code after you (i.e., you, 6 months later)" made my day! - Arctelix
Who cares why he is asking the question? There are plenty of valid reasons to need to do this. - Christopher Barber
@Christopher: Although the need doesn't often arise, here's a case in point. - martineau

6 Answers

232
votes
import sys
current_module = sys.modules[__name__]
26
votes

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.

16
votes

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.

13
votes

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

3
votes

You can pass it in from outside:

mymod.init(mymod)

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

1
votes

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