Skip to main content
Editor

How to Create and Structure a Python Package

Intermediate20 min4 exercises60 XP
0/4 exercises

Imagine you have a filing cabinet. Right now, all your papers are thrown in one big drawer - recipes mixed with homework mixed with tax forms. Finding anything is a nightmare.

A Python package is like adding labeled folders to that filing cabinet. Instead of one giant file with all your code, you split it into organized folders where each folder handles one topic.

In this tutorial, you'll learn how Python packages work, what the mysterious __init__.py file does, and how to structure your own projects like a professional developer.

What Is a Python Package?

You already know that a module is a single .py file. A package takes it one step further - it's a folder that contains multiple modules.

The key ingredient that turns a regular folder into a Python package is a special file called __init__.py. When Python sees a folder with this file, it knows: "This folder is a package I can import from."

Simulating a package with two modules
# A simple package structure:
# mypackage/
# __init__.py
# greetings.py
# math_tools.py
# Let's simulate this with Python code
# Imagine greetings.py contains:
def say_hello(name):
return f'Hello, {name}!'
# And math_tools.py contains:
def add(a, b):
return a + b
# We can use both from the same package
print(say_hello('Alice'))
print(add(3, 7))
Output
Hello, Alice!
10

In a real project, each function above would live in its own file inside the mypackage/ folder. You'd import them like from mypackage.greetings import say_hello.


What Does __init__.py Do?

Think of __init__.py as the front desk of a building. When someone walks in, the front desk tells them what's available and where to go.

The __init__.py file runs automatically whenever you import the package. It can be completely empty, or it can contain code that sets up the package - like importing key functions so users don't have to dig through submodules.

How __init__.py works as a front desk
# Imagine __init__.py inside mypackage/ contains:
# from .greetings import say_hello
# from .math_tools import add
# This lets users write:
# from mypackage import say_hello, add
# Instead of:
# from mypackage.greetings import say_hello
# from mypackage.math_tools import add
# Let's simulate what __init__.py does:
package_exports = ['say_hello', 'add']
print('Package loaded!')
print(f'Available functions: {package_exports}')
Output
Package loaded!
Available functions: ['say_hello', 'add']

An empty __init__.py is perfectly fine. It just tells Python "this folder is a package." But adding imports to it creates a cleaner experience for anyone using your package.

Controlling exports with __all__
# Simulating __all__ behavior
__all__ = ['greet', 'farewell']
def greet(name):
return f'Hello, {name}!'
def farewell(name):
return f'Goodbye, {name}!'
def _internal_helper():
return 'This is private'
# Only greet and farewell are in __all__
for name in __all__:
print(f'Public function: {name}')
print(f'\n_internal_helper is hidden from import *')
Output
Public function: greet
Public function: farewell

_internal_helper is hidden from import *

How Should You Structure a Python Package?

A well-organized package is like a well-organized kitchen. Pots go in one cabinet, spices in another. Anyone walking in can find what they need without opening every drawer.

Here's a typical layout for a Python project with a package inside it:

A professional project layout
# Standard project layout:
project_layout = '''
my_project/
README.md
pyproject.toml
src/
mypackage/
__init__.py
core.py
utils.py
models/
__init__.py
user.py
product.py
tests/
test_core.py
test_utils.py
'''
print(project_layout)
Output

my_project/
    README.md
    pyproject.toml
    src/
        mypackage/
            __init__.py
            core.py
            utils.py
            models/
                __init__.py
                user.py
                product.py
    tests/
        test_core.py
        test_utils.py

Notice the src/ folder. This is called the src layout and is recommended by the Python Packaging Authority. It prevents accidental imports from your project root instead of the installed package.

Visualizing nested packages
# Sub-packages: packages inside packages!
# This is how large projects stay organized.
structure = {
'mypackage': {
'__init__.py': 'top-level init',
'core.py': 'main logic',
'utils.py': 'helper functions',
'models': {
'__init__.py': 'models init',
'user.py': 'user-related code',
'product.py': 'product-related code',
},
}
}
def print_structure(tree, indent=0):
for key, value in tree.items():
prefix = ' ' * indent
if isinstance(value, dict):
print(f'{prefix}{key}/')
print_structure(value, indent + 1)
else:
print(f'{prefix}{key} # {value}')
print_structure(structure)
Output
mypackage/
  __init__.py  # top-level init
  core.py  # main logic
  utils.py  # helper functions
  models/
    __init__.py  # models init
    user.py  # user-related code
    product.py  # product-related code

Each sub-folder that has an __init__.py is its own sub-package. You can nest as deep as you need, but try to keep it to 2-3 levels. Deeper nesting usually means your project needs a redesign.


What Are Relative vs Absolute Imports?

When modules inside a package need to import from each other, you have two choices: absolute imports and relative imports.

An absolute import spells out the full path from the top-level package. A relative import uses dots to say "import from nearby." It's like the difference between giving a full street address vs saying "the house next door."

Absolute Import
# Inside mypackage/models/user.py
from mypackage.utils import validate_email
from mypackage.core import Database
Relative Import
# Inside mypackage/models/user.py
from ..utils import validate_email
from ..core import Database

In relative imports, a single dot . means "current package" and double dots .. mean "parent package." Three dots ... mean "grandparent," and so on.

Understanding dot notation in relative imports
# Let's understand the dot notation:
import_examples = {
'from . import utils': 'Import from current package',
'from .utils import helper': 'Import helper from sibling module',
'from .. import core': 'Import from parent package',
'from ..core import Engine': 'Import Engine from parent's core module',
'from ...config import settings': 'Import from grandparent package',
}
for code, meaning in import_examples.items():
print(f'{code}')
print(f' -> {meaning}\n')
Output
Traceback (most recent call last):
  File "<exec>", line 6
    'from ..core import Engine': 'Import Engine from parent's core module',
                                                                         ^
SyntaxError: unterminated string literal (detected at line 6)

How Do You Build a Complete Package from Scratch?

Let's walk through building a small but complete package. We'll simulate the file structure in a single script since we're in a browser, but the logic is exactly what you'd put in separate files.

A complete mathkit package simulation
# ── Simulating: mathkit/__init__.py ──
# from .operations import add, subtract
# from .formatting import format_result
# ── Simulating: mathkit/operations.py ──
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
# ── Simulating: mathkit/formatting.py ──
def format_result(operation, a, b, result):
return f'{a} {operation} {b} = {result}'
# ── Using the package ──
result1 = add(10, 5)
result2 = subtract(10, 5)
result3 = multiply(10, 5)
print(format_result('+', 10, 5, result1))
print(format_result('-', 10, 5, result2))
print(format_result('*', 10, 5, result3))
Output
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50

In a real project, each section above would be its own file. The __init__.py would import add, subtract, and format_result so users can access them directly from mathkit.


Practice Exercises

Time to practice! These exercises test your understanding of package structure, __init__.py, and imports.

Build a Package Structure Dictionary
Write Code

Create a function called get_package_structure() that returns a dictionary representing a Python package structure. The dictionary should have a key 'webapp' whose value is another dictionary containing these keys (in any order): '__init__.py', 'routes.py', 'models.py', and 'utils.py'. Each value should be the string 'module'.

def get_package_structure():
# Build and return the package structure dictionary
pass
Fix the Broken __all__ Export
Fix the Bug

The code below defines a simulated package with a __all__ list and three functions. The get_public_api() function should return only the names listed in __all__, but there are bugs. Fix them so the output shows exactly the two public functions.

# Simulated package exports
_all_ = ['calculate_area', 'calculate_perimeter']
def calculate_area(radius):
return 3.14159 * radius ** 2
def calculate_perimeter(radius):
return 2 * 3.14159 * radius
def _internal_validate(radius):
return radius > 0
def get_public_api():
all_functions = ['calculate_area', 'calculate_perimeter', '_internal_validate']
public = []
for func in all_functions:
if func in _all_:
public.append(func)
return public
result = get_public_api()
for name in result:
print(name)
Predict the Import Path
Predict Output

Read the code below carefully. It simulates how Python resolves import paths in a nested package. What will it print?

package_tree = {
'myapp': {
'models': ['user', 'product'],
'views': ['home', 'dashboard'],
}
}
def resolve_import(package, subpackage, module):
if package in package_tree:
if subpackage in package_tree[package]:
if module in package_tree[package][subpackage]:
return f'{package}.{subpackage}.{module}'
return 'ImportError'
print(resolve_import('myapp', 'models', 'user'))
print(resolve_import('myapp', 'views', 'dashboard'))
print(resolve_import('myapp', 'utils', 'helpers'))
Refactor Into a Package Registry
Refactor

The code below uses separate variables to track modules in a package. Refactor it into a single class called PackageRegistry with:

  • An __init__ method that sets the package name and an empty dictionary modules
  • A register(module_name, description) method that adds to modules
  • A get_info() method that returns a formatted string showing the package name and each module on its own line in the format - module_name: description
  • The output must match exactly.

    # Messy code: refactor this into a PackageRegistry class
    pkg_name = 'analytics'
    pkg_modules = {}
    pkg_modules['stats'] = 'Statistical functions'
    pkg_modules['charts'] = 'Chart generation'
    pkg_modules['export'] = 'Data export tools'
    info = f'Package: {pkg_name}'
    for mod, desc in pkg_modules.items():
    info += f'\n - {mod}: {desc}'
    print(info)

    Related Tutorials

    Was this tutorial helpful?