Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Quarantine Suspicious Files in Python
Move files with suspicious extensions to a quarantine folder using pathlib and shutil for safe isolation.
import shutil
import os
from pathlib import Path
def quarantine_files(source_dir, quarantine_dir, suspicious_extensions):
"""
Move files with suspicious extensions to a quarantine folder.
Returns list of moved files.
"""
source_path = Path(source_dir)
quarantine_path = Path(quarantine_dir)
…
How to Use threading.local for Per-Thread Data in Python
Use threading.local to keep thread-specific data — each thread gets its own copy of the attribute, so values don't leak between threads.
import threading
import time
local_storage = threading.local()
def worker(name):
local_storage.name = name
time.sleep(0.1)
print(f"Thread {threading.current_thread().name}: {local_storage.name}")
if __name__ == "__main__":
threads = []
for i in range(3):
t = threading.Thread(target=worke…
How to Mock Hexagonal Architecture Ports and Adapters in Python
Mock an email adapter in a hexagonal architecture with unittest.mock to test business logic in isolation.
from unittest.mock import Mock
class EmailService:
def send(self, recipient, message):
raise NotImplementedError
class OrderProcessor:
def __init__(self, email_service):
self.email_service = email_service
def process_order(self, order_id, customer_email):
# Business logic
…
Implement Bulkhead Thread Pool Isolation in Python
Create isolated thread pools with a bulkhead pattern to protect different services from cascading failures.
import threading
import time
import random
from concurrent.futures import ThreadPoolExecutor
class Bulkhead:
"""Simple bulkhead isolation: separate thread pools for different tasks."""
def __init__(self, max_workers):
self.executor = ThreadPoolExecutor(max_workers=max_workers)
self.active = …
How to Implement Namespaced Cache Keys for Tenant Isolation in Python
Build a tenant-aware cache wrapper that prefixes keys with tenant and namespace, and test it with mocks.
from keyvaluestore import SimpleCache
from unittest.mock import patch
class TenantCache(SimpleCache):
def __init__(self, tenant_id, namespace="default"):
super().__init__()
self.tenant_id = tenant_id
self.namespace = namespace
def _key(self, key):
return f"tenant:{self.tenant_…
How to Expand a Contract and Migrate Data in Python
Expand an old data contract by renaming fields and adding defaults, then migrate to a final version with deepcopy isolation.
import json
from copy import deepcopy
# Mock data representing a user record (old contract)
old_contract = {
"id": 1,
"name": "Alice",
"email": "alice@example.com",
"age": 30,
"status": "active"
}
# Expanded contract: adds fields with defaults and renames some fields
expand_rules = {
"id": "u…
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.