How to create your own Python package?

Caiwei Wang
2 min readSep 24, 2021

--

The layout of the files are as followed:

base-myfirstpackage/   
└--myfirstpackage/
└--extras/
├--__init__.py
├--divide.py
├--multiply.py
├--__init__.py
├--add.py
├--subtract.py
├--setup.py

Note: replace “myfirstpackage” name with a unique name for your package, because we will need to use it later.

  1. Create empty files following the layout above.
  2. In the divide.py, multiply.py, add.py and subtract.py file create functions that have the same name as the file name.

For example, inside add.py file we have:

def add(a, b):
return a+b

3. In the first __init__.py file (the one inside the /extras directory), write the following:

import .divide from subtract
import .multiply from multiply

Do the same for the other __init__.py file:

import .add from add
import .subtract from subtract

4. Inside the setup.py file, write:

from setuptools import setup, find_packages

VERSION = '0.0.1' # replaced by 0.0.2 if you want to update
DESCRIPTION = 'My first Python package'
LONG_DESCRIPTION = 'A description'

# Setting up
setup(
name="myfirstpackage",
version=VERSION,
author="FirstName LastName",
author_email="<youremail@email.com>",
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
packages=find_packages(),
install_requires=[], # dependencies

keywords=['python', 'first package'],
classifiers= [
"Development Status :: 3 - Alpha",
"Intended Audience :: Education",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
]
)

5. Before turning this directory into a package, you need to register a PyPi account to get username and password.

6. Go to command line, under the base directory (/base-myfirstpackage), execute:

python setup.py sdist bdist_wheel

Then run

twine upload dist/*

You will be prompted to enter username and password.

You might fail because the package name is not unique (someone has already registered a package with the same name). Change the directory name and the package name inside the setup.py file and try step 6 again.

After succesfully publishing your package, you can get your package by

pip install myfirstpackage

then you can use it like this:

>>> import myfirstpackage as Math
>>> math.add(2,3)
5
>>> import math.extras as MoreMath
>>> MoreMath.multiply(2,3)
6

7. To update your package, make changes to the functions and do the following:

delete the /dist folder

change the version number in the setup.py file, to 0.0.2 for example.

Run step 6 again with the commands. Then upgrade through pip.

pip install package_name --upgrade

--

--

Caiwei Wang

Software developer in the making. Incoming CS Master student at UCSD.