Data types and variables
Modules and Packages
Conversion Programs
More Code Examples
Cheat Sheet

Organizing Modules into Packages

What is a Package?

A package in Python is a way of organizing related modules into a directory hierarchy. It allows for a structured way to manage code and promotes modular programming.

Creating a Package

Basic Structure

To create a package, follow this structure:

  • This file can be empty but is necessary to mark the directory as a package. It can also include initialization code for the package.
  • and Python files containing your code.

Here’s an example of a simple package structure:



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

def subtract(a, b):
    return a - b


def uppercase(text):
    return text.upper()

def lowercase(text):
    return text.lower()

Importing from Packages

To use functions from your package:

from mypackage.math_operations import add
from mypackage.string_operations import uppercase

print(add(5, 3))

You can also import entire modules:

import mypackage.math_operations as math_ops

print(math_ops.subtract(10, 5))

Benefits of Using Packages

Code Organization

Packages help organize code into logical sections, making it easier to manage and navigate large codebases.

Namespace Management

Packages prevent naming conflicts by encapsulating modules within a namespace.


Modular code within packages can be reused across multiple projects, enhancing efficiency.

Advanced Package Features


Packages can contain subpackages to further organize code:


To import from subpackages:

from mypackage.utils.helper import some_function

The file can be used to define what is available when importing the package:

# mypackage/
from .math_operations import add, subtract
from .string_operations import uppercase, lowercase

Then, you can import directly from the package:

from mypackage import add, uppercase

Best Practices for Packages

Clear Structure

Maintain a clear, logical directory structure to make navigation and maintenance easier.


Include documentation within each module and package to describe their purpose and usage.

Version Control

Use version control systems like Git to manage changes and track the evolution of your packages.