Python
programming
module reference
coding tips
software development

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

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In Python, a module can get a reference to its own module object through sys.modules[__name__]. That works because Python stores every imported module in sys.modules, keyed by its import name. Most of the time you do not need the module object explicitly, but it becomes useful for reflection, dynamic registration, or code that wants to modify module-level attributes programmatically.

The Direct Answer

Inside a module, the standard pattern is:

python
1import sys
2
3current_module = sys.modules[__name__]
4print(current_module)

__name__ is the current module’s name, and sys.modules is the interpreter’s registry of already loaded modules. Looking up the current name returns the module object itself.

Why This Works

When Python imports a module, it creates a module object and stores it in sys.modules. Future imports of the same module reuse that object instead of creating a fresh one.

That means a module does not need some magical special variable called self. The module object is already registered globally, and __name__ tells you which entry belongs to the currently executing module.

A Practical Example

Suppose a module wants to register functions dynamically by name.

python
1import sys
2
3
4def hello():
5    return "hello"
6
7
8def goodbye():
9    return "goodbye"
10
11
12module = sys.modules[__name__]
13registry = {
14    name: getattr(module, name)
15    for name in ["hello", "goodbye"]
16}
17
18print(registry["hello"]())

This is not something you should do everywhere, but it shows why the module reference can be useful for introspection.

globals() Versus the Module Object

Sometimes people ask for the module object when what they really need is access to module-level names. In simple cases, globals() is enough.

python
print(globals()["__name__"])

The difference is that globals() gives you the namespace dictionary, while sys.modules[__name__] gives you the actual module object. If you need attributes, metadata, or a value you can pass around as a module, use the module object.

Another Option: importlib.import_module

You can also do this:

python
1import importlib
2
3module = importlib.import_module(__name__)
4print(module)

This works, but inside the module itself it is more indirect than sys.modules[__name__]. Since the module is already loaded, going straight to sys.modules is clearer.

When You Probably Should Not Do This

If the only goal is to call a module-level function or read a module-level constant, you usually do not need a self-reference at all. Just use the names directly.

python
VERSION = "1.0"

print(VERSION)

Requesting a module reference for ordinary local code can be a sign that the design is becoming too dynamic for its own good. Reflection is useful, but unnecessary indirection makes code harder to read.

Special Case: __main__

One subtle point is that __name__ becomes "__main__" when a file is executed as the main script. In that case, sys.modules[__name__] still works, but the key is "__main__", not the package import path.

That matters if the same code can run both as an imported module and as a script. The module object exists in both cases, but the name used to look it up may differ.

Common Pitfalls

The biggest pitfall is overengineering. Many uses of a self-module reference can be replaced with direct function calls, constants, or explicit registries.

Another mistake is confusing globals() with the module object. globals() gives a dictionary, which is not always the same thing operationally as passing around a module reference.

Developers also get tripped up by __main__. If code assumes the module will always be registered under its package name, running the file directly may break that assumption.

Finally, do not mutate module state dynamically unless you have a clear reason. It can make imports order-dependent and much harder to debug.

Summary

  • The standard way for a Python module to reference itself is sys.modules[__name__].
  • This works because Python stores loaded module objects in sys.modules.
  • Use the module object only when you need reflection or dynamic attribute access.
  • 'globals() exposes the namespace dictionary, but it is not the same thing as the module object.'
  • Be careful when the file runs as __main__, because the module name differs from the normal import path.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.