Reference library

Python Code Samples

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

7 matches
Functions & basics easy

Call a Function Dynamically by Name in Python

Use globals() to look up and call a function by its name as a string, with optional arguments.

globals dynamic-dispatch reflection
Python
def greet():
    return "Hello from greet!"

def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

if __name__ == "__main__":
    func_name = "add"
    args = (3, 5)
    
    # Call function dynamically by name from globals
    result = globals()[func_name](*args)
    print(f"{func_name}({', '.join(ma…
13 0 Open
Functions & basics easy

How to Use a Dispatch Table in Python (Map Strings to Functions)

Maps string command names to callable functions in a dictionary, then dispatches calls safely with error handling.

dispatch-table dictionary functions
Python
def add(a, b):
    return a + b


def subtract(a, b):
    return a - b


def multiply(a, b):
    return a * b


def divide(a, b):
    if b == 0:
        raise ValueError("Division by zero")
    return a / b


dispatch = {
    "add": add,
    "subtract": subtract,
    "multiply": multiply,
    "divide": divide,
}


def…
13 0 Open
Functions & basics easy

How to Use singledispatch for Type-Based Overloading in Python

This code demonstrates Python's functools.singledispatch decorator to create functions that behave differently based on the type of their first argument.

singledispatch overloading functools
Python
from functools import singledispatch

@singledispatch
def process(value):
    return f"Unknown type: {type(value).__name__}"

@process.register(int)
def _(value):
    return f"Integer: {value * 2}"

@process.register(str)
def _(value):
    return f"String: {value.upper()}"

@process.register(list)
def _(value):
    re…
12 0 Open
OOP & classes medium

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.

visitor-pattern design-patterns double-dispatch
Python
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…
11 0 Open
Cloud + Python easy

How to Build a Multi-Cloud Config Loader with Provider Switching in Python

Load cloud provider configurations (AWS, Azure, GCP) from JSON files using a provider dispatch pattern in Python.

cloud config json
Python
import json
from pathlib import Path
from dataclasses import dataclass
from typing import Dict, Any


@dataclass
class CloudConfig:
    provider: str
    region: str
    settings: Dict[str, Any]


class ConfigLoader:
    def __init__(self, config_dir: str = "configs"):
        self.config_dir = Path(config_dir)
      …
12 0 Open
System design patterns easy

Route Messages to Handlers with a Python Dict

This code demonstrates a simple message routing pattern using a dictionary to map topic keys to handler functions, with a default handler for unmatched topics.

routing dictionary message-broker
Python
def route_message(message, routing_table):
    """Route a message to the correct handler based on the topic key."""
    topic = message.get("topic", "default")
    handler = routing_table.get(topic, routing_table.get("default"))
    return handler(message)


def handle_orders(message):
    return f"Orders handler proc…
12 0 Open
Observability & SRE easy

How to Route Alerts by Severity in Python

Map alert severity levels to routing targets and simulate dispatching alerts to on-call pages, email, Slack, or logs.

observability alerts routing
Python
def main():
    # Severity levels with corresponding alert routing targets
    routing_map = {
        "critical": "call_page",
        "high": "call_page",
        "medium": "email_team",
        "low": "slack_channel",
        "info": "log_only"
    }

    # Simulated alerts with severity
    alerts = [
        {"na…
12 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.