Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you reference a module?

If you are providing an in-text reference to an online module text, you will need to provide the year of module start, instead of the year of publication. For example: Author (year of module start), or (Author, year of module start). comma) • The module code, block number and title (in italics).

How do you reference a module in Python?

You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.

Can you have a module within a module Python?

Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).

What is __ import __ in Python?

__import__() Parameters name - the name of the module you want to import. globals and locals - determines how to interpret name. fromlist - objects or submodules that should be imported by name. level - specifies whether to use absolute or relative imports.


import sys
current_module = sys.modules[__name__]

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.


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


You can pass it in from outside:

mymod.init(mymod)

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


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