Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Find Most Active Contributors in a Repository with Python
Filter recent commits by date and count the most active contributors using Counter and datetime.
from collections import Counter
from datetime import datetime, timedelta
# Simulated commit data
commits = [
{"author": "Alice", "timestamp": datetime.now() - timedelta(days=1)},
{"author": "Bob", "timestamp": datetime.now() - timedelta(days=2)},
{"author": "Alice", "timestamp": datetime.now() - timedelta…
How to Build an In-Memory CRUD Repository Class in Python
Define a Python Repository class that stores objects in a dictionary and supports create, read, update, delete, and list operations.
class Repository:
def __init__(self):
self._data = {}
def create(self, key, value):
self._data[key] = value
return key
def read(self, key):
return self._data.get(key)
def update(self, key, value):
if key not in self._data:
raise KeyError(f"Key '{ke…
Track GitHub Repository Growth in Python
A Python dashboard that fetches and displays GitHub repository statistics including stars, forks, creation date, and recent star activity using the GitHub API.
import requests
import json
from datetime import datetime, timedelta
def track_repo_growth(owner, repo):
url = f"https://api.github.com/repos/{owner}/{repo}"
headers = {"Accept": "application/vnd.github.v3+json"}
response = requests.get(url, headers=headers)
data = response.json()
name = data…
How to Download All Assets from GitHub Releases in Python
Downloads every asset attached to the latest GitHub release of a repository, saving them locally using the GitHub API and Python's requests and pathlib libraries.
import requests
import os
import zipfile
from pathlib import Path
def download_github_release_assets(owner: str, repo: str, output_dir: str = "release_assets") -> None:
"""Downloads all assets from the latest release of a GitHub repository."""
releases_url = f"https://api.github.com/repos/{owner}/{repo}/relea…
How to Download a GitHub Repository as a ZIP File in Python
Download any public GitHub repository as a ZIP file using the GitHub API and Python's requests and zipfile modules.
import requests
import zipfile
import io
import os
def download_github_repo_as_zip(repo_url, output_path='.'):
"""
Download a GitHub repository as a ZIP file.
Args:
repo_url (str): Full GitHub repository URL (e.g., 'https://github.com/username/repo')
output_path (str): Directory to sa…
Amend Last Commit Message in Python
This script uses subprocess to run `git commit --amend` and update the most recent commit's message in your repository.
import subprocess
import sys
def amend_last_commit_message(new_message: str) -> None:
"""Change the message of the most recent commit."""
result = subprocess.run(
["git", "commit", "--amend", "-m", new_message],
capture_output=True,
text=True,
check=False,
)
if result.…
Find the Commit That Introduced a String in Git History Using Python
Use git log -S with Python subprocess to find the earliest commit that introduced a specific string across your repository history.
import subprocess
import sys
def find_introducing_commit(repo_path: str, search_string: str, file_glob: str = "*") -> str:
"""Find the first commit that introduced a given string in a git repository."""
result = subprocess.run(
["git", "-C", repo_path, "log", "--all", "--oneline", "-S", search_string…
How to Archive a Repository as a ZIP in Python
Create a ZIP archive of a repository directory with a mock export, skipping hidden files and __pycache__ folders.
import zipfile
import io
import os
from pathlib import Path
def archive_repo_mock(repo_path, output_path="repo_archive.zip"):
"""Create a zip archive of a repository directory (mock export)."""
repo = Path(repo_path)
if not repo.exists():
raise FileNotFoundError(f"Repository not found: {repo}")
…
How to Filter Git History to Remove Secret File Entries in Python
A pure-Python mock that filters a repository's history to drop any commit that touched a secret file, so you can plan a cleanup before rewriting Git history.
from pathlib import Path
import json
def filter_history(history, secret_path):
"""Remove entries that touch the secret file."""
return [entry for entry in history if secret_path not in entry["files"]]
if __name__ == "__main__":
repo_history = [
{"commit": "a1b2c3", "message": "Add app", "files": …
How to Mirror a Bare Git Repository Backup in Python
Run a git clone --bare subprocess to create a timestamped bare-repo backup folder with error handling.
import subprocess
import shlex
from pathlib import Path
from datetime import datetime
def mirror_bare_repo(source_url: str, backup_dir: str) -> str:
"""Mirror a bare git repository to a timestamped backup folder."""
backup_path = Path(backup_dir)
backup_path.mkdir(parents=True, exist_ok=True)
timest…
How to Mock Git Cherry-Pick in Python for Tests
Mock the `repo.git.cherry_pick` method with `unittest.mock` to test a Git cherry-pick helper without a real repository.
from unittest.mock import patch, MagicMock
class GitCherryPicker:
def __init__(self):
self.applied_commits = []
def cherry_pick(self, commit_hash, repo):
try:
result = repo.git.cherry_pick(commit_hash)
self.applied_commits.append(commit_hash)
return f"A…
How to Mock Git Stash and Pop in Python
Mock Git stash, apply, and pop operations using unittest.mock so you can test Git automation without touching a real repository.
import git
from unittest.mock import Mock, patch
def stash_and_pop(repo):
"""Mock a stash operation and then pop it back."""
repo.git.stash("save", "WIP: temp changes")
stashed_output = repo.git.stash("list")
# Simulate the stash was applied, then pop
repo.git.stash("apply", "stash@{0}")
…
How to Push Git Tags to a Remote with Python
Push specified git tags (or all tags) to a remote repository using Python's subprocess module with error handling.
import subprocess
import sys
def push_tags_to_remote(remote: str = "origin", tags: list[str] | None = None) -> None:
"""
Push git tags to a remote repository.
If no tags are given, push all local tags.
"""
if tags:
subprocess.run(["git", "push", remote, *tags], check=True)
else:
…
How to Revert a Commit and Create a New Revert Commit in Python
Demonstrates a mock Git repository that creates a new revert commit on top of the current head when reverting an existing commit.
class GitCommit:
"""Minimal mock of a git commit for demonstrating revert behavior."""
def __init__(self, sha, message):
self.sha = sha
self.message = message
self.parent = None
class GitRepository:
"""Mock repository tracking a simple commit chain."""
def __init__(self):
…
How to sync a fork with upstream in Python
Run git fetch and merge commands from Python with subprocess to sync a forked repository with upstream/main.
import subprocess
import sys
def sync_fork_with_upstream():
"""Simulate syncing a forked repo with upstream via git commands."""
# Mock git operations: pretend to fetch from upstream and merge into main
fetch_result = subprocess.run(
["git", "fetch", "upstream"],
capture_output=True, tex…
How to List Pre-commit Hooks from YAML Config in Python
Parse a .pre-commit-config.yaml file with PyYAML and print every hook ID paired with its source repository.
import yaml
pre_commit_config = """
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- repo: https://github.com/psf/black
rev: 23.11.0
hooks:
- id: black
"""
def list_hooks(c…
How to Apply the Clean Architecture Dependency Rule in Python
Demonstrates the dependency rule with a Protocol repository, a use case, and a presenter wired together at a composition root.
from dataclasses import dataclass
from typing import List, Protocol
class Repository(Protocol):
def get_items(self) -> List[str]:
...
@dataclass
class InMemoryRepository:
items: List[str]
def get_items(self) -> List[str]:
return self.items
class UseCase:
"""Application layer depends…
How to Implement the Repository Pattern in Python with an In-Memory Dict
Stores, retrieves, updates, and deletes user records in memory using a Repository abstraction over a plain dict, isolating data access from business logic.
class UserRepository:
def __init__(self):
self._storage = {}
self._next_id = 1
def create(self, name, email):
user_id = self._next_id
self._next_id += 1
self._storage[user_id] = {"id": user_id, "name": name, "email": email}
return self._storage[user_id]
def…
How to mock the domain center in an onion architecture in Python
Define a repository interface and an in-memory mock to test domain services without touching infrastructure.
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Dict, List, Optional
@dataclass
class Order:
id: int
customer: str
items: List[str]
total: float
class OrderRepository(ABC):
@abstractmethod
def find_by_id(self, order_id: int) -> Optional[Order]:
…
How to Mock a GraphQL Query Type in Python
Create a lightweight mock of a GraphQL Query type to simulate repository lookups without a server.
import json
class Query:
def __init__(self):
self.starred_repos = [
{"id": 1, "name": "graphql", "owner": "graphql"}
]
def repository(self, name):
if name == "graphql":
return {"id": 1, "name": "graphql", "stargazerCount": 85000}
return None
if __name…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.