Advanced Python Project: How make a library and upload it to PyPi?

Hello world 👋🏻 my name is Francisco, fcoterroba on the Internet and today I bring you a little post, very advanced this time in Python 🐍

Specifically, given an already found idea, we are going to create and program a library using Python and then share it with the largest language library indexer, the PyPi website.

Currently, next to the post about scheduling a bot in Twitter, seems to me to be one of the most complicated projects, not only because of the programming, but also because several factors must be taken into account. Factors that surely, if you have the most advanced notions about the language, you can do without any problems.

Even so, if you see that this project is too big for you, remember that you have an entire category in my website when you can go project by project learning by 0

Before starting, although later I will explain what it is, I will I recommend visiting a post that I uploaded more than a month ago, in which I explain many of the most used computer terms in our day to day. Since, in this post, you will see words that you probably do not sound a lot. 🤯 You can reed the post here.

I also want to remind you that a few months ago I uploaded a video to my YouTube channel, very interesting, focused on home automation. Specifically, we connect, configure and install a smart light bulb 💡 with which you can change its color, turn it off, turn it on and much more simply by using your mobile phone and/or voice assistants such as Google, Alexa, etc. 👇🏻

Finally, before starting, I wanted to communicate that I have been uploading videos to TikTok for a few weeks. Lately they are from Eurovision since there is little left for it but I leave you here the last one I did today on computers.

@fcoterroba like para la parte 2#fyp #parati #informatica #darkweb #deepweb ♬ She Share Story (for Vlog) – 山口夕依

Before start, what is a library or package in Python?

A library or package in Python (and thus in almost all other programming languages that allow it) is a set of functional implements that help you program.

According to David Zarruk, a programming library is a set of functions that someone wrote somewhere in the world and has made available for anyone to use for free.

I love this definition because I think it's a nice nod to free software and programming in general. Reach any other part of the planet by code.🤩

1️⃣ FIRST STEP 1️⃣

Got an idea.

Before we start the actual programming, we need to get the idea of our library.

It is true that we can simply create a library that returns Hello World, but try to get a little ingenuity out of it and, for example, return a string in binary.

In my case, what I am going to do is a random generator of Spanish names.

2️⃣ SECOND STEP 2️⃣

Obtain all you need

If, for example, you are going to return a string in binary, you don't need anything else and you can go directly to the third step, but in my case, I need official data and sources.

In my case, I needed to download a csv with all the information about Spanish names and surnames and I found this fantastic repository of Marc Boquet

So, I cloned the repository and kept the three main CSVs, the one for men's names, the one for women's names and the one for last names.

3️⃣ THIRD STEP 3️⃣

Let's start to programm

Now that we have everything we need, we create our directory, open it with VSCode, and import the necessary files if we need them.

I am not going to be very explanatory in this project since it is not about how I made this library but about how to make your own, but even so, let's go little by little:

The first thing I did was install the only library I needed to easily work with CSV files: Pandas.

pip3 install pandas

Below I simply wanted to return a random name from the csv of men, for example.

name = pd.read_csv("hombres.csv")
temporal_return = name.sample()["nombre"].to_string(index=False).strip()
print(temporal_return)
# Te devuelve un string así:
# BRYAN ANTHONY

Just like I did with the one for women and the one for surnames.

Then, I wanted to make it more usable and I wanted to give a little more freedom to the user who installed the library, giving him the possibility to request as many names as he wanted.

To do this I had to add a parameter WITH DEFAULT to the function and modify a little the content of itself

def testing(numberNames=1):

    name = pd.read_csv("hombres.csv")
    if numberNames >= 2:
        result_array = []
        for i in range(numberNames):
            temporal_return = name.sample()["nombre"].to_string(index=False).strip()
            result_array.append(temporal_return)
        return result_array
    else:
        result_string = name.sample()["nombre"].to_string(index=False).strip()
        return result_string

print(testing(5))
# Te devuelve un array de este estilo:
# ['FEDERICO JOAQUIN', 'QUNWEI', 'DAVID MANUEL', 'PEDRO BASILIO', 'JAVIER ANIBAL']

Now, the last thing that occurred to me that could become prevalent in the likely uses of the library is the request for FULLNAMES, that is, that the user requests 1 or more names but with their respective surnames, this is how this turned out:

def getRandomMaleName(numberNames=1, fullName=False):

    name = pd.read_csv("hombres.csv")
    if numberNames >= 2:
        result_array = []
        surname = pd.read_csv("apellidos.csv")
        for i in range(numberNames):
            temporal_return = name.sample()["nombre"].to_string(index=False).strip()
            if fullName:
                temporal_return += " "
                temporal_return += surname.sample()["apellido"].to_string(index=False)
                temporal_return += " "
                temporal_return += surname.sample()["apellido"].to_string(index=False)
            result_array.append(temporal_return)
        return result_array
    else:
        result_string = name.sample()["nombre"].to_string(index=False).strip()
        return result_string

print(getRandomMaleName(2, True))
# Esto nos devuelve un array de dos strings con nombres completos
# ['JUAN BENIGNO PASQUAL MORAGREGA', 'ADRIAN ENRIQUE CEDEÑO KENT']

Exactly the same applies to women's names, but of course, what parameters can we add when requesting only surnames?

Well, as before, how many surnames do you want and if you want individual surnames or IN PAIRS.

def getRandomSurname(numberSurnames=1, pairs=False):

    surname = pd.read_csv("apellidos.csv")
    if numberSurnames >= 2:
        result_array = []
        tmp = ""
        for i in range(numberSurnames):
            if pairs:
                tmp = surname.sample()["apellido"].to_string(index=False)
            result_array.append(surname.sample()["apellido"].to_string(index=False)  + " " + tmp)
        return result_array
    else:
        tmp = ""
        if pairs:
            tmp = surname.sample()["apellido"].to_string(index=False)
        return f"{surname.sample()['apellido'].to_string(index=False) + ' ' + tmp}"

print(getRandomSurname(4, True))
# Esto nos devuelve un array de strings con pares de apellidos
# ['AINOZA LAFORET', 'SAID JUAREZ', 'ALFARO RAHHOU', 'LLADOSA CAPOTE']      

4️⃣ FOURTH STEP 4️⃣

Once we have our script working and we have tested it correctly, we are going to start with the process of uploading it to pypi.

But before we upload it we need to have our project directory correctly distributed.

First, we need the file __init__.py which will be the way we indicate how we can call our functions.

It is possible to leave it empty, although it would be more complicated for the user since he would have to import it into his project like this:

from carpeta.archivo import función

To make it more elegant we will have to indicate the RELATIVE PATH well how to write one line per function. In our case:

from .functions import getRandomMaleName
from .functions import getRandomFemaleName
from .functions import getRandomSurname

Next we need the file setup.py which, follows a standard template and is not complex at all. Here is the empty template:

import pathlib
from setuptools import find_packages, setup

HERE = pathlib.Path(__file__).parent

VERSION = 'X.X'
PACKAGE_NAME = 'EL NOMBRE DE TU PAQUETE'
AUTHOR = 'AUTOR'
AUTHOR_EMAIL = 'TU@EMAIL.COM'
URL = 'WWW.TUPAGINAWEB.ES'

LICENSE = 'TIPO DE LICENCIA'
DESCRIPTION = 'DESCRIPCIÓN CORTA EXPLICANDO LA LIBRERÍA'

#Paquetes necesarios para que funcione la libreía. Se instalarán a la vez si no lo tuvieras ya instalado
INSTALL_REQUIRES = [
    'pandas'
]

setup(
    name=PACKAGE_NAME,
    version=VERSION,
    description=DESCRIPTION,
    author=AUTHOR,
    author_email=AUTHOR_EMAIL,
    url=URL,
    install_requires=INSTALL_REQUIRES,
    license=LICENSE,
    packages=find_packages(),
    include_package_data=True
)

Once we have all this we distribute it like this:

A BASE folder which contains setup and another folder which contains init and our functions' file

5️⃣ FIFTH STEP 5️⃣

We are nearing the end but first we will need PACKAGE our library and create the distribution files

To do this we execute the setup.py that we have created as follows:

python3 setup.py sdist bdist_wheel

This will create a folder called dist which will contain our library in format .tar.gz and .whl

6️⃣ SIXTH STEP 6️⃣

Now yes, we are going to proceed to upload our library to the pypi indexer.

To do this, the first thing is to install the twine library with:

pip3 install twine

Once installed we upload the two generated formats and that's it!

twine upload dist/TUARCHIVO.tar.gz dist/TUARCHIVO-py3-none-any.whl

Once done, it will ask you for a username and password for your Pypi profile and voila, you will have created your first library!

You can see my library's repo in GitHub and even see it in pypi!

🏁 End of the post 🏁

And this has been all for today. Thank you for reaching the end, I hope you have served and liked it. See you soon!

You can contribute financially through Paypal. Any amount is well received! 🙂

I also hope you have a great week and see you here soon! A greeting and remember to follow me on the networks as TwitterFacebookInstagram, GitHub, LinkedIn and now too in TikTok. 🤟🏻

sources: crehana.com, antonio-fernandez-troyano-medium.com

Leave a Reply

Your email address will not be published. Required fields are marked *