How to make a python package?
If you are one of those python programmers, who are interested to implement things on one machine and use them on another machine without (or with minimal) changes, with no need to replicate the entire script in every system you work on and lastly when you want that your script to be available to almost everyone then this article might help you achieve you the above mentioned goals!
To demonstrate the process I am going make a simple scrapper that scraps the top most important news from https://apnews.com/hub/ap-top-news and make a python package that returns the top news from the website with just few lines of code!
So let’s get started…
First lets make the scrapper. To do that we will first get sorted with the libraries.
So now the soup is defined let’s make the class with the scrapper function,
Checking whether the scrapper is working or not,
Now let’s just get sorted with all the directories. Based on what I did, we first make a folder with name of the package and inside that we make another folder with the name of the package. The inner folder holds all the codes and matter that the package is suppose to do. and the outermost folder consists of the setup file. (Will explain the setup file in a while.)
Before we move on, lets just save the code that we made above in a .py format
Now comes the init function. This function is present in every package and this function is called when the package is initialized. This function is declared implicitly, and execution happens in the order they are created.
So, lets move on to the setup.py file. This is a python file that will consist of all the package metadata information.
Here is a table from https://dzone.com/articles/executable-package-pip-install which explains some parameters from the above setup.py code.
As we are done with the setup.py file, we will go back to the inner folder with the package name so that we can make DIST folder. DIST is nothing but “distribution”, the compiled code/library, also named public/
or build/
. The files meant for production or public use are usually located here.
Now that we have the dist file lets upload it to the PyPI using twine. Twine is a utility for publishing Python packages on PyPI. To use it, first we install it,
Now comes the final part of the tutorial i.e. uploading the files to PyPI. This step requires you to log in to your PyPI account so do that with correct credentials.
To get the exact overview of how the directory will look, here is the glimpse,
So, we have successfully made our package using these simple steps.
Here is a view from PyPI website:
Now lets test our package,
To conclude, we learned how to make a python package using very simple steps. I hope you liked it.