Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

5 matches
System design patterns easy

How to Implement the Repository Pattern in Python with an In-Memory Dict

Stores, retrieves, updates, and deletes user records in memory using a Repository abstraction over a plain dict, isolating data access from business logic.

repository-pattern design-patterns in-memory
Python
class UserRepository:
    def __init__(self):
        self._storage = {}
        self._next_id = 1

    def create(self, name, email):
        user_id = self._next_id
        self._next_id += 1
        self._storage[user_id] = {"id": user_id, "name": name, "email": email}
        return self._storage[user_id]

    def…
11 0 Open
System design patterns easy

How to Mock Hexagonal Architecture Ports and Adapters in Python

Mock an email adapter in a hexagonal architecture with unittest.mock to test business logic in isolation.

hexagonal-architecture unittest-mock dependency-injection
Python
from unittest.mock import Mock

class EmailService:
    def send(self, recipient, message):
        raise NotImplementedError

class OrderProcessor:
    def __init__(self, email_service):
        self.email_service = email_service
    
    def process_order(self, order_id, customer_email):
        # Business logic
   …
15 0 Open
System design patterns easy

How to mock the domain center in an onion architecture in Python

Define a repository interface and an in-memory mock to test domain services without touching infrastructure.

onion-architecture repository-pattern dependency-injection
Python
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Dict, List, Optional


@dataclass
class Order:
    id: int
    customer: str
    items: List[str]
    total: float


class OrderRepository(ABC):
    @abstractmethod
    def find_by_id(self, order_id: int) -> Optional[Order]:
     …
11 0 Open
System design patterns easy

Python MVC Pattern Example (Model-View-Controller)

A minimal, runnable Model-View-Controller (MVC) example in pure Python that separates data, presentation, and logic.

mvc design-pattern architecture
Python
class Model:
    def __init__(self):
        self.data = {"title": "Initial Title", "content": "Initial Content"}

    def get_data(self):
        return self.data

    def update_data(self, title=None, content=None):
        if title:
            self.data["title"] = title
        if content:
            self.data["c…
15 0 Open
Microservices patterns easy

How to Demonstrate the Shared Database Antipattern in Python

This code simulates a shared database where multiple services write and read the same SQLite table, illustrating tight coupling and its pitfalls.

microservices database antipatterns
Python
import sqlite3
from pathlib import Path

def create_shared_db(db_path: Path) -> None:
    """Mock demonstrating the shared database antipattern where multiple
    services access the same database, causing tight coupling."""
    conn = sqlite3.connect(db_path)
    cur = conn.cursor()
    cur.execute("""
        CREATE…
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.