Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

11 matches
Strings & text easy

How to Highlight Search Terms in Python Text

Highlights all case-insensitive occurrences of a search term in a string by wrapping them in markers.

string search highlight
Python
def highlight_search_term(text: str, term: str) -> str:
    """Highlight all occurrences of term in text using terminal-style markers."""
    if not term:
        return text

    term_lower = term.lower()
    result = []
    i = 0

    while i < len(text):
        # Check if the term starts at position i (case-insens…
11 0 Open
Strings & text easy

How to wrap long text to a specified width in Python

Uses Python's textwrap.fill to wrap a long string to a specified width at word boundaries, preserving readability in console output or logs.

textwrap text wrapping formatting
Python
import textwrap

text = """This is a long piece of text that definitely exceeds the width limit
if we try to print it on a single line without any wrapping applied."""

wrapped = textwrap.fill(text, width=40)

print(wrapped)
11 0 Open
Functions & basics easy

Format CLI help text in Python

Build a readable usage string for a command-line tool, aligning flags and wrapping descriptions with the textwrap module.

cli textwrap formatting
Python
import textwrap


def format_help(command_name: str, description: str, options: list[tuple[str, str]]) -> str:
    """Format CLI help text into a readable usage string."""
    header = f"Usage: {command_name} [OPTIONS]"
    lines = [header, "", description, "", "Options:"]

    for flag, help_text in options:
        …
12 0 Open
Errors & debugging easy

How to Wrap a Low Level Error in a Higher Level Exception in Python

Wrap low-level exceptions in a higher-level exception while preserving the original cause with the `from` keyword.

exception-chaining error-handling wrapping
Python
class LowLevelError(Exception):
    pass

class HighLevelError(Exception):
    pass

def low_level_operation():
    raise LowLevelError("storage drive failed to respond")

def high_level_operation():
    try:
        low_level_operation()
    except LowLevelError as e:
        raise HighLevelError(f"database operation…
13 0 Open
OOP & classes easy

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.

composition design-patterns oop
Python
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, …
13 0 Open
OOP & classes easy

How to Implement the Decorator Pattern in Python to Add Behavior

This Python code demonstrates the decorator pattern by wrapping a function to add logging behavior without modifying the original function.

decorator pattern logging
Python
import functools

def logger(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with {args} {kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

@logger
def add(a, b):
   …
11 0 Open
Algorithms & data structures easy

Pair Elements with Next Cyclic Neighbor in Python

Create tuples pairing every element with its next element, wrapping around to the first element for the last one.

pairs cyclic list
Python
def cyclic_pairs(lst):
    if not lst:
        return []
    return [(lst[i], lst[(i + 1) % len(lst)]) for i in range(len(lst))]


if __name__ == "__main__":
    sample = [1, 2, 3, 4, 5]
    result = cyclic_pairs(sample)
    print(result)
15 0 Open
API design & gRPC easy

How to Implement RBAC Permission Checks with a Route Decorator in Python

Build a reusable Python decorator that checks a user's role against allowed roles and raises a custom PermissionError when access is denied.

decorator rbac permissions
Python
from functools import wraps
from enum import Enum

class Role(Enum):
    ADMIN = "admin"
    MODERATOR = "moderator"
    USER = "user"

class PermissionError(Exception):
    pass

def require_role(*allowed_roles):
    def decorator(func):
        @wraps(func)
        def wrapper(user_role, *args, **kwargs):
          …
13 0 Open
Reliability & rate limiting easy

How to Inject Random Latency for Chaos Testing in Python

Mock unreliable services by wrapping functions with a decorator that adds random network-like delays before execution.

chaos-engineering decorators latency
Python
import random
import time
from functools import wraps

def inject_latency(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        latency = random.uniform(0.1, 0.5)
        print(f"Injecting {latency:.3f}s latency...")
        time.sleep(latency)
        return func(*args, **kwargs)
    return wrapper

@inje…
12 0 Open
Microservices patterns easy

How to Use the Adapter Pattern to Mock a Legacy System in Python

This code demonstrates the Adapter pattern, allowing a modern interface to interact with a legacy system by wrapping its outdated method.

adapter-pattern design-patterns legacy
Python
class LegacySystem:
    def legacy_method(self, data):
        return f"Legacy processed: {data}"

class ModernInterface:
    def process(self, data):
        raise NotImplementedError

class Adapter(ModernInterface):
    def __init__(self, legacy):
        self.legacy = legacy

    def process(self, data):
        re…
13 0 Open
Auth & security at scale medium

How to Mock KMS Envelope Encryption in Python

Demonstrates a minimal mock of AWS KMS envelope encryption flow with AES-GCM data key wrapping and unwrapping.

kms encryption aes-gcm
Python
import base64
import json
import os
import hashlib


class MockKMS:
    """Minimal mock of AWS KMS envelope encryption flow."""

    def generate_data_key(self):
        # Simulate KMS returning a plaintext and encrypted data key
        plaintext_key = os.urandom(32)
        encrypted_key = hashlib.sha256(plaintext_k…
13 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.