What exactly is a Python package?

In Python, the term package has a very specific meaning that may be different than what you initially expect. Furthermore, a deep understanding of what exactly a package is doesn’t only allow you to correct your friends at parties (because you talk about Python at parties… right?), but is integral to being able to separate your code into separate files and subsequently import it correctly.

Before explaining what a package is, we first need to go over a module.

What is a Python module?

As described in the Python docs a module is simply a Python file or script with the file extension .py. You have probably written a module and may not have known it!

In short, a package is a directory that has at least a __init__.py file and most likely some other Python files (or modules if you want to be technically correct). Python packages collect modules and allow you to organize them.

Aside: if you want to be technically correct, a package is a module itself that “can contain submodules or recursively, subpackages. Technically , a package is a Python module with a __path__ attribute.” Source I honestly find this a little confusing, like thinking of a directory as a file that contains other files. While it may be implemented that way, it is easier to think of a package as a collection of modules.

Example of a package

Take the following directory structure of a Python package:

outer_package/      # this is the outermost package
    __init__.py
    inner_package/  # this is a subpackage of outer_package
        __init__.py
        mod1.py     # this is a module 

This example describes a Python package called outer_package that has a subpackage of inner_package and a module called mod1.py. How would you actually use this package in Python? There are a few different ways, you can:

import outer_package
Python

If you want to use everything in outer_package. Or if only need the mod1 module:

from outer_package.inner_package import mod1
Python

Note that the module depth is denoted with . in the import statements.

What is with the __init__.py files?

The __init__.py file serves an important purpose, it is run every time the module is imported and you can also use it to control which functions and variables are exported.

Since Python 3.3+ you actually don’t need an __init__.py file in order for a directory to be considered a package! But it is still good practice to use it, even if it is empty.

Want to keep up to date? Subscribe to the newsletter!

Leave a Reply

Your email address will not be published. Required fields are marked *