Random Tech Thoughts

The title above is not random

Get the Current Module in Python

It’s sometimes useful to do introspection on the module itself you are writing. But python doesn’t provide any direct way to support this. In fact a PEP about this feature has been rejected.

A little google find a solution to this problem. Here’s the code

1
2
3
4
5
6
7
import sys
# get the current module's name
modname = globals()['__name__']
# get the module
module = sys.modules[modname]
# or more simply as suggested by E.T
module = sys.modules[__name__]

Comments