Reference library

Python Code Samples

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

7 matches
Dictionaries & sets easy

How to Use MappingProxyType to Create Immutable Dict Views in Python

Create a read-only, immutable view of a dictionary using MappingProxyType from the types module, while the original dict stays mutable.

mappingproxytype dict immutable
Python
from types import MappingProxyType

config = {"debug": True, "port": 8080}

# Create an immutable read-only view of the dict
read_only_config = MappingProxyType(config)

print(f"Read-only value: {read_only_config['debug']}")
print(f"Dict is mapping: {isinstance(read_only_config, dict)}")

# Original dict can still be …
13 0 Open
OOP & classes medium

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.

lazy-loading proxy properties
Python
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…
15 0 Open
Cloud + Python easy

How to Parse an AWS API Gateway Proxy Event in Python

Extract and parse common fields from a mock API Gateway proxy event, turning the JSON body into a native Python dict.

aws lambda api-gateway
Python
import json
from typing import Any, Dict, Optional


def parse_proxy_event(event: Dict[str, Any]) -> Dict[str, Any]:
    """Extract and parse common fields from an API Gateway proxy event."""
    body = event.get("body", "")
    if isinstance(body, str):
        body = json.loads(body) if body else {}
    elif body is…
13 0 Open
System design patterns medium

How to Build a Sidecar Logging Proxy in Python

Wrap any object with a proxy that transparently logs every method call, arguments, return value, and execution time to a file — mimicking a sidecar pattern.

proxy logging sidecar
Python
import logging
import time
from datetime import datetime


class LoggingProxy:
    """Sidecar-style proxy that logs all calls to a wrapped object."""

    def __init__(self, target, log_file="proxy.log"):
        self._target = target
        logging.basicConfig(
            filename=log_file,
            level=loggin…
15 0 Open
System design patterns medium

Lazy loading with a proxy in Python: defer expensive service creation

A lazy proxy defers creating an expensive service object until its method is first called, then caches it for reuse.

proxy lazy-loading design-patterns
Python
import time
import random


class ExpensiveService:
    def __init__(self, name):
        self.name = name
        print(f"Creating expensive service: {self.name}")

    def fetch_data(self):
        time.sleep(1)
        return f"Data from {self.name}: {random.randint(1, 100)}"


class LazyProxy:
    def __init__(sel…
15 0 Open
Microservices patterns easy

How to Mock a Service Mesh Sidecar Proxy in Python

Simulate a service mesh sidecar proxy with route registration, service discovery, and request proxying using a simple Python class.

sidecar-proxy service-mesh microservices
Python
class SidecarProxy:
    def __init__(self, name):
        self.name = name
        self.routes = {}
        self.services = {}
        self.requests_processed = 0

    def register_service(self, service_name, address, port):
        self.services[service_name] = f"{address}:{port}"

    def add_route(self, path, servi…
14 0 Open
Microservices patterns easy

How to Mock an Ambassador Edge Proxy in Python

Build a lightweight mock Ambassador edge proxy with Python's http.server that responds to health and user endpoint requests for local development and testing.

ambassador mock http-server
Python
import http.server
import json
import urllib.parse
import threading

class AmbassadorProxyHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        parsed = urllib.parse.urlparse(self.path)
        if parsed.path == "/health":
            self.send_response(200)
            self.send_header("Content-T…
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.