Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
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.
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…
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.
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…
Verify Webhook HMAC Signatures in Python
Create and verify HMAC-SHA256 signatures for webhook payloads using Python's hmac module, protecting against tampering.
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…
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.
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…
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.
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, …
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.
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…
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.
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…
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.
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) &…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.