May 2, 2020

Packaging python code with pip

Create a directory structure for your python scripts

Your directory structure should take the form

Parent Folder/
    README.md
    LICENSE
    setup.py
    PACKAGE_FOLDER/
    	__init__.py
        .py scripts
        OPTIONAL_SUBFOLDERS/
        	__init__.py
        	.py scripts

We create an empty "__init__.py" file in each of the package folders containing our ".py" scripts.

Use the README.md to provide a general description and instruction related to your package.

Create a LICENSE file containing text for your licensing terms. It is important to include the terms of your license in every package. Any software and piece of work you come across on the internet or elsewhere is copyrighted by default and is the intellectual property of its creator (whether an explicit claim to this effect is made or not is irrelevant). As a result if you wish to share your work for other people to use, you have to explicitly give them the right to do so, by including a license file. If you are open-sourcing your package, you can choose amongst a large number of standard and legally vetted licences (see https://choosealicense.com/ for some examples). Otherwise you can create a custom license and add the text to your LICENSE file (*this is usually not a good idea. Custom texts may not hold up to legally vetted standards, unless you create it with some legal advise).

Create a setup file

Create a setup.py file your projects parent folder. This does all the heavy lifting and creates a distributable package. Add the following contents to the setup.py

import setuptools

with open("README.md","r") as fh:
	long_description = fh.read()

setuptools.setup(
	name="PACKAGENAME-YOUR-USERNAME",
    version="VERSION_NUMBER_HERE",
    author="AUTHOR_NAME_HERE",
    description="SHORT_DESCRIPTION_HERE",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="PROJECT_REPOSITORY_URL_HERE",
    packages=setuptools.findpackages(),
    classifiers=[
    	"Progrmming Language :: Python :: 3",
        "License :: LICENSE_TYPE_HERE",
        "Operating System" :: OS Independent"
        ],
    python_requires='>3.6',
)

Publish the package

You can publish the package on the official pip repository if your project is ready for public release. You can refer to the official instructions as mentioned on https://packaging.python.org/tutorials/packaging-projects/ for this purpose.

In case you are not ready to release the package on pip just yet and are using it for your own work and testing, you can use your own git repository.

To use your own git repository, push the Parent folder for the package and all its content to your own git repository. Then anyone with access to the repository can install the package using

pip install git+https://YOUR_GIT_REPO_URL_HERE

That's that! Now you can maintain your code as an installable package. Happy Coding!