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., calculate_taxes.py), 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”…

  • calculate_state.py: Calculates the state tax using a “private” variable for “rate” and a private function for “doCalculation”.
  • calculate_federal.py: 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, calculate_taxes.py, “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:
    • __init__.py: 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”.
    • my_module.py: This file contains the code that makes up the module “my_module” inside the package “my_package”.

Sample contents of “my_module.py”:

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

Sample contents of “use_package.py”:

import my_package.my_module
print(my_package.my_module.f(3))