Modules and Packages – Python Examples

Example 1

Problem: Suppose two programmers are collaborating, but working independently to create a single Python program to calculate taxes for a client.

  • The program calculates state and federal taxes for the client.
  • One programmer is working on the state taxes, the other is working on the federal taxes.
  • Each programmer defines a variable “rate” and a function “doCalculation”.
  • When their code is merged into the single file (e.g.,, the duplicate “rate” variables and “doCalculation” functions cause conflicts–the program will not compile.

Solution: Each programmer creates code in a separate file or “module”…

  • Calculates the state tax using a “private” variable for “rate” and a private function for “doCalculation”.
  • Calculates the federal tax using a different private variable for “rate” and a different private function for “doCalculation”.
  • The variables and functions defined in each file are “private” and “distinct” from one another.
  • The main program,, “imports” each module and calls functions inside them using “dot notation”.
import calculate_state
import calculate_federal

state_tax = calculate_state.doCalculation()
federal_tax = calculate_federal.doCalculation()

Example 2

This example illustrates a very simple (“minimal”) generic package and how to use it.

  • Create a directory for this example, e.g., “example”.
  • Create a sub-directory of “example” called “my_package”.  Inside the “my_package” directory, create two files:
    • This file is (typically) empty and just lets the Python compiler know that the directory in which it is located is to be considered to be and is used as a “module”.
    • This file contains the code that makes up the module “my_module” inside the package “my_package”.

Sample contents of “”:

x = 12
def f(y):
return x + 2 * y
  • In the “example” directory, create file “”. This file is a Python program that uses the “my_package” module.

Sample contents of “”:

import my_package.my_module