How to Build Python Packages

A tutorial on how to build Python packages

George Pipis

--

In this tutorial, we will show you how to build Python Packages. Our goal is to build a Python package called mymath that consists of two modules, such as the basic module that contains three functions and the stats module that contains two functions too.

We have to create a new folder with the name of our package, in this case, “mymath”.

mkdir mymath

Now, within the “mymath” folder, let’s create the “basic” and the “stats” module with file names, basic.py and stats.py respectively.

The “basic.py” file:

def square(number):
"""
This function returns the square of a given number
"""
return number ** 2

def double(number):
"""
This function returns twice the value of a given number
"""
return number * 2

def add(a, b):
"""
This function returns the sum of given numbers
"""
return a + b

The stats.py file:

def mean(numbers):
"""
This function returns the mean of the given list of numbers
"""
return sum(numbers)/len(numbers)

def median(numbers):
"""
This function returns median of the given list of numbers
"""
numbers.sort()

if len(numbers) % 2 == 0:
median1 = numbers[len(numbers) // 2]
median2 = numbers[len(numbers) // 2 - 1]
mymedian = (median1 + median2) / 2
else:
mymedian = numbers[len(numbers) // 2]
return mymedian

Finally, we have to create a file called __init__.py that imports the two modules.

The “__init__.py” file:

from . import basic
from . import stats

The structure of the package is:

.
├── mymath
│ ├── basic.py
│ ├── __init__.py
│ └── stats.py

The package is ready for use. We test it by running one function of each module.

The “test_my_package.py“:

import mymath

print("5+6 is equal to:\n")
print(mymath.basic.add(5,6))

print("\n\nThe mean of 4,5,6 is equal to:\n")
print(mymath.stats.mean([4,5,6]))

--

--

George Pipis

Sr. Director, Data Scientist @ Persado | Co-founder of the Data Science blog: https://predictivehacks.com/