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

試著忘記壹切 提交于 2019-11-28 03:30:41
import sys
current_module = sys.modules[__name__]

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.

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

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.

You can pass it in from outside:

mymod.init(mymod)

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!