Skip to main content
As your programs grow beyond a single file, you need a way to split code into manageable, reusable pieces. Python’s module and package system lets you do exactly that: put related functions and classes in their own .py file, then import exactly what you need wherever you need it. This page takes you from importing a single function all the way to structuring a multi-file project.

What is a Module?

A module is any Python file with a .py extension. Every variable, function, and class defined in that file becomes part of the module’s namespace and can be imported by other files. Suppose you create calculator.py:
You can now use it from main.py in the same directory:

Import Styles

Imports the entire module. Access members using module.name:
Best when you use many things from the module and want to keep the namespace clear.

The if __name__ == '__main__' Pattern

When Python runs a file directly, it sets the special variable __name__ to "__main__". When the file is imported by another module, __name__ is set to the module’s own name instead. This lets you guard code that should only run when the file is executed directly:
Always use this pattern to separate reusable library code from executable scripts. It makes your modules safe to import without triggering side effects.

Built-in Standard Library Modules

Python ships with a comprehensive standard library — no installation needed.

math — Mathematics

random — Random Numbers

datetime — Dates and Times

os — Operating System Interface

sys — System Information


Creating Your Own Module

1

Write your functions in a .py file

Create utils.py in your project directory:
2

Import and use it in another file

In main.py (same directory):

What is a Package?

A package is a directory that contains one or more module files plus a special file named __init__.py. The presence of __init__.py tells Python to treat the folder as an importable package.

Simple Package Structure

math_utils.py:
text_utils.py:
__init__.py — expose the most-used names at the package level:
main.py:

Realistic Multi-File Project Layout

As your project grows, a typical structure looks like this:
Keep each module focused on a single responsibility. A module named user.py should only contain user-related code. This makes the project easy to navigate and test.

Key Takeaways

Module = .py file

Any .py file is a module. Break your code into files the moment a single file grows hard to navigate.

Standard library first

Before installing a third-party package, check whether math, datetime, os, random, or another built-in module already solves your problem.

__init__.py controls the API

Use __init__.py to decide which names are public. Import the most-used names there so consumers don’t need to know the internal file structure.

if __name__ == '__main__'

Guard executable code with this pattern to keep modules both importable as a library and runnable as a script.