ZetCode

Python module

last modified November 17, 2026 Python 3.15

In this article we show how to create and use modules in Python.

A module is a file containing Python definitions and statements. The file name is the module name with the .py extension appended. Modules are the basic unit of code organization in Python: related functions, classes, and variables are placed in one module, and other code uses them by importing the module.

Python code is organized into these building blocks:

A small script can live in a single module. Larger programs are split into several modules; database code goes into one module, security code into another, and so on. Modules are in turn grouped into packages. Each module has its own global namespace, so names defined in one module do not clash with the same names in another.

Module names

A module name is the file name without the .py extension; the empty.py file is the empty module. Inside a module, the name is available in the __name__ global variable. The module that is run as a program, the main module, gets the special name '__main__'.

empty.py
"""
An empty module
"""

This is the empty module. It contains only a docstring.

test_empty.py
import empty
import sys

print(__name__)
print(empty.__name__)
print(sys.__name__)

The test_empty.py program imports two modules: the sys module from the standard library and our own empty module. It prints the names of the current module and of the two imported modules. Both files are in the same directory; the directory of the executed script is searched for modules first.

$ python test_empty.py
__main__
empty
sys

The module search path

When a module is imported, Python looks for it in the list of directories stored in sys.path. The list is initialized from the directory of the executed script (or the current directory in the interactive shell), the directories in the PYTHONPATH environment variable, and installation-dependent defaults such as the standard library and the site-packages directory.

search_path.py
import sys

for path in sys.path:
    print(path)

The program prints the directories of the module search path, one per line. The first entry is the directory of the script. If a module is not found in any of these directories, a ModuleNotFoundError is raised.

$ python search_path.py
/home/user/python
/home/user/.local/share/uv/python/cpython-3.15.2-linux-x86_64-gnu/lib/python315.zip
/home/user/.local/share/uv/python/cpython-3.15.2-linux-x86_64-gnu/lib/python3.15
/home/user/.local/share/uv/python/cpython-3.15.2-linux-x86_64-gnu/lib/python3.15/lib-dynload
/home/user/.local/share/uv/python/cpython-3.15.2-linux-x86_64-gnu/lib/python3.15/site-packages

Built-in and standard library modules

Some modules, such as sys or math, are compiled into the interpreter; they are found before the search path is consulted. The sys.builtin_module_names tuple lists them. The sys.stdlib_module_names frozenset contains the names of all standard library modules.

module_kinds.py
import sys

import json
import math

print('math' in sys.builtin_module_names)
print('json' in sys.builtin_module_names)
print('json' in sys.stdlib_module_names)

print(json.__file__)
print(getattr(math, '__file__', 'no file, compiled into the interpreter'))

The json module is a regular standard library module loaded from a file, while math is built into the interpreter and has no __file__ attribute. The getattr function returns the given default when the attribute is missing.

$ python module_kinds.py
True
False
True
/home/user/.local/share/uv/python/cpython-3.15.2-linux-x86_64-gnu/lib/python3.15/json/__init__.py
no file, compiled into the interpreter

The import statement

The most common form of import binds the module object to its name in the current namespace. The definitions of the module are then accessed with the dot operator.

import_module.py
import math

pi = 3.14

print(math.cos(3))
print(math.pi)
print(pi)

We reference the definitions through the module name. Our own pi variable does not clash with math.pi; the two names live in different namespaces.

$ python import_module.py
-0.9899924966004454
3.141592653589793
3.14

Importing specific names

The from module import name form copies the selected names into the current namespace. The module itself is not bound to a name.

import_specific.py
from math import sin, pi

print(sin(3))
print(pi)

try:
    print(cos(3))
except NameError as e:
    print(e)

We import the sin function and the pi constant from the math module and use them without the module prefix. Other definitions of the module, such as cos, are not available.

$ python import_specific.py
0.1411200080598672
3.141592653589793
name 'cos' is not defined

Aliasing modules and names

The as keyword binds an imported module or name to a different name. Aliases shorten long names and help avoid clashes.

aliasing.py
import statistics as stats
from datetime import date as Date

vals = [1, 2, 3, 4, 5, 6, 7]

print(stats.mean(vals))
print(stats.median(vals))
print(Date(2026, 11, 17).isoformat())

The statistics module is available as stats and the date class as Date.

$ python aliasing.py
4
4
2026-11-17

Importing all names

The from module import * form imports all public names of a module into the current namespace.

star_import.py
from math import *

print(cos(3))
print(pi)

We call cos and read pi directly, without the module prefix. This form is handy in the interactive shell but is discouraged in programs, because it is not clear which names are present in the namespace.

$ python star_import.py
-0.9899924966004454
3.141592653589793

Namespace pollution

A star import silently overwrites existing names that happen to be defined in the imported module.

pollution.py
e = 'error code'
pi = 3.14

from math import *

print(pi)
print(e)

Our e and pi variables are replaced by the math.e and math.pi constants. In larger programs, such clashes lead to bugs that are hard to find.

$ python pollution.py
3.141592653589793
2.718281828459045

Private names

Names beginning with an underscore are considered private to the module. A star import does not import them.

names.py
"""
names is a test module
"""

_version = 1.0

names = ['Paul', 'Frank', 'Jessica', 'Thomas', 'Katherine']


def show_names():
    for name in names:
        print(name)


def _show_version():
    print(_version)

The names module defines a private _version variable and a private _show_version function.

test_names.py
from names import *

print([name for name in globals() if not name.startswith('__')])

show_names()

try:
    _show_version()
except NameError as e:
    print(e)

We import everything from the names module and print the names of the current namespace that do not start with a double underscore. Only names and show_names were imported.

$ python test_names.py
['names', 'show_names']
Paul
Frank
Jessica
Thomas
Katherine
name '_show_version' is not defined

Importing private names explicitly

The underscore is only a convention. Private names can still be imported explicitly.

private_names.py
from names import _version, _show_version

print(_version)
_show_version()

We import the private variable and function by their names. This works, but it is a bad practice; private names are not part of the module's interface and may change without notice.

$ python private_names.py
1.0
1.0

The __all__ variable

A module can define its public interface in the __all__ list. When it is present, a star import imports exactly the listed names.

shapes.py
__all__ = ['area', 'Square']

UNIT = 'cm'


class Square:

    def __init__(self, side):
        self.side = side


def area(shape):
    return f'{shape.side ** 2} {UNIT}²'

The shapes module exports the area function and the Square class. The UNIT constant is not listed.

test_shapes.py
from shapes import *

sq = Square(4)
print(area(sq))

try:
    print(UNIT)
except NameError as e:
    print(e)

The star import brings in Square and area. The UNIT constant is used inside the module, but it is not imported into our namespace.

$ python test_shapes.py
16 cm²
name 'UNIT' is not defined

Import errors

A ModuleNotFoundError is raised when a module cannot be found; it is a subclass of ImportError. An ImportError is raised when a module exists but the requested name cannot be imported from it.

import_error.py
try:
    import empty2
except ModuleNotFoundError as e:
    print('Failed to import:', e)
    print('Module name:', e.name)

try:
    from math import cube
except ImportError as e:
    print('Failed to import:', e)

There is no empty2 module and no cube function in the math module. The name attribute of the exception holds the name of the missing module.

$ python import_error.py
Failed to import: No module named 'empty2'
Module name: empty2
Failed to import: cannot import name 'cube' from 'math' (unknown location)

Optional dependencies

Catching ModuleNotFoundError is a common way to use a faster third-party module when it is installed and fall back to the standard library otherwise.

optional_dep.py
try:
    import ujson as json
except ModuleNotFoundError:
    import json

data = {'name': 'Paul', 'age': 34}

print(json.__name__)
print(json.dumps(data))

The program tries the ujson package first. It is not installed, so the standard json module is imported under the same name; the rest of the code works with either.

$ python optional_dep.py
json
{"name": "Paul", "age": 34}

Executing modules

A module can be imported or run as a script. The code in the if __name__ == '__main__': block is executed only when the module is run as the main program; when the module is imported, its __name__ is the module name and the block is skipped.

We demonstrate this on a module with a Fibonacci function. In the Fibonacci sequence, each number is the sum of the two preceding ones.

fibonacci.py
"""
A module containing the fibonacci function.
"""


def fib(n):
    a, b = 0, 1
    while b < n:
        print(b, end=' ')
        a, b = b, a + b
    print()


if __name__ == '__main__':
    fib(500)

When run as a script, the module prints the Fibonacci numbers smaller than 500. When imported, it only defines the fib function.

$ python fibonacci.py
1 1 2 3 5 8 13 21 34 55 89 144 233 377 
$ python -c "import fibonacci; fibonacci.fib(100)"
1 1 2 3 5 8 13 21 34 55 89 
$ python -m fibonacci
1 1 2 3 5 8 13 21 34 55 89 144 233 377 

Running modules with -m

The -m option of the interpreter locates a module on the search path and runs it as the main module. The previous transcript ended with python -m fibonacci. Many standard library modules provide a command-line interface this way.

$ python -m http.server
$ python -m json.tool data.json
$ python -m venv .venv

The commands start a simple web server, pretty-print a JSON file, and create a virtual environment. Running a module with -m also puts the current directory at the start of sys.path, so local imports work the same way as in a script.

Modules are loaded only once

A module is executed only the first time it is imported. The module object is stored in the sys.modules dictionary, and later imports return the cached object.

counter.py
print(f'loading module {__name__}')

count = 0


def increment():
    global count
    count += 1
    return count

The counter module prints a message when its code runs and keeps a counter in a module-level variable.

single_load.py
import sys

import counter
import counter as cnt

counter.increment()
counter.increment()

print(cnt.count)
print(counter is cnt)
print(sys.modules['counter'] is counter)

We import the module twice, once under an alias. The loading message is printed only once and both names refer to the same module object, so the state is shared.

$ python single_load.py
loading module counter
2
True
True

Reloading modules

The importlib.reload function executes the code of an already imported module again. It is mostly useful in interactive sessions after the source file has been edited.

reloading.py
import importlib

import counter

counter.increment()
print(counter.count)

importlib.reload(counter)
print(counter.count)

The reload runs the module code again, which resets the count variable to zero. The module object stays the same; its namespace is updated in place.

$ python reloading.py
loading module counter
1
loading module counter
0

Importing modules by name

The importlib.import_module function imports a module whose name is known only at runtime, for instance from a configuration file or a command-line option.

dynamic_import.py
import importlib

data = {'name': 'Paul', 'age': 34}

for name in ('json', 'pickle', 'marshal'):
    mod = importlib.import_module(name)
    out = mod.dumps(data)
    print(f'{mod.__name__:8} {type(out).__name__:6} {len(out)}')

The three modules all provide a dumps function. We import each of them by name, serialize the same dictionary, and print the type and length of the result: json produces a string, the other two produce bytes.

$ python dynamic_import.py
json     str    27
pickle   bytes  38
marshal  bytes  24

Module attributes

Each module has special attributes set by the import system: __name__, __doc__, __file__, __spec__, and others. The __spec__ object describes how the module was found and loaded.

module_attrs.py
"""
Shows the special attributes of a module.
"""

import fibonacci

print(__name__)
print(__doc__.strip())
print(__file__)

print(fibonacci.__name__)
print(fibonacci.__file__)
print(fibonacci.__spec__.cached)
print(hasattr(fibonacci, '__cached__'))

We print attributes of the main module and of the imported fibonacci module. The __spec__.cached attribute holds the path of the compiled bytecode file. Python 3.15 no longer sets the old __cached__ module attribute, which was deprecated in favour of __spec__.cached.

$ python module_attrs.py
__main__
Shows the special attributes of a module.
/home/user/python/module_attrs.py
fibonacci
/home/user/python/fibonacci.py
/home/user/python/__pycache__/fibonacci.cpython-315.pyc
False

The __pycache__ directory

Python compiles the source of a module to bytecode before executing it. To speed up later imports, it caches the bytecode of imported modules in the __pycache__ directory as module.cpython-315.pyc, where the tag identifies the interpreter version. The cached file is reused until the source changes. The main script itself is not cached.

In the following session, we run a program that imports the names module; only that module gets a .pyc file. Then the compileall module compiles two more modules ahead of time; the -q option suppresses the list of compiled files. Given a directory, compileall compiles all modules in it recursively.

$ python test_names.py > /dev/null
$ ls __pycache__
names.cpython-315.pyc
$ python -m compileall -q fibonacci.py shapes.py
$ ls __pycache__
fibonacci.cpython-315.pyc
names.cpython-315.pyc
shapes.cpython-315.pyc

The dir function

The built-in dir function without arguments returns a sorted list of names in the current namespace. With a module argument, it returns the names defined in that module.

dir_fun.py
"""
This is dir_fun module
"""

import math
import textwrap

version = 1.0

names = ['Paul', 'Frank', 'Jessica', 'Thomas', 'Katherine']


def show_names():
    for name in names:
        print(name)


print(textwrap.fill(', '.join(dir())))
print([name for name in dir(math) if name.startswith('f')])

We import two modules and define a variable, a list, and a function. Then we print the names of the current module, wrapped with textwrap.fill, and the names of the math module that start with the letter f.

$ python dir_fun.py
__builtins__, __doc__, __file__, __loader__, __name__, __package__,
__spec__, math, names, show_names, textwrap, version
['fabs', 'factorial', 'floor', 'fma', 'fmax', 'fmin', 'fmod', 'frexp', 'fsum']

The globals function

The globals function returns the dictionary of the current module's global namespace. It is the actual namespace, not a copy; changing it changes the module's variables.

globals_fun.py
import textwrap

version = 1.0


def myfun():
    pass


gl = globals()
print(textwrap.fill(', '.join(gl)))

print(gl['version'])
gl['version'] = 2.0
print(version)

We print the global names of the module and then modify the version variable through the dictionary.

$ python globals_fun.py
__name__, __doc__, __package__, __loader__, __spec__, __builtins__,
__file__, textwrap, version, myfun, gl
1.0
2.0

The __module__ attribute

The __module__ attribute of a class holds the name of the module in which the class is defined. Instances see it through their class.

animals.py
"""
module animals
"""


class Cat:
    pass


class Dog:
    pass

The animals module defines two classes.

class_module.py
from animals import Cat


class Being:
    pass


b = Being()
print(b.__module__)

c = Cat()
print(c.__module__)
print(Cat.__module__, Cat.__qualname__)

We define the Being class in the main module and import the Cat class from the animals module. Together with __qualname__, the __module__ attribute fully identifies where a class comes from; the pickle module uses it to locate classes when loading objects.

$ python class_module.py
__main__
animals
animals Cat

Module __getattr__

A module can define a __getattr__ function. It is called when an attribute is not found in the module, which allows computed or deprecated names.

settings.py
import warnings

TIMEOUT = 30


def __getattr__(name):
    if name == 'TIME_OUT':
        warnings.warn('TIME_OUT is deprecated, use TIMEOUT',
                      DeprecationWarning, stacklevel=2)
        return TIMEOUT
    raise AttributeError(f'module {__name__!r} has no attribute {name!r}')

The settings module renamed TIME_OUT to TIMEOUT. The old name still works but issues a DeprecationWarning. Other unknown names raise an AttributeError.

use_settings.py
import warnings

import settings

warnings.simplefilter('always')

print(settings.TIMEOUT)
print(settings.TIME_OUT)

try:
    print(settings.RETRIES)
except AttributeError as e:
    print(e)

Deprecation warnings are hidden by default outside the main module, so we enable all warnings with simplefilter('always'). The warning is written to standard error and refers to the line of the caller thanks to stacklevel=2.

$ python use_settings.py
30
/home/user/python/use_settings.py:8: DeprecationWarning: TIME_OUT is deprecated, use TIMEOUT
  print(settings.TIME_OUT)
30
module 'settings' has no attribute 'RETRIES'

Lazy imports

Python 3.15 adds explicit lazy imports (PEP 810). A lazy import or lazy from ... import statement binds the name immediately but postpones loading the module until the name is first used. This shortens the start-up time of programs that import many modules but need only some of them in a given run.

lazy_imports.py
import sys

lazy import json
lazy from decimal import Decimal

print('json' in sys.modules)
print('decimal' in sys.modules)

print(json.dumps({'price': str(Decimal('1.10') + Decimal('2.20'))}))

print('json' in sys.modules)
print('decimal' in sys.modules)

Neither json nor decimal is in sys.modules after the lazy import statements. Both are loaded when the json.dumps call needs them. The lazy soft keyword is new in 3.15; older interpreters report a syntax error.

$ python lazy_imports.py
False
False
{"price": "3.30"}
True
True
$ python3.14 lazy_imports.py
  File "/home/user/python/lazy_imports.py", line 3
    lazy import json
         ^^^^^^
SyntaxError: invalid syntax

Source

Modules – The Python Tutorial

The import system – Python language reference

importlib – The implementation of import

PEP 810 – Explicit lazy imports

In this article we have worked with Python modules. See also Python package, Python relative imports, Python namespace packages, and Python dir built-in function.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.