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

前端 未结 6 917
梦毁少年i
梦毁少年i 2020-12-07 11:55

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条回答
  • 2020-12-07 12:17
    import sys
    current_module = sys.modules[__name__]
    
    0 讨论(0)
  • 2020-12-07 12:28

    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.

    0 讨论(0)
  • 2020-12-07 12:34

    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

    0 讨论(0)
  • 2020-12-07 12:35

    You can pass it in from outside:

    mymod.init(mymod)
    

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

    0 讨论(0)
  • 2020-12-07 12:37

    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

    0 讨论(0)
  • 2020-12-07 12:41

    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.

    0 讨论(0)
提交回复
热议问题