Python Packages

Lesson 12 of 16 • 10 XP

Keep your place in this quest

Log in or sign up for free to subscribe, follow lesson progress, and access more learning content.

Now that you know what modules are, let’s take it one step further and talk about packages in Python.

A package is a way to group related modules together in a single, organized folder.
If modules are like individual tools, a package is like a toolbox containing multiple tools neatly arranged.


What Makes a Package?

A package is simply a directory that contains:

  • An __init__.py file (even if it’s empty)
  • One or more module files (.py)
  • Optional sub-packages (folders with their own __init__.py)

The __init__.py file is executed when the package is imported.
It can be used to set up default imports, define variables, or run initialization code.

Example Package Structure

Here’s a simple package called mypackage:

mypackage/
**init**.py
module1.py
module2.py

Using __init__.py for Default Imports

Inside __init__.py, you can choose what parts of the package are directly available when someone imports it.

Example — in mypackage/__init__.py:

from .module1 import my_function
from .module2 import another_function

This way, when you import the package, you can use these functions without having to import each module individually.

Importing and Using the Package

Example — in another Python file:

import mypackage

mypackage.my_function()
mypackage.another_function()

Here:

  • import mypackage runs the code in __init__.py.
  • The functions from module1 and module2 are available because we imported them in __init__.py.
TIP: You can still import specific modules from a package if you prefer:
from mypackage import module1

Why Use Packages?

Packages help you: • Organize your code into logical sections. • Reuse related modules across different projects. • Scale your programs as they grow in complexity.

Whether you’re working on a large application or just keeping your code tidy, packages are a cornerstone of clean, maintainable Python projects.


Next, we’ll learn more about importing modules and packages using different techniques — and when to choose each one.