
PYTHON — Create Python Package
The most dangerous phrase in the language is, ‘We’ve always done it this way.’ — Grace Hopper
Creating a Python Package: A Step-by-Step Guide
In this tutorial, we will go through the process of creating a Python package. A package in Python is a way of organizing related modules into a single directory hierarchy.
To start, we will create a package called helpers with three modules: __init__.py, string.py, and calc.py. In the string.py module, we will add a function called shout() that takes a single string parameter and returns a new string with all the letters in uppercase. In the calc.py module, we will add a function called area that takes two parameters called length and width and returns their product, length multiplied by width.
Once the package and modules are created, we will create a module called main.py in the package_exercises/ folder that imports the string and calc modules. We will then use string.shout() and calc.area() to print the following output: THE AREA OF A 5-BY-8 RECTANGLE IS 40.
Step 1: Create the Package
First, create a new directory for the project and name it package_exercises. Inside this directory, create another directory called helpers. This is where our package will reside.
# Create the package directory
mkdir package_exercises
cd package_exercises
# Create the helpers package directory
mkdir helpersStep 2: Create the Modules
Inside the helpers directory, create the following modules: __init__.py, string.py, and calc.py.
# Create the __init__.py file
touch __init__.py
# Create the string.py file
touch string.py
# Create the calc.py file
touch calc.pyIn the string.py module, define the shout() function as follows:
# string.py
def shout(s):
return s.upper()In the calc.py module, define the area() function as follows:
# calc.py
def area(length, width):
return length * widthStep 3: Create the Main Module
Now, in the package_exercises/ folder, create a module called main.py that imports the string and calc modules.
# main.py
import helpers.string as string
import helpers.calc as calc
# Use string.shout() and calc.area() to print the following output
print(string.shout("The area of a 5-by-8 rectangle is " + str(calc.area(5, 8))))Conclusion
In this tutorial, we have gone through the process of creating a Python package with multiple modules. We created a package called helpers with modules string.py and calc.py, and then used them in a main module called main.py. This package structure allows for better organization and reuse of code.
