Modules and packages¶

Module is a Python source code file, i.e. a file with .py extension.

Package is a directory which contains __init__.py file and can contain python modules and other packages.

Why to organize your code into modules and packages¶

  • Maintainability
  • Reusability
  • Namespacing
  • People unfamiliar with your project can get a clear overview just by looking at the directory structure of your project
  • Searching for certain functionality or class is easy

How to use¶

Let's use the following directory structure as an example:

food_store/
    __init__.py

    product/
        __init__.py

        fruit/
            __init__.py
            apple.py
            banana.py

        drink/
            __init__.py
            juice.py
            milk.py
            beer.py

    cashier/
        __ini__.py
        receipt.py
        calculator.py

Let's consider that banana.py file contains:

def get_available_brands():
    return ["chiquita"]


class Banana:
    def __init__(self, brand="chiquita"):
        if brand not in get_available_brands():
            raise ValueError(f"Unknown brand: {brand}")
        self._brand = brand

Importing¶

Let's say that we need access Banana class from banana.py file inside receipt.py. We can achive this by importing at the beginning of receipt.py:

from food_store.product.fruit.banana import Banana

# then it's used like this
my_banana = Banana()

If we need to access multiple classes or functions from banana.py file:

from food_store.product.fruit import banana

# then it's used like this
brands = banana.get_available_brands()
my_banana = banana.Banana()

A comprehensive introduction to modules and packages can be found here.