Back to series
· 12 min read

Python Modules and the import Mechanism


I. What Is a Python Module

A module is the basic unit by which Python organizes code. A module usually corresponds to a .py file, which can define variables, functions, and classes, and can also contain executable statements.

Through the module mechanism, a large program can be split into multiple files with clear responsibilities, making the code more maintainable, reusable, and better organized.

1. Basic Structure of a Module

For example, create a file named math_utils.py:

PI = 3.1415926

def add(a, b):
    return a + b

def circle_area(radius):
    return PI * radius ** 2

class Calculator:
    def multiply(self, a, b):
        return a * b

This file is a Python module. It contains:

  • Module variable: PI
  • Module functions: add(), circle_area()
  • Module class: Calculator

Other Python files can import and use these objects through import.

2. Purpose of Modules

Modules mainly solve the following problems:

Purpose Description
Code reuse Multiple files can share the same function and class definitions
Namespace isolation Different modules can have variables and functions with the same names
Separation of responsibilities Organize code by business functionality
Dependency management Clarify the reference relationships between modules
Independent maintenance When a module is modified, reduce the impact on other modules

3. Relationship Between Modules and Files

In a typical Python project, a .py file usually corresponds to a module, but a module does not necessarily correspond only to an ordinary Python file.

Python also supports:

  • Built-in modules: provided by the Python interpreter, such as sys and os.
  • Standard library modules: provided with the Python installation, such as json and datetime.
  • Third-party modules: installed through package management tools, such as requests and numpy.
  • Extension modules: usually implemented in languages such as C and C++, and loaded through Python interfaces.
  • Namespace packages: can be composed of multiple directories and may not have __init__.py.

Note that a module is a runtime module object, while a .py file is only a common source of modules.

II. Python Module Namespaces

Each module has its own namespace. Variables, functions, and classes in a module are usually accessed through the module name.

For example:

# math_utils.py

PI = 3.1415926

def add(a, b):
    return a + b

Another file:

import math_utils

print(math_utils.PI)
print(math_utils.add(10, 20))

Here, math_utils is a module object, and PI and add are members of the module namespace.

1. Module Attributes

Python modules have several important built-in attributes:

Attribute Meaning
__name__ The name of the current module
__file__ The file path corresponding to the module; some modules may not have one
__package__ The name of the package to which the module belongs
__doc__ The module docstring
__spec__ Import specification information for the module
__loader__ The loader that loads the module
__path__ The search path of the package; ordinary modules usually do not have one

Example:

# example.py

"""This is an example module."""

print(__name__)
print(__file__)
print(__package__)
print(__doc__)

When this file is executed directly, it usually outputs:

__main__
/path/to/example.py

This is an example module.

Here, the value of __name__ depends on how the module is run.

2. Module Namespace and Dictionary

The global namespace of a module can be accessed through __dict__:

import math_utils

print(math_utils.__dict__.keys())

You can also use vars():

print(vars(math_utils))

A module's namespace is essentially a mapping structure used to store the bindings between module-level names and objects.

It is important to distinguish:

  • A name is an identifier for a variable, function, or class.
  • An object is the actual runtime entity referenced by a name.
  • A namespace stores the mapping between names and objects.

3. Basic Usage of import

import is Python's module import statement. It is responsible for finding the module, loading the module, initializing the module, and binding the module object into the current namespace.

1. import module

The most common import form:

import math

print(math.sqrt(16))
print(math.pi)

After the import, the name math is bound in the current namespace.

To access module members, use dot notation:

math.sqrt(16)

This makes it clear which module a member comes from and helps avoid name conflicts.

2. import module as alias

You can set an alias for a module with as:

import numpy as np

array = np.array([1, 2, 3])

print(array)

An alias only affects the name binding in the current namespace; it does not change the module's own name.

Common aliases include:

Original module Common alias
numpy np
pandas pd
matplotlib.pyplot plt
tensorflow tf
datetime Usually no alias is used

3. from module import name

You can import specific members directly from a module:

from math import sqrt, pi

print(sqrt(25))
print(pi)

In this case, sqrt and pi are bound directly in the current namespace and do not need to be accessed through math.

This form is suitable for importing a small number of specific members.

However, if an imported name conflicts with another name in the current scope, it may overwrite an existing binding.

For example:

from math import sqrt

def sqrt(value):
    return value

print(sqrt(16))

Here, the later-defined function rebinds the name sqrt, and the originally imported function is no longer accessible through this name.

4. from module import name as alias

You can set an alias for a module member:

from math import sqrt as square_root

print(square_root(36))

This is useful for:

  • Avoiding name conflicts.
  • Shortening long names.
  • Clearly distinguishing members with the same name from different modules.

5. from module import *

A star import binds the names in a module that meet the export rules to the current namespace:

from math import *

print(sqrt(16))
print(pi)

Pay special attention to its import rules:

  • If the module defines __all__, only the names listed in it are imported.
  • If __all__ is not defined, names that do not start with an underscore are usually imported.
  • A star import does not automatically import all internal names in the module.
  • Imported names may overwrite objects with the same name in the current namespace.

For example:

# geometry.py

__all__ = ["PI", "circle_area"]

PI = 3.1415926
DEBUG = True

def circle_area(radius):
    return PI * radius ** 2

def internal_helper():
    return "internal"

Run:

from geometry import *

print(PI)
print(circle_area(5))

# DEBUG and internal_helper will not be imported via star import

In real-world engineering, it is not recommended to frequently use from module import * in large projects, because it reduces code readability and increases the risk of name conflicts.

IV. The Execution Mechanism of import

Understanding import cannot stop at the syntax level. When Python imports a module, it executes a mechanism for lookup, loading, initialization, and caching.

1. The Overall Process of Module Import

When this is executed:

import math_utils

Python first checks whether the module already exists in the import cache. If it does not exist, it searches for the module, creates a module object, executes the module code, and caches it.

The overall process is as follows:

flowchart TD
    A["Execute the import statement"] --> B["Check sys.modules"]
    B --> C{"Is the module already cached?"}
    C -->|Yes| D["Get the existing module object"]
    C -->|No| E["Find the module spec"]
    E --> F{"Is the module found?"}
    F -->|No| G["Raise ModuleNotFoundError"]
    F -->|Yes| H["Create the module object"]
    H --> I["Put it into sys.modules"]
    I --> J["Execute the module code"]
    J --> K["Complete module initialization"]
    K --> L["Bind the imported name"]
    D --> L
    L --> M["Continue executing subsequent code"]
    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style G fill:#FBE9E9,stroke:#D9AAAA,color:#334155
    style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style I fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style K fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style L fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style M fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

This is a conceptual process. The actual import system also involves details such as import locks, module specs, loaders, and package initialization.

2. Module Lookup and Loading

Python's import system is mainly completed through the cooperation of the following mechanisms:

  • sys.meta_path: stores meta path finders, which participate in module lookup.
  • sys.path: the search path used by regular file system imports.
  • sys.path_hooks: used to create path import finders.
  • sys.path_importer_cache: caches the relationship between paths and path finders.
  • importlib: provides a programmatic interface to the module import system.

Module lookup usually first uses meta path finders to find the module spec, and then the corresponding loader creates and executes the module.

The module spec object is usually represented by ModuleSpec, and contains information such as the module name, loader, and source location.

3. Why Modules Must First Be Put into sys.modules

Before executing module code, Python usually first puts the newly created module object into sys.modules.

The main reason for doing this is to avoid infinitely creating the same module during circular imports, and also to let the import system recognize modules that are being initialized.

For example:

# a.py

print("Start importing a")

import b

value_a = "A"

print("Finished importing a")
# b.py

print("Start importing b")

import a

value_b = "B"

print("Finished importing b")

When a imports b, and b in turn imports a, the second import of a can find the module object that already exists in sys.modules.

However, this object may not yet have completed initialization, so some of its names may not exist yet.

This is one of the reasons circular imports are prone to errors.

V. sys.modules and Module Caching

sys.modules is a very important cache structure in Python's import system.

It is a dictionary that stores the mapping between module names and module objects.

1. Viewing the Module Cache

```python import sys import math print("math" in sys.modules) print(sys.modules["math"]) ``` You can use it to check whether a module has already been loaded.

2. Why repeated imports do not run again

For example:

# counter.py

print("counter module initialization")

count = 0

Main program:

import counter
import counter

print(counter.count)

Usually it prints only once:

counter module initialization
0

Because on the first import the module has already been loaded and cached. The second import reuses the existing module object instead of re-executing the module's top-level code.

Therefore, module-level initialization usually runs only once — on the first successful load within the same interpreter process.

3. The effect of modifying sys.modules

You can inspect or delete the module cache:

import sys
import counter

del sys.modules["counter"]

import counter

After deleting the cache, importing again may re-create and re-execute the module.

But note:

  • Deleting the cache does not automatically destroy the existing module object.
  • Other variables may still reference the old module object.
  • Re-importing may create a new module object.
  • The old object and the new object may coexist in the program.

Therefore, modifying sys.modules directly should be done with care and should not be used as a general module-reloading approach.

4. Module cache vs. reload

Python provides importlib.reload() to re-execute module code:

import importlib
import counter

importlib.reload(counter)

It is not the same as deleting the cache and importing again.

Aspect Re-importing after deleting the sys.modules cache importlib.reload
Module object Usually creates a new module object Usually reuses the original module object
Module code Re-executed Re-executed
Module dictionary The new object has its own new module dictionary Usually keeps the original dictionary and updates its definitions
External references May still point to the old object Still point to the original module object, but references to old members may persist
Typical use Special import testing Reloading modules in a development environment

reload() is not a complete state-reset mechanism:

  • Old names in the module dictionary that are not overwritten by the new code may persist.
  • Objects already imported via from module import name are not updated automatically.
  • Existing class instances do not automatically become instances of the new class.
  • External side effects produced by module initialization are not automatically undone.

In production environments, you should generally not rely on hot module reloading to manage program state.

VI. Python's module search path

When Python imports a module, it needs to know where to look for it.

The module search path is mainly influenced by sys.path, how the interpreter was started, the environment configuration, and the import system.

1. Inspecting sys.path

import sys

for path in sys.path:
    print(path)

sys.path is a list of strings containing the search locations used by the regular path-based import mechanism.

Common sources of these paths include:

  • The directory containing the current script, or the initial search directory determined by how the interpreter was started.
  • Directories specified by the PYTHONPATH environment variable.
  • The Python standard library directories.
  • Third-party package installation directories.
  • site-packages in a virtual environment.
  • Directories added through startup configuration or program code.

The exact contents are affected by the Python version, operating system, startup arguments, and environment configuration.

2. Priority of the module search path

In ordinary filesystem-based import scenarios, the order can be understood as follows:

flowchart TD
    A["Import module"] --> B["Check sys.modules"]
    B --> C{"Already cached?"}
    C -->|Yes| D["Reuse module directly"]
    C -->|No| E["Traverse sys.meta_path"]
    E --> F{"Module spec found?"}
    F -->|Yes| G["Use the corresponding loader"]
    F -->|No| H["Import fails"]
    G --> I["Execute module initialization"]
    I --> J["Bind module name"]
    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style H fill:#FBE9E9,stroke:#D9AAAA,color:#334155
    style I fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style J fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Pay special attention: sys.path is not the only search mechanism in the import system. Meta path finders can provide modules before or outside the regular path search, so not all import behavior can be simply understood as only traversing sys.path.

3. The PYTHONPATH Environment Variable

PYTHONPATH can add module search directories for Python.

Linux or macOS:

export PYTHONPATH=/opt/my_python_libs:$PYTHONPATH

Windows PowerShell:

$env:PYTHONPATH = "C:\my_python_libs;$env:PYTHONPATH"

Afterward, when Python starts, it will include these directories in the module search path configuration.

It is not advisable to set too many global search directories arbitrarily; otherwise, module name conflicts may occur between different projects.

4. Dynamically Modifying sys.path

You can also add paths while the program is running:

import sys

sys.path.append("/opt/my_python_libs")

import my_module

append() adds the directory to the end of the search path.

If you use:

sys.path.insert(0, "/opt/my_python_libs")

then the directory will be placed at the front of the search path, increasing its priority in the regular path search.

However, this may also cause custom modules to override modules with the same name in the standard library or third-party packages.

Engineering projects generally recommend using a standardized package structure, virtual environments, and installable projects rather than relying on extensive manual modifications to sys.path.

VII. Absolute and Relative Imports

When a project contains multiple directories and modules, how import paths are written affects code maintainability.

Python supports two main approaches: absolute imports and relative imports.

1. Absolute Import

An absolute import describes the module path starting from the top-level package name.

Project structure:

my_project/
├── main.py
└── app/
    ├── __init__.py
    ├── services/
    │   ├── __init__.py
    │   └── user_service.py
    └── utils/
        ├── __init__.py
        └── logger.py

In user_service.py:

from app.utils.logger import get_logger

Absolute imports explicitly specify the complete package path of a module and are suitable for large projects.

2. Relative Import

Relative imports use dots to indicate the current package or a parent package.

For example:

from ..utils.logger import get_logger

Where:

  • . indicates the current package.
  • .. indicates the parent package.
  • ... indicates the package two levels up.

Relative imports can reduce path duplication within a package, making it easier to maintain when the package structure changes.

3. Differences Between Absolute and Relative Imports

Aspect Absolute import Relative import
Path starting point Top-level package Current package
Readability Path is explicit Better suited to references inside a package
Directory changes Paths may need to be modified Adjustments within the same package may be more flexible
Scope of use Works both inside and outside the package Requires the correct package context
Main risk Package names changing Incorrect runtime context

4. Why Relative Imports Cannot Be Run Arbitrarily

Suppose user_service.py contains:

from ..utils.logger import get_logger

If you run it directly:

python app/services/user_service.py

You may get:

ImportError: attempted relative import with no known parent package

The reason is that when a file is executed directly, Python usually runs it as a top-level script, lacking the package context that relative imports require.

A more appropriate approach is to run it from the project root directory:

python -m app.services.user_service

-m runs the target module by its module name, giving it the appropriate package context.

Note that -m does not simply swap a file path for a module path; it affects the module's runtime identity and import environment.

VIII. The Relationship Between Packages and Modules

As a project grows complex, a single module is no longer enough to organize all the code. At this point you can use packages.

A package is a structure for organizing multiple modules, forming a hierarchical namespace.

1. Regular Packages

Typical structure:

my_project/
├── main.py
└── app/
    ├── __init__.py
    ├── models.py
    ├── services.py
    └── utils.py

Here:

  • app is a package.
  • models.py is a module.
  • services.py is a module.
  • utils.py is a module.
  • __init__.py is the package initialization file.

In traditional regular packages, __init__.py marks the directory as a package and can execute package initialization code.

For example:

# app/__init__.py

VERSION = "1.0.0"

From outside, you can access it like this:

import app

print(app.VERSION)

2. Importing Modules Within a Package

You can import a module inside a package directly:

import app.models

user = app.models.User()

You can also use:

from app import models

user = models.User()

Or you can import a specific member from a module:

from app.models import User

user = User()

These three approaches bind names differently, so choose based on code readability and namespace requirements.

3. The Role of init.py

__init__.py can take on the following responsibilities:

  • Marking a traditional regular package.
  • Executing package initialization logic.
  • Exposing the package-level public interface.
  • Defining the package's version information.
  • Defining __all__ to control which names a star import brings in.

For example:

# app/__init__.py

from .models import User
from .services import UserService

__all__ = ["User", "UserService"]

Then from outside you can use them directly:

from app import User, UserService

But note that imports inside a package initialization file add dependencies at package initialization time. If the import chain is complex, circular imports become likely.

Therefore, __init__.py should not accumulate too much business logic.

4. Namespace Packages

Python 3 also supports namespace packages.

A namespace package allows multiple directories to jointly form a single package, without requiring an __init__.py in every directory.

For example:

project_a/
└── company/
    └── service_a/
        └── __init__.py

project_b/
└── company/
    └── service_b/
        └── __init__.py

If the parent directories of both projects are on the import search path, company can serve as a namespace package, combining subpackages from different locations.

Namespace packages suit large ecosystems, plugin architectures, and cross-project extension.

However, the lookup rules for regular packages and namespace packages differ, so you cannot simply assume that a missing __init__.py makes import impossible.

9. name and main

__name__ is an important attribute of Python modules, and the key mechanism for distinguishing module import from direct script execution.

1. Values of name

When a module is run in different ways, the value of __name__ may differ:

How it is run Typical value of __name__
Executing a Python file directly __main__
Using python -m package.module __main__
Imported by another module The module's canonical import name
Executed through an interactive environment Usually __main__

2. if name == "main"

A common pattern:

def add(a, b):
    return a + b

def main():
    print(add(10, 20))

if __name__ == "__main__":
    main()

When the file is executed directly, __name__ is usually __main__, so main() is called.

When the file is imported as a module, __name__ is usually the module name, the condition is false, and the entry-point code does not run.

3. Why a main entry point is needed

This structure separates module definitions from program execution logic:

  • Functions and classes can be reused by other modules.
  • Importing the module does not automatically execute the main program logic.
  • The program entry point is clearer.
  • Testing tools can import the module without triggering the full program.

4. Module execution identity and import name

Using:

python -m app.tools

When you run a module this way, __name__ in the code is usually __main__, but information such as the module's __spec__ can still retain its original module specification.

This means the execution identity is not exactly the same as the module's place in the package hierarchy.

In addition, if the same file is loaded under different module names, it may produce different module objects. This can lead to inconsistencies in class identity checks, singleton state, and global variables.

Therefore, use a consistent module import path wherever possible, and avoid loading the same source file repeatedly as multiple modules.

10. Common module import errors

Module import problems usually stem from the search path, name conflicts, circular dependencies, and incorrect package context.

1. ModuleNotFoundError

For example:

import my_module

The error:

ModuleNotFoundError: No module named 'my_module'

Common causes:

  • The module file does not exist.
  • The directory containing the module is not on the search path.
  • The virtual environment is misconfigured.
  • A third-party dependency is not installed.
  • The module name is misspelled.

How to troubleshoot:

import sys

print(sys.executable)
print(sys.path)

Confirm that the current interpreter and module search path match expectations.

2. ImportError

For example:

from math import unknown_function

If the module exists but the specified member does not, ImportError is raised.

Other cases include: