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?
178
votes
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
26
votes
16
votes
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
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