As developers, it can be easy to write messy code or for code to bloat and become unwieldy. When this happens you may start to recognise patterns or repeated code. These repeating patterns should be moved into a class for storing these “utility” functions. As your utility classes grow the classes could become a project of their own, but, how would I access my classes?
Before packaging and uploading we check how usable our new utilities are. Write some unit tests in your new project to ensure the project’s functions work as you expect. You can use pip install -e
to emulate installing a package from PyPI. Use this command on your new utilities, and investigate how they work in combination with the original project. Now, you are ready to package your project, upload it, and then access it through PyPI, that is what this tutorial will cover.
There are a couple of pre-requisites you must meet before you are ready to package your software. You need to create a handful of files to package up this project and prepare it for distribution. Create the new files listed below and place them in the project’s Python root directory. Official instructions can be found here (they are useful).
- A tests folder for unit tests
- A setup.py file, the build script for setuptools
- A readme file
- A license file
The next step is to generate your distribution package. You will need to run the following command from the root of the package you are trying to package.
py setup.py sdist bdist_wheel
Note: if you get the error “invalid command bdist_wheel”, check here.
This command should output a lot of text and once completed should generate two files in the dist directory. You can check the output of the command with the following command. This command should tell you if the outputs are valid and able to be uploaded to PyPI.
twine check dist/*
Now to upload our package to PyPI. Run the following command to upload all of the archives under dist.
py -m twine upload --repository pypi dist/*
After the command completes you should see output telling you, you have successfully uploaded your package. You can double-check the upload was successful by checking your account on PyPI for the relevant package.