If you’re a beginner or intermediate Python developer, you’ve probably wondered how to publish your own packages so you can share them with friends and colleagues. This post walks through publishing a package on PyPi.
So what is PyPi?
PyPi is the Python Package Index. It’s similar to npm or Homebrew: a place to find packages like Flask, Django, Tweepy, and many more. Most of the packages are open source, and PyPi itself is open source, maintained by developers in their free time.
Writing our first package
This is going to be a simple Python package that calculates the square and cube of a number passed as a command-line argument.
To get started, you need:
- Python installed
pip install twine, which connects to PyPi and publishes our packagepip install docopt, which parses the arguments passed on the command line
Let’s write the code.
"""calc
Usage:
calc.py square <num>
calc.py cube <num>
calc.py (-h | --help)
Options:
-h --help Show this screen.
"""
from docopt import docopt
def square(num):
print(num**2)
def cube(num):
print(num**3)
if __name__ == '__main__':
arguments = docopt(__doc__)
if arguments['square']:
square(int(arguments['<num>']))
elif arguments['cube']:
cube(int(arguments['<num>']))After writing the package, create a file named
setup.py. This file lets us install the package, and PyPi uses it too.We also need a README file with instructions on installing and using the package.
Here’s what
setup.pylooks like. It holds the details about our package.
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="Calculator",
version="0.0.1",
author="Your Name",
author_email="Your Email",
description="Description regarding the package",
long_description=long_description,
long_description_content_type="text/markdown",
url="Project_url",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
)- After creating
setup.py, run this command to generate the package’s.tarfile:
python3 setup.py sdist - That creates a folder named
dist/containing the package. Now upload it with twine:
twine upload dist/ # This will prompt username and password for pypi You’ve published your first PyPi package
If I missed anything, feel free to DM me on Twitter. Feel free to share this with friends and colleagues.