Python Modules

Last Updated 29 Sep, 2026

A Python module is a single file of Python code, saved with a .py extension, that holds functions, classes, and variables. Splitting a program into modules keeps each file focused on one job, makes bugs easier to find, and lets you reuse the same code in many projects without copying it.

Creating Your Own Module

Any Python file is already a module. Save the following as geometry.py:

# geometry.py
import math
 def circle_area(radius):
    return math.pi * radius ** 2
 def rectangle_area(width, height):
    return width * height

Now create another file in the same folder and use it:

import geometry
 print(geometry.rectangle_area(4, 5))
print(round(geometry.circle_area(3), 2))

Output:

 
20
28.27

The module's contents are reached with dot notation: module_name.item.

Ways to Import

Import the whole module. Everything stays behind the module name, which keeps your namespace tidy.

import geometry

Import selected names. Only the names you list are brought in, so no prefix is needed.

from statistics import mean, median
 data = [4, 8, 15, 16, 23, 42]
print(mean(data))
print(median(data))

Output:

18
15.5

Import with an alias. Useful for long module names or common conventions (import numpy as np).

import datetime as dt
 print(dt.date(2026, 9, 29).strftime("%A"))

Output:

Tuesday

Import everything with *. This pulls every public name into your file.

from collections import *

Avoid this in real projects. You can no longer tell where a name came from, and it can silently overwrite your own variables or functions. If a module defines a list called __all__, only the names in that list are imported this way.

Kinds of Modules

Built-in and standard library modules ship with Python, so nothing needs installing (os, json, collections, pathlib).

from collections import Counter
 print(Counter("banana").most_common(1))

Output:

[('a', 3)]

User-defined modules are the files you write yourself, like geometry.py above.

Third-party modules are written by the community and installed with pip, for example pip install requests.

import requests
 response = requests.get("https://example.com")
print(response.status_code)

Packages are folders that group related modules. A folder is treated as a package when it contains an __init__.py file (that file can be empty). Since Python 3.3, folders without it can still be imported as "namespace packages", but including it is still the clearer choice for regular projects.

shop/
    __init__.py
    cart.py
    payment.py
 
from shop import cart
from shop.payment import charge_card

Inside a package, modules can refer to each other with relative imports:

# inside shop/payment.py
from . import cart          # sibling module
from .cart import total     # a name from a sibling module

Inspecting a Module

The built-in dir() lists the names a module defines:

import geometry
 print([name for name in dir(geometry) if not name.startswith("_")])

Output:

['circle_area', 'math', 'rectangle_area']

Note that math appears too, because geometry imported it.

Running a File Directly vs. Importing It

When Python runs a file directly, it sets the special variable __name__ to "__main__". When the same file is imported, __name__ is the module's name instead. This lets one file work as both a reusable module and a script:

# geometry.py
import math
 def circle_area(radius):
    return math.pi * radius ** 2
 if __name__ == "__main__":
    print(circle_area(1))

Running python geometry.py prints 3.141592653589793. Importing geometry from elsewhere prints nothing, because the block is skipped.

How Python Finds a Module

When you write import something, Python looks in this order:

  1. sys.modules, a cache of modules already loaded in the current run.
  2. Built-in modules compiled into the interpreter.
  3. The directories listed in sys.path.

sys.path normally contains the folder of the running script, any folders in the PYTHONPATH environment variable, the standard library folders, and the site-packages folder where pip installs libraries.

import sys
print(sys.path)

Because of the sys.modules cache, a module's code runs only on the first import. Importing it again in the same program just reuses the loaded copy. If you edit a module while a session is running and want the change applied, use:

import importlib
importlib.reload(geometry)

Python also saves compiled bytecode in a __pycache__ folder so repeat imports load faster. You can ignore this folder and leave it out of version control.

Common Mistakes

  • Naming your file after an existing module. A file called random.py or math.py in your project will shadow the standard library version and cause confusing errors. Pick unique names.
  • Circular imports. If a.py imports b.py and b.py imports a.py at the top level, you can hit errors from half-loaded modules. Restructure shared code into a third module, or move the import inside the function that needs it.
  • Using import *. As covered above, it hides where names come from and invites conflicts.
  • Module not found. Check the spelling, confirm the file is in a folder on sys.path, and for third-party libraries make sure pip installed it into the same Python environment you are running.

Conclusion

A module is just a Python file you can import. Use import, from ... import, or an alias depending on how you want names to appear. Standard library, your own files, pip-installed libraries, and packages are all imported the same way. Python resolves imports through sys.modules and sys.path, and the if __name__ == "__main__": check lets a file serve as both a script and a module.