The Basics - 1
What is a package in Python?
Hold up, isn’t this one of those terms we use synonymously with other terms like library, module etc?
Well no. Let’s learn what the differences are -
Module
A module can be any file with a .py extension. For example -
hero.py
1def hero():
2 return f"Anyone"
3
4print(hero())
This module when executed using python hero.py returns the string “Anyone”.
Because a hero can be Anyone.
Package
A package is typically a collection or a group of related modules. The indication of a package is via an empty init.py file alongside the rest of the package’s modules.
E.g.
top_level_folder
|- cloud_functions
|- __init__.py
|- gcp.py
|- aws.py
|- azure.py
|- main.py
Now if __init.py__ is empty and gcp.py looks something like this -
1from google.cloud import storage
2from googleapiclient import discovery
3from google.oauth2 import service_account
4
5
6class GCPClient:
7 def __init__(self, credentials_file):
8 self.credentials = service_account.Credentials.from_service_account_file(credentials_file)
9 # More instance variables
10
11 # GCS: Upload file to Google Cloud Storage
12 def upload_file_to_gcs(self, bucket_name, source_file_name, destination_blob_name):
13 bucket = self.storage_client.bucket(bucket_name)
14 blob = bucket.blob(destination_blob_name)
15 blob.upload_from_filename(source_file_name)
16 print(f"File {source_file_name} uploaded to {destination_blob_name}.")
17
18# ... Other functions
Then in main.py, the functions in gcp.py can be accessed as -
1from cloud_functions.gcp import *
2
3upload_file_to_gcs(...)
Here cloud_functions is a package - a package of related cloud functionalities.
Library
A library in common parlance is a building where books are housed. A library in Python similarly is a (usually installable) collection of packages and modules.
For example, the popular data manipulation tool pandas is a library.
Like the way to make a package is by way of an empty __init.py__ file, the way to make a Python library is by providing a way to package the set of packages and modules using something called a setup.py file.
Here’s a sample Python library’s structure -
superheroes/
├── dc/
│ ├── __init__.py # This makes it a package
│ └── batman.py # Python file in dc package
└── setup.py # Setup script for distribution
└── README.md # Most packages have a README to provide context about it
A typical setup file looks like -
1# setup.py
2
3from setuptools import setup, find_packages
4
5setup(
6 name="superheroes", # The name of our library
7 version="0.1", # Release version
8 author="EverythingPython",
9 author_email="everythingpython0@gmail.com",
10 description="A package to chronicle all Superheroes",
11 packages=find_packages(), # Automatically find packages in the directory
12 install_requires=[], # List dependencies here if any
13)
A package is installed using a package installer like pip.