Learning Management Platform for Written Tutorial Series.

Python 3 Packages - Get to know packages inside and out

Python 3 Packages - Get to know packages inside and out

Python Packages

If you have programmed in other languages such as Java or C#, then you must be familiar with the concept of namespaces. Python packages are similar to namespaces. Before we define what namespaces are, let's look at the kind of problems that they solve.

Let's say we have two independent developers who have created packages that both contain classes that have the same name. This creates a name conflict and can be problematic when using their packages. Working with modules solves this problem. They allow each developer to package their library into a custom namespace.

For example, let's say the two (2) developers are from companies Microsoft and Apple, then the one from Microsoft can package their library into a module called Microsoft while the one from Apple can package their into a module called Apple. This allows both developers to use same class names without creating conflicts.

Topics to be covered

In this tutorial, we will cover the following topics

  • What is a Package?
  • How to create packages
  • Third-party packages

What is a package?

A package is a collection of libraries grouped under a common name that perform a specific task. Packages allow us to break down our application into small manageable parts. A typical python application can have hundreds of files. Having them all in the same directory can be difficult to manage in the long run. With packages, we can create folders that contain the files separated by functionality.

For example, let's say you have a simple database application, you can structure it like so

Python packages

As you can see from the above application, we have three folders inside our project namely bets, games and teams that represent packages and a file app.py in the many directory. This makes our project look net and organized.

How to create packages

In this section, we will convert the directories that we created in the above example into python packages.

To convert a directory into a package, all you have to do is add a file __init__.py into the directory and the intepretor will treat it as a package. The file __init__.py must be added in all the three directories.

We will also add the following files to our directories

  • bets - add pybet.py
  • games - add champions.py
  • teams - add english.py

The code for bets/pybet.py is as follows

def name():
    return 'PyBet'


def version():
    return 3.1

HERE,

  • def name(): defines a function that returns the name of the betting platform
  • def version(): defines a function that returns the version number of the platform

The code for games/english.py is as follows

def get():
    return ['English','French','LaLiga']

HERE,

  • def get(): defines a function that returns a list that contains championships.

The code for teams/english.py is as follows

def get():
    return ['Man U','Arsenal','Chelsea']

HERE,

  • def get(): defines method that returns a list of English teams.

The code for app.py is as follows

from bets.pybet import name,version
import teams.english as teams
import games.champions as champs

print(f'The betting platform is {name()} and the current version is {version()}')

print(f'\nWe have the following registered teams')

for team in teams.get():
    print(team)

print(f'\nWe have the following championships')

for champ in champs.get():
    print(champ)

HERE,

  • from bets.pybet import name,version imports the functions name and version from the pybet module that is located in the bets package.
  • import teams.english as teams imports the english module from the teams package and returns it using as alias teams
  • import games.champions as champs imports the champions module from the games package.
  • name(); version() calls the name and version function that we imported from the package bets
  • teams.get() calls the get function from the package teams
  • champs.get() calls the get function from the champions package.

Executing the above code produces the following results.

The betting platform is PyBet and the current version is 3.1

We have the following registered teams
Man U
Arsenal
Chelsea

We have the following championships
English
French
LaLiga

Third-party packages

Just like the name suggests, these are packages that have been created by other people that we can install via a command line tool and use them in our python application. We use pip to download packages. Read the next lesson to find out more about pip.

In this lesson, we will create a simple application that communicates with an API that returns football data. We will get the championships and print them in a beautiful terminal table.

For us to accomplish this, we will have to download two third-party packages namely

  • football_data_api - this package is used to access data from foot-ball.org. You will need to register for a free account to get the api_key
  • terminaltables - this package allows us to print tables in the terminal.
  • os - this is a built-in python module that we will use to set the api key.

Installing third-party packages

Run the following command to install our two third-party packages

pip install football_data_api
pip install terminaltables

After you have successfully installed the packages, create a new file soccer.py in our sports trading application.

Add the following code

import os
import football_data_api
from terminaltables import AsciiTable

os.environ['FOOTBALL_DATA_API'] = "your_api_key"

data = football_data_api.CompetitionData()

competitions = data.get_available_competitions()

table_data = [
    ['Championship', 'Year']
]

for key in competitions:
    competition = [key,competitions[key]]
    table_data.append(competition)
    table = AsciiTable(table_data)

print (table.table)

HERE,

  • import os; import football_data_api; from terminaltables import AsciiTable imports the modules that we need to use in our application
  • os.environ['FOOTBALL_DATA_API'] = "your_api_key" sets an environment variable using the os module that contains the API key
  • data = football_data_api.CompetitionData() makes an API call
  • competitions = data.get_available_competitions() extracts the competitions from the data object that is returned from the API call. The data returned is in JSON format.
  • table_data = [['Championship', 'Year']] defines a list variable that contains the table data definition. We have set our table headers to Championship and Year.
  • for key in competitions: loops through the JSON object extracting the keys.
  • competition = [key,competitions[key]] creates a list that contains the championship and the year as values.
  • table_data.append(competition) appends the list to the table_data list variable.
  • table = AsciiTable(table_data) creates a terminal table
  • print (table.table) prints the table in the terminal.

Executing the above code produces the following results.

+-----------------------+------+
| Championship          | Year |
+-----------------------+------+
| série a               | 2013 |
| premier league        | 2021 |
| championship          | 2016 |
| european championship | 2018 |
| uefa champions league | 2001 |
| ligue 1               | 2015 |
| bundesliga            | 2002 |
| serie a               | 2019 |
| eredivisie            | 2003 |
| primeira liga         | 2017 |
| primera division      | 2014 |
| fifa world cup        | 2000 |
+-----------------------+------+

Python allows us to create and consume packages that we create ourselves and those created by other people that enhance the functionality of python.

Summary

Packages allow us to group related modules under a unique namespace. The package name must be included in the import statement when we want to use the modules that have been defined in a module. Python allows us to create our own packages as well as use packages that come with python or downloaded from PyPI.

What next?

If you enjoyed this lesson then show us your appreciation by creating a free accounts on our site. As always we appreciate your comments down below. The next lesson shows you how to install third-party packages using pip.


...