Day 29: Packaging, Deployment & Git Integration
🐍 Day 29: Packaging, Deployment & Git Integration
1. Learning Objectives
By the end of Day 29, you will be able to:
- Structure a Python project for distribution using
pyproject.toml(orsetup.py) - Create and activate virtual environments to isolate dependencies
- Generate
requirements.txtand install from it - Build and publish a package to PyPI (the Python Package Index)
- Convert a Python script into a standalone executable with PyInstaller
- Initialize and use Git for version control (init, add, commit, push)
- Write a proper
.gitignoreandREADME.mdfor any project
2. Concept Explanation
2.1 Why Packaging and Deployment Matter
So far you've written Python scripts that run on your machine. To share them with others (or deploy them to servers), you need to package them so anyone can install and run them with a single command. Packaging also makes your code reusable and professional.
Key concepts:
| Term | Meaning |
|---|---|
| Package | A directory of Python modules with an __init__.py (or namespace package) |
| Distribution | A versioned archive that can be installed (source distribution or wheel) |
| Dependency | A third‑party library your project needs (e.g., requests) |
| Virtual environment | An isolated Python environment to avoid dependency conflicts |
| PyPI | The Python Package Index – public repository of Python packages |
pip | The standard package installer for Python |
2.2 Virtual Environments – Isolating Project Dependencies
Each project may need different versions of the same library. Virtual environments keep them separate.
Create and activate:
# Create a virtual environment named 'venv' (or '.venv')
python -m venv venv
# Activate (Windows)
venv\Scripts\activate
# Activate (macOS/Linux)
source venv/bin/activate
# Deactivate when done
deactivate
After activation, pip installs packages locally into venv/Lib/site-packages. Your terminal prompt usually shows (venv).
Install dependencies and freeze them:
pip install requests flask
pip freeze > requirements.txt # saves exact versions
Another developer can recreate the identical environment:
pip install -r requirements.txt
2.3 Project Structure for a Package
A minimal distributable Python project:
my_project/
├── my_package/ # The actual package
│ ├── __init__.py
│ └── core.py
├── tests/
│ └── test_core.py
├── README.md
├── pyproject.toml # Modern build configuration
└── requirements.txt
The pyproject.toml file (replaces setup.py for most use cases):
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.backends._legacy:_Backend"
[project]
name = "my_project"
version = "0.1.0"
description = "A short description"
readme = "README.md"
requires-python = ">=3.8"
dependencies = [
"requests>=2.28",
]
[project.scripts]
my-cli = "my_package.cli:main"
This tells pip how to build and install your package. The [project.scripts] section creates a command-line entry point.
Building the distribution:
# Install build tool
pip install build
# Build source and wheel distributions
python -m build
This creates a dist/ folder containing .tar.gz (source) and .whl (wheel) files. You can then upload to PyPI using twine.
2.4 Standalone Executables with PyInstaller
Sometimes you want to give someone a single file that runs without Python installed. PyInstaller bundles your script and all dependencies into an executable.
pip install pyinstaller
# Create a single executable
pyinstaller --onefile my_script.py
# Add an icon (Windows)
pyinstaller --onefile --icon=app.ico my_script.py
The executable appears in the dist/ folder. Note that PyInstaller packages the current Python environment, so run it inside the correct virtual environment.
2.5 Introduction to Git – Version Control
Git tracks changes in your code, lets you collaborate, and provides a safety net (you can revert to any previous version). Every professional developer uses it.
Basic workflow:
# Initialize a new repository in your project folder
git init
# Configure your identity (once per machine)
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
# Add files to staging area
git add .
# Commit with a message
git commit -m "Initial commit"
# Connect to a remote repository (e.g., GitHub)
git remote add origin https://github.com/username/repo.git
# Push your code
git push -u origin main
Common commands:
| Command | Purpose |
|---|---|
git status | See changed files |
git diff | Show line‑by‑line changes |
git log | View commit history |
git branch | List branches |
git checkout -b feature | Create and switch to new branch |
git merge feature | Merge branch into current branch |
git pull | Fetch and merge remote changes |
.gitignore file
A .gitignore tells Git which files to ignore (virtual environments, compiled files, secrets).
# .gitignore
venv/
__pycache__/
*.pyc
dist/
build/
.env
*.egg-info/
README.md
A README is the front page of your project. It should contain:
- Project name and description
- Installation instructions
- Usage examples
- How to contribute
2.6 Packaging Workflow Summary
- Organise your code into a package (with
__init__.py). - Create
pyproject.toml(orsetup.py). - Write a
README.md. - Set up a virtual environment and install dependencies.
- Freeze to
requirements.txt. - (Optional) Build distributions and upload to PyPI.
- (Optional) Create a standalone executable with PyInstaller.
- Initialize Git, add
.gitignore, commit, and push to a remote.
3. Code Examples
Example 1: Simple pyproject.toml for a CLI tool
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.backends._legacy:_Backend"
[project]
name = "weather-cli"
version = "1.0.0"
description = "A simple weather CLI"
readme = "README.md"
requires-python = ">=3.8"
dependencies = [
"requests",
]
[project.scripts]
weather = "weather.cli:main"
Example 2: Building and Installing Locally
# From the project root (where pyproject.toml lives)
pip install -e . # installs in "editable" mode (symlinks, good for development)
# Now the command 'weather' is available system-wide (within the venv)
weather --city Manila
Example 3: Creating an Executable with PyInstaller
# hello.py
print("Hello, world!")
# In terminal:
# pyinstaller --onefile hello.py
# dist/hello.exe (or dist/hello on Linux/macOS)
Example 4: Basic Git Workflow Script
git init
echo "venv/" > .gitignore
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/user/my_project.git
git push -u origin main
4. Hands-On Exercises
Exercise 1: Virtual Environment and Freeze
Create a new project folder. Set up a virtual environment inside it (name it .venv). Activate it, install requests and pytest. Freeze the requirements to requirements.txt. Deactivate, then create a new virtual environment elsewhere and install from requirements.txt to verify reproducibility.
Exercise 2: Package a Simple Module
Create a package mathutils with a module operations.py containing add(a, b) and multiply(a, b). Add an __init__.py that imports these functions. Write a pyproject.toml that makes the package installable. Install it in editable mode and test the import in a Python shell.
Exercise 3: PyInstaller Executable
Take one of your previous scripts (e.g., the to‑do list CLI from Day 7) and turn it into a standalone executable using PyInstaller. Run the generated executable from the dist/ folder to verify it works without Python.
Exercise 4: Git Init and First Commit
Navigate to one of your existing project directories. Initialize a Git repository, create a .gitignore (ignore venv/, __pycache__/, *.pyc), write a brief README.md, stage all files, and commit with a message "Initial commit".
Exercise 5: Create a CLI Entry Point
Take the expense tracker CLI from Day 23. Add a pyproject.toml that declares a script entry point expense-tracker = "main:main". After installing with pip install -e ., verify you can run expense-tracker from the terminal.
5. Applied Challenge Task 🏗️
Package and Deploy the GUI Finance Tracker
Take the Personal Finance Tracker GUI application you built on Day 28. Prepare it for distribution and version control.
Requirements:
Organise the code into a proper package structure:
- Rename the main script to something like
finance_tracker/__main__.py - Ensure all imports use relative or absolute package imports.
- Add
__init__.pyfiles where needed.
- Rename the main script to something like
Create
pyproject.toml:- Set name, version, description.
- List dependencies:
tkinteris built‑in, but includesqlite3note; if you use any external lib (likematplotlib), add it. - Add a console script entry point:
finance-tracker = "finance_tracker.main:main"(or similar).
Generate
requirements.txtfrom your virtual environment (even if just for record‑keeping).Build a standalone executable using PyInstaller with the
--onefileand--windowed(to avoid console window) flags. Test on a machine without Python (or ask a friend).Initialize a Git repository:
- Create a
.gitignoresuitable for Python, Tkinter, and virtual envs. - Write a
README.mdexplaining the app, how to install from source, and how to use the executable. - Commit all files and push to a new GitHub repository (if you have an account).
- Create a
Stretch goals:
- Publish the package to TestPyPI (test.pypi.org) as a practice.
- Add automated tests (from Day 22) and include a
[project.optional-dependencies]section fortest. - Create a simple GitHub Actions workflow that runs tests on push.
6. Brief Review Summary
| Concept | Key Points |
|---|---|
| Virtual environment | python -m venv venv ; isolate dependencies |
requirements.txt | pip freeze > requirements.txt ; reproducible installs |
pyproject.toml | Modern build configuration; defines metadata and scripts |
pip install -e . | Editable install – links your package to the venv |
| PyInstaller | Bundles script + interpreter into a single executable |
| Git | init, add, commit, push – track changes |
.gitignore | Excludes temporary/build files from version control |
| README | Entry point documentation for any project |
7. Preview of Next Topic — Day 30
🎉 The final day: Capstone Project
Tomorrow you will build a real‑world system that integrates everything you've learned:
- Object‑Oriented Programming
- Database (SQLite)
- REST API or GUI (your choice)
- Unit testing with pytest
- Packaging and deployment
- Professional documentation
You’ll have the entire day to design, code, test, and polish your masterpiece. We’ll provide a project brief with several options (e.g., a Library Management System, a Personal Dashboard, a Blog API with a simple frontend) and a rubric for self‑evaluation.
🎯 Your Action Items for Day 29:
- ✅ Complete all 5 exercises
- ✅ Package and deploy the GUI Finance Tracker
- ✅ Push a project to GitHub (create a free account if you haven't)
- ✅ Install a package in editable mode and verify the CLI command works
Comments
Post a Comment
Leave us your comments here...