Python Packages: Structure Code By Bundling Your Modules

We use Python packages to structure and organize our code. When talking about Python packages, people generally mean one of the following:

  1. Packages installable with tools like pip and pipenv are often distributed through the Python Package Index.
  2. Packages in your code base are used to structure and organize your code.

If you’re looking for instructions on how to install packages, you should read the article on installing packages with pip install instead. I can also recommend the article on virtual environments.

This article is about creating your own packages and modules. We’ll look at what packages are, how they are structured, and how to create a Python package. You’ll also discover how packages and modules work together to organize and structure your codebase.

If you are unfamiliar with modules, read my article on Python modules first and then come back here. These two subjects are strongly related to each other.

What are Python packages?

A Python package is a directory that contains zero or more Python modules. Note that a directory is the same as what people call a ‘folder’ on Windows. A Python package can contain sub-packages, which are also directories containing modules. Each package always includes a special file named __init__.py. You’ll learn exactly what this mysterious file is for and how to use it to make your package easier to import.

Structure of a Python package

So, a Python package is a folder that contains Python modules and an __init__.py file. The structure of a simple Python package with two modules is as follows:

── package_name
    ├── __init__.py
    ├── module1.py
    └── module2.pyCode language: plaintext (plaintext)

As mentioned, packages can contain sub-packages. We can use sub-packages to organize our code further. I’ll show you how to do that in more detail in one of the sections below. Let’s first take a look at the structure of a package with sub-packages:

── package_name
    ├── __init__.py
    ├── subpackage1
        ├── __init__.py
        ├── module1.py
    └── subpackage2
        ├── __init__.py
        ├── module2.pyCode language: plaintext (plaintext)

As you can see, packages are hierarchical, just like directories.

What is __init__.py in a Python package?

The __init__.py file is a special file that is always executed when the package is imported. When importing the package from above with import package_name, the __init__.py file is executed.

When importing the nested package from above, with import package_name.subpackage1, the