Reference library

Python Code Samples

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

13 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…
13 0 Open
Functions & basics easy

How to Use Keyword-Only Arguments in Python Functions

Define Python functions with keyword-only arguments using the * separator to enforce clarity and prevent positional misuse.

functions keyword-arguments function-signature
Python
def greet(name, *, greeting="Hello", punctuation="!"):
    """Greet someone with a customizable message using keyword-only arguments."""
    message = f"{greeting}, {name}{punctuation}"
    return message

if __name__ == "__main__":
    # Basic call with only the positional argument
    print(greet("Alice"))

    # Al…
15 0 Open
Git + Python easy

Verify Git tag signatures with HMAC in Python

Create and verify deterministic HMAC-SHA256 signatures for git tags using the Python standard library.

hmac git security
Python
import hashlib
import hmac


def sign_tag(tag: str, secret_key: str) -> str:
    """Create a deterministic HMAC signature for a tag."""
    message = tag.encode("utf-8")
    key = secret_key.encode("utf-8")
    return hmac.new(key, message, hashlib.sha256).hexdigest()


def verify_signed_tag(tag: str, signature: str, …
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
Modern tooling easy

How to Type Check a Mock with pyright in Python

Shows how pyright validates a mock function against a TypedDict and Callable signature before runtime.

pyright type-checking mocking
Python
from typing import TypedDict, Callable


class User(TypedDict):
    id: int
    name: str


def get_user_name(user_id: int, get_user: Callable[[int], User]) -> str:
    user = get_user(user_id)
    return user["name"]


def mock_get_user(user_id: int) -> User:
    return {"id": user_id, "name": f"User {user_id}"}


if…
15 0 Open
API design & gRPC easy

How to Validate a JWT Signature in Python with a Mock Secret

Validates a JWT's signature using a mock secret, decoding and handling expired or invalid tokens gracefully.

jwt authentication security
Python
import jwt
import time

SECRET = "mock_secret_key_123"

def validate_token(token):
    try:
        payload = jwt.decode(token, SECRET, algorithms=["HS256"])
        return f"Valid token. Payload: {payload}"
    except jwt.ExpiredSignatureError:
        return "Token expired"
    except jwt.InvalidTokenError:
        …
12 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 easy

How to Generate and Verify HMAC Signatures in Python

Create and validate HMAC-SHA256 signatures with a shared secret key using Python's hmac and hashlib modules.

hmac security cryptography
Python
import hashlib
import hmac

SECRET_KEY = b"pepper-secret-2024"

def generate_hmac(message: str) -> str:
    return hmac.new(SECRET_KEY, message.encode("utf-8"), hashlib.sha256).hexdigest()

def verify_hmac(message: str, received_hmac: str) -> bool:
    expected = generate_hmac(message)
    return hmac.compare_digest(e…
15 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.