Reference library

Python Code Samples

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

30 matches
System design patterns medium

Microkernel Plug-in Core Mock in Python

Implements a minimal microkernel plug-in core that registers, unregisters, and executes synchronous or asynchronous plugins via a pluggable manager class.

microkernel plugin design-patterns
Python
import json
import abc
import inspect


class MicrokernelCore(abc.ABC):

    def __init__(self):
        self._plugins = {}

    def register(self, name, plugin):
        self._plugins[name] = plugin

    def unregister(self, name):
        return self._plugins.pop(name, None)

    def execute(self, name, *args, **kwa…
13 0 Open
System design patterns medium

Object Pool Pattern for Database Connections in Python

Implements a reusable connection pool with acquire/release and context manager support, mocking database connections with idle reuse and exhaustion handling.

object-pool connection-pool databases
Python
import time
from contextlib import contextmanager
from collections import deque


class ConnectionPool:
    def __init__(self, size=3, max_idle=5):
        self._idle = deque(maxlen=max_idle)
        self._active = set()
        self.size = size

    def _create(self):
        return {"created_at": time.time(), "queri…
12 0 Open
System design patterns medium

Singleton Config Loader in Python with Caution

Implements a singleton config loader in Python that reads JSON config files, but demonstrates the hidden gotcha of shared state across instances.

singleton config design-patterns
Python
import json
from pathlib import Path

class ConfigLoader:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self, config_file="config.json"):
        if not hasattr(self, "loaded…
12 0 Open
System design patterns medium

Template Method Workflow Steps Base Class in Python

Define a reusable workflow skeleton in a base class and let subclasses fill in each step with the Template Method design pattern.

template-method design-patterns abc
Python
from abc import ABC, abstractmethod


class DataPipeline(ABC):
    """Template Method pattern: defines a workflow skeleton."""

    def run(self):
        """Template method - defines the algorithm's structure."""
        result = {"extracted": False, "transformed": False, "loaded": False}
        raw_data = self._ext…
13 0 Open
Microservices patterns medium

CQRS with Separate Read and Write Repositories in Python

Implement CQRS in Python with separate write and read repositories, using commands for mutations and frozen DTOs for queries.

cqrs repositories microservices
Python
from dataclasses import dataclass
from typing import Dict, List, Optional


# --- Write side: commands mutate state ---
@dataclass
class CreateUserCommand:
    id: int
    name: str


class UserWriteRepository:
    def __init__(self) -> None:
        self._store: Dict[int, Dict[str, object]] = {}

    def create(self,…
14 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

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.