Reference library

Python Code Samples

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

8 matches
Functions & basics medium

How to Parse Function Signatures in Python with inspect

Extract a function's parameter names, kinds, defaults, annotations, and return type using Python's built-in inspect module.

inspect function signature introspection
Python
import inspect

def example_function(a: int, b: str = "default", *args, c: float = 1.5, **kwargs) -> bool:
    """An example function with various parameter types."""
    return True

def parse_signature(func):
    """Parse a function's signature using the inspect module."""
    sig = inspect.signature(func)
    param…
14 0 Open
Cloud + Python medium

Generate a Mock Presigned URL in Python with HMAC

Build a mock AWS S3 presigned URL using an HMAC-SHA256 signature, mimicking the core SigV4 pattern without cloud SDK dependencies.

aws s3 presigned-url
Python
import hashlib
import hmac
import time
import base64

def generate_presigned_url_mock(secret_key, bucket, object_key, expires_in=3600):
    # Build the canonical request string (simplified AWS SigV4 style)
    timestamp = str(int(time.time()))
    expiry = str(int(time.time()) + expires_in)
    payload = f"GET\n/{buck…
13 0 Open
API design & gRPC medium

Verify Webhook HMAC Signatures in Python

Create and verify HMAC-SHA256 signatures for webhook payloads using Python's hmac module, protecting against tampering.

webhooks hmac security
Python
import hashlib
import hmac
import json

SECRET = b"super-secret-webhook-key"

def create_signature(payload: bytes) -> str:
    return hmac.new(SECRET, payload, hashlib.sha256).hexdigest()

def verify_signature(payload: bytes, signature: str) -> bool:
    expected = create_signature(payload)
    return hmac.compare_dig…
12 0 Open
Auth & security at scale medium

How to Create and Verify HMAC SHA256 API Signatures in Python

Generate and verify HMAC-SHA256 signatures for API requests using Python's hmac, hashlib, and base64 modules.

hmac sha256 authentication
Python
import hmac
import hashlib
import base64
import json
from datetime import datetime, timezone

def create_api_signature(secret_key: str, method: str, path: str, timestamp: str, body: dict = None) -> str:
    """Create HMAC-SHA256 signature for API request."""
    payload = {
        "method": method.upper(),
        "p…
14 0 Open
Auth & security at scale medium

How to Encode and Decode JWT with HS256 in Python

Implement JWT encoding and decoding using HMAC-SHA256 (HS256) with Python's standard library, including signature verification.

jwt hmac authentication
Python
import base64
import hashlib
import hmac
import json


def base64url_encode(data: bytes) -> bytes:
    return base64.urlsafe_b64encode(data).rstrip(b"=")


def base64url_decode(data: str) -> bytes:
    padding = "=" * (-len(data) % 4)
    return base64.urlsafe_b64decode(data + padding)


def encode_jwt(payload: dict, …
16 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
Auth & security at scale medium

How to sign and verify JWT RS256 in Python

Generate RSA keys, create a JWT signed with RS256, verify its signature, and decode the payload using the cryptography library.

jwt rs256 rsa
Python
import json
import time
import base64
import hmac
import hashlib
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric.utils import encode_ds…
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

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.