Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
How to Implement Slowly Changing Dimension Type 2 History in Python
Build a type-2 slowly changing dimension pipeline that closes old records and opens new ones when customer data changes.
from datetime import datetime, timedelta
def apply_scd_type2(records, current_date):
"""Returns active records after inserting new records with type-2 history."""
history = []
active = {}
for record in records:
key = record["customer_id"]
if key in active:
active[key]["end…
Circuit Breaker Pattern in Python: Closed, Open, and Half-Open States
Implement a circuit breaker with closed, open, and half-open states to prevent repeated calls to failing services and allow recovery after a timeout.
class CircuitBreaker:
def __init__(self, failure_threshold=3, timeout_seconds=5):
self.failure_threshold = failure_threshold
self.timeout_seconds = timeout_seconds
self.state = "closed"
self.failure_count = 0
self.last_failure_time = None
def record_success(self):
…
How to Implement a Circuit Breaker in Python
A Python dataclass that provides circuit breaker logic with closed, open, and half-open states to fail fast on repeated errors.
from dataclasses import dataclass
from datetime import datetime, timedelta
import time
@dataclass
class CircuitBreaker:
failure_threshold: int = 3
timeout_seconds: float = 5.0
failures: int = 0
state: str = "closed"
last_failure: datetime = None
def call(self, func):
if self.state ==…
How to Drain a Connection Pool Before Exit in Python
Gracefully close all pooled sockets using a thread-safe ConnectionPool that drains connections before program exit.
import socket
import threading
import time
import random
class ConnectionPool:
def __init__(self, size=5):
self.pool = []
self.lock = threading.Lock()
self.closed = False
for _ in range(size):
self.pool.append(self.create_connection())
def create_connection(sel…
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.