29 Jan'24
In this article, we are going to learn how to create our very own Python package and access the package's functions (scripts) using the Python interpreter. A Python package is a collection of modules. A module is a file ending in '.py' containing Python functions, classes and variables. These packages can be imported by another module so that the functions can be accessed or it can be used as scripts via the Python command line. For additional context, a collection of packages forms a library. Some of the more established libraries are NumPy (scientific computing), Pandas (data analysis) and Scikit-learn (machine-learning).
This tutorial assumes one has the pre-requisite knowledge on using the command line and an IDE like VS Code.
basic.py 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
geometry.py import math def area_of_rectangle(length, breadth): return length*breadth def area_of_circle(radius): return math.pi*radius**2
from . import basic from . import geometry
At this point, the setup for the package has been created. Let's access it using the Python interpreter.
This sums up the tutorial on creating a Python package. We have learnt how to create a Python package by looking at the directory structure and creating a __init__.py to initialise the construction of the package. We have also used the Python interpreter to import a package and call its modules' functions. With this knowledge, one can proceed to build his or her own package/library of Python functions (scripts) and use them for their work or own projects. Who knows, you may create the next NumPy scientific computing library 😄. Till next time...