Reference library

Python Code Samples

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

8 matches
OOP & classes easy

Add property getter setter validation in Python

Shows how to use @property with a setter to validate values before assigning them in a Python class.

property validation oop
Python
class Temperature:
    def __init__(self, celsius=0):
        self._celsius = celsius  # Use underscore to avoid recursion
    
    @property
    def celsius(self):
        """Getter returns the stored value."""
        return self._celsius
    
    @celsius.setter
    def celsius(self, value):
        """Setter valid…
16 0 Open
OOP & classes medium

Borg pattern shared state in Python

Implement the Borg pattern to share state across class instances by assigning a class-level dictionary to each instance's __dict__.

borg monostate shared-state
Python
class Borg:
    _shared_state = {}

    def __init__(self):
        self.__dict__ = Borg._shared_state


class ConfigManager(Borg):
    def __init__(self):
        super().__init__()
        if not hasattr(self, "settings"):
            self.settings = {}

    def set(self, key, value):
        self.settings[key] = va…
14 0 Open
Git + Python easy

Git Signing in Python

Sign and verify Git commits with a mock GPG implementation using HMAC and SHA-256.

git signing hmac
Python
import hashlib
import hmac

class GPGMock:
    def __init__(self, secret_key):
        self.secret_key = secret_key.encode()

    def sign_commit(self, commit_message):
        """Mock GPG signing by computing an HMAC of the commit message."""
        signature = hmac.new(self.secret_key, commit_message.encode(), hash…
13 0 Open
Big data & Spark easy

Z-Order Optimization in Python

A mock concept demonstrating z-order layout optimization by reassigning z-indices based on areas size.

zorder layout optimization
Python
class ZOrderLayout:
    """
    Minimal mock for z-order layout optimization using a stacking score.
    Elements overlap; higher z_index is drawn on top.
    """
    def __init__(self):
        self.elements = []

    def add_element(self, name, area, z_index):
        self.elements.append({"name": name, "area": area…
12 0 Open
Auth & security at scale medium

How to Create and Verify an OpenID Connect ID Token in Python

Generate and validate a mock OpenID Connect ID token (JWT) with HS256 signing using only the Python standard library.

jwt oidc security
Python
import base64
import hashlib
import hmac
import json
import time
from typing import Optional


def b64url_encode(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode("utf-8")


def b64url_decode(data: str) -> bytes:
    padding = "=" * (-len(data) % 4)
    return base64.urlsafe_b64decode(…
14 0 Open
Auth & security at scale medium

How to Sign and Verify with Ed25519 in Python

A minimal Ed25519 sign-and-verify helper that generates a key pair, signs a message, and checks the signature with the cryptography library.

ed25519 cryptography signing
Python
import hashlib
from cryptography.hazmat.primitives.asymmetric import ed25519
from cryptography.hazmat.primitives import serialization

def sign_verify_mock(
    message: bytes,
    private_key: ed25519.Ed25519PrivateKey,
    public_key: ed25519.Ed25519PublicKey
) -> tuple[bool, bytes]:
    signature = private_key.sign…
13 0 Open
Production deployment patterns medium

How to Mock Image Signing Cost in Python

Create a deterministic mock signing cost calculator that predicts resource usage for image signatures before real signing infrastructure is staged.

mock signing cost-model
Python
import math
import struct


def sign_image_cost(image_signature: bytes) -> int:
    """Deterministic mock signing cost based on image signature bytes."""
    if not image_signature:
        raise ValueError("Empty image signature")
    digest = 0
    for byte in image_signature:
        digest = (digest * 31 + byte) &…
14 0 Open
Production deployment patterns medium

How to Mock Kubernetes Services with a ClusterIP Registry in Python

Simulate Kubernetes service discovery by assigning ClusterIP addresses to dataclass-defined services, with JSON export for inspection or testing.

kubernetes clusterip mock
Python
import json
from dataclasses import dataclass, asdict
from typing import Dict, Optional


@dataclass
class Service:
    name: str
    namespace: str
    cluster_ip: str
    selector: Dict[str, str]
    port: int
    target_port: Optional[int] = None


class ClusterIPServiceRegistry:
    _ip_counter = 0

    def __init…
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.