Modules and packages

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

Package is a directory which contains 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:






Let's consider that file contains:

def get_available_brands():
    return ['chiquita']

class Banana:
    def __init__(self, brand='chiquita'):
        if brand not in get_available_brands():
            raise ValueError('Unkown brand: {}'.format(brand))
        self._brand = brand


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

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 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.