Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Automatically Detect Weak Passwords from Large Password Lists in Python
This Python script identifies weak passwords from a list by checking length, common patterns, sequential characters, and uniform characters, returning those that fail the security checks.
import re
COMMON_PASSWORDS_FILE = "common_passwords.txt"
def is_weak(password):
# Check length
if len(password) < 8:
return True
# Check for common patterns
if password.lower() in {"password", "123456", "qwerty", "letmein", "admin", "welcome"}:
return True
# Check for sequential c…
How to Detect PII in Documents Using Python
Use regex patterns to automatically detect emails, phone numbers, SSNs, and credit card numbers in text documents.
import re
from typing import List, Dict
def detect_pii(text: str) -> Dict[str, List[str]]:
patterns = {
"email": r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}",
"phone": r"\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}",
"ssn": r"\b\d{3}-\d{2}-\d{4}\b",
"credit_card": r"\b\d{4}[- ]?\d{4}[-…
How to Use Optional Return in Python Instead of Raising Exceptions
A Python function returns None for missing dictionary keys instead of raising KeyError, enabling graceful lookup handling with type hints.
from typing import Optional
def find_user(users: dict, user_id: int) -> Optional[dict]:
"""
Look up a user by ID. Returns the user dict if found,
otherwise returns None instead of raising KeyError.
"""
return users.get(user_id)
def main() -> None:
users = {
1: {"name": "Alice", "ema…
Implement circuit breaker open after failures demo in Python
A minimal CircuitBreaker class that calls a function and automatically 'opens' after a set number of consecutive failures, blocking further calls with a RuntimeError.
import time
from datetime import datetime
class CircuitBreaker:
def __init__(self, threshold=3):
self.threshold = threshold
self.failure_count = 0
self.is_open = False
def call(self, func, *args, **kwargs):
if self.is_open:
raise RuntimeError("Circuit is OPEN")
…
Composable Predicates with the &, |, ~ Operators in Python
Define a reusable Predicate class that combines boolean checks with & (AND), | (OR), and ~ (NOT) operators.
class Predicate:
def __init__(self, func, name=None):
self.func = func
self.name = name or getattr(func, "__name__", "predicate")
def __call__(self, value):
return self.func(value)
def __and__(self, other):
return Predicate(lambda v: self(v) and other(v), f"({self.name} AN…
Composition over Inheritance: How to Build a Wallet Account in Python
Demonstrates composition by wrapping a WalletAccount class in an AuditedWallet decorator-like class to add behavior without changing the original class.
class WalletAccount:
def __init__(self, owner, balance=0.0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self.balance += amount
return self.balance
def withdraw(self, …
How to Implement the Command Pattern with Undo in Python
Python code demonstrating the Command design pattern with undo and redo support using action objects and a history manager.
class Command:
def execute(self):
raise NotImplementedError
def undo(self):
raise NotImplementedError
class AddTextCommand(Command):
def __init__(self, document, text):
self.document = document
self.text = text
def execute(self):
self.document.append(self.tex…
How to Implement the State Pattern in Python
Implement the State design pattern in Python by delegating behavior to state objects, letting a media player change actions dynamically without if-else chains.
class State:
def play(self, player): pass
def pause(self, player): pass
def stop(self, player): pass
class PlayingState(State):
def play(self, player):
return "Already playing"
def pause(self, player):
player.state = PausedState()
return "Pausing playback"
def stop(self…
How to Lazy Load an Expensive Attribute with a Proxy in Python
This code shows a Proxy class that lazily loads an ExpensiveResource only when first accessed, caching it for subsequent uses.
class ExpensiveResource:
def __init__(self, name):
self.name = name
print(f"Expensive resource '{name}' created (e.g., DB connection)")
def use(self):
return f"Using {self.name}"
class Proxy:
def __init__(self, name):
self._name = name
self._resource = None
@p…
How to Use abstractmethod in Python
Define an abstract base class with abstract methods to enforce a common interface across subclasses.
import abc
class Shape(abc.ABC):
@abc.abstractmethod
def area(self):
"""Calculate area of the shape."""
@abc.abstractmethod
def perimeter(self):
"""Calculate perimeter of the shape."""
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
s…
How to implement a Facade class to simplify subsystem calls in Python
Use a Facade class to wrap complex subsystem interactions behind a simple start() method, hiding the details and providing a clean interface.
class CPU:
def freeze(self):
print("CPU: freezing")
def jump(self, position):
print(f"CPU: jumping to {position}")
def execute(self):
print("CPU: executing")
class Memory:
def load(self, position, data):
print(f"Memory: loading '{data}' at {position}")
class HardDr…
Implement the Strategy Pattern with Interchangeable Algorithm Classes in Python
Uses abstract base classes to define a SortStrategy interface, then swaps between BubbleSort and QuickSort at runtime.
from abc import ABC, abstractmethod
from typing import List
class SortStrategy(ABC):
@abstractmethod
def sort(self, data: List[int]) -> List[int]:
pass
class BubbleSort(SortStrategy):
def sort(self, data: List[int]) -> List[int]:
result = data[:]
n = len(result)
for i in…
Python Factory Method: Create Shapes by Type String
A factory method that maps a type string to a concrete shape class and returns an instance, with runtime error handling.
class Shape:
def draw(self):
raise NotImplementedError
class Circle(Shape):
def draw(self):
return "Drawing a circle"
class Square(Shape):
def draw(self):
return "Drawing a square"
class Triangle(Shape):
def draw(self):
return "Drawing a triangle"
class ShapeFact…
Unit of Work Pattern: Track Changes, Commit, and Rollback in Python
This code defines a UnitOfWork class that tracks operations (add) and supports commit to apply changes and rollback to revert them, using a dataclass-based logger.
from dataclasses import dataclass, field
from typing import Any, Callable, List, Tuple
@dataclass
class UnitOfWork:
log: List[Tuple[str, Callable, tuple, dict]] = field(default_factory=list)
def track(self, operation: str, fn: Callable, *args, **kwargs):
self.log.append((operation, fn, args, kwargs)…
Visitor Pattern in Python: Double Dispatch Demo
Demonstrates the Visitor design pattern with double dispatch so operations on Dog and Cat objects are selected at runtime without modifying their classes.
class Animal:
def accept(self, visitor):
visitor.visit(self)
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
class SoundVisitor:
def visit(self, animal):
if isinstance(animal, Dog):
return self.visit_do…
How to Decode a String with Repeated Brackets in Python
Decodes strings with patterns like '3[a]2[bc]' by using a stack to handle nested and repeated bracket groups.
def decode_string(s: str) -> str:
stack = []
current_num = 0
current_str = ""
for ch in s:
if ch.isdigit():
current_num = current_num * 10 + int(ch)
elif ch == "[":
stack.append((current_str, current_num))
current_str = ""
current_num = 0…
How to Detect Hardcoded Secrets in Python Source Code
A Python utility that scans source code for common hardcoded secrets like API keys, passwords, tokens, and AWS credentials using regex patterns.
import re
def detect_secrets(text):
"""Detect potential hardcoded secrets in source code."""
patterns = {
'api_key': r'(?i)(api[_-]?key|apikey)\s*[=:]\s*["\']([^"\']+)["\']',
'password': r'(?i)(password|passwd)\s*[=:]\s*["\']([^"\']+)["\']',
'token': r'(?i)(\b(token|secret)\b)\s*[=:]\s…
Build a Python Tool to Find All API Endpoints on a Website
A Python script that crawls a website, searches for common API endpoint patterns in HTML and JavaScript, and returns all discovered public API URLs.
import re
import requests
from urllib.parse import urljoin, urlparse
from collections import deque
def find_api_endpoints(base_url, max_pages=10):
visited = set()
queue = deque([base_url])
api_endpoints = set()
api_patterns = [
r'/api/[a-zA-Z0-9_/-]+',
r'/v[0-9]+/[a-zA-Z0-9_/-]+',…
How to Generate Git LFS Extension Patterns in Python
This script builds mock Git LFS file patterns for common geospatial extensions and filters them based on compression suffixes.
import itertools
import re
LFS_EXTENSIONS = {".csv", ".geojson", ".tif", ".shp", ".gpkg"}
def build_mock_lfs_pattern(base_name="data_usgs_lidar"):
patterns = []
for ext in sorted(LFS_EXTENSIONS):
for variant in (("", ".lz4"), (".compressed",), (".b", ".a"), ("_v1", ".zip")):
full_pattern …
How to detect secrets in git history with Python
Scan a git history export file for common secret patterns using regex and Python.
import re
from pathlib import Path
def scan_history_for_secrets(history_file: str) -> list:
"""Scan a git history export for potential secrets using regex patterns."""
patterns = {
"AWS Access Key": r"AKIA[0-9A-Z]{16}",
"GitHub Token": r"gh[pousr]_[0-9A-Za-z]{36,255}",
"Private Key": …
How to Create a Mock STS AssumeRole Credentials Dict in Python
Build a realistic AWS STS AssumeRole response dict with temporary credentials, expiry time, and assumed role ARN for local testing.
import json
from datetime import datetime, timedelta, timezone
def mock_sts_credentials(role_arn, session_name, duration=3600):
now = datetime.now(timezone.utc)
expiration = now + timedelta(seconds=duration)
credentials = {
"Credentials": {
"AccessKeyId": "ASIAEXAMPLEACCESSKEY",
…
Dependency Injection in Python for Testability
Inject a config dependency into a service so you can swap a real environment-based config for a fake one in tests.
import os
class Config:
"""Simple config loader that can be easily faked in tests."""
def get(self, key, default=None):
return os.environ.get(key, default)
class UserService:
def __init__(self, config):
self.config = config
def get_timeout(self):
return int(self.config.get(…
Domain Driven Design Aggregate Root Example in Python
Model an Order as an aggregate root with invariants enforced through methods, demonstrating DDD principles in Python.
from __future__ import annotations
from dataclasses import dataclass
from typing import List, Optional
from uuid import uuid4
class Money:
def __init__(self, amount: float, currency: str = "USD"):
self.amount = amount
self.currency = currency
def __add__(self, other: Money) -> Money:
…
Facade Pattern in Python with Mock Simplification
This code demonstrates the Facade pattern by hiding complex subsystem interactions behind a simple start/stop interface, and adds a MockFacade for testing failure scenarios.
class SubsystemA:
def operation_a(self):
return "Subsystem A: ready"
class SubsystemB:
def operation_b(self):
return "Subsystem B: ready"
class SubsystemC:
def operation_c(self):
return "Subsystem C: ready"
class Facade:
def __init__(self):
self._a = SubsystemA()
…
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.