Reference library

Python Code Samples

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

2 matches
Auth & security at scale medium

How to Hash Passwords and Authenticate Users in Python

A beginner-friendly dataclass-based design that hashes passwords with PBKDF2 and verifies them securely using constant-time comparisons.

security password hashing pbkdf2
Python
import hashlib
import hmac
import secrets
from dataclasses import dataclass
from typing import Optional


@dataclass
class User:
    id: int
    username: str
    password_hash: str
    salt: str


def hash_password(password: str) -> tuple[str, str]:
    salt = secrets.token_hex(16)
    password_hash = hashlib.pbkdf2_…
16 0 Open
Auth & security at scale medium

How to mock Argon2 password hashing in Python

This code demonstrates a mock Argon2 password hasher using HMAC-SHA256 iterations, providing hash and verify methods that mimic Argon2's salted, iterated derivation.

password-hashing security argon2
Python
import hashlib
import hmac
import os


class Argon2Mock:
    def __init__(self, salt_size=16, hash_len=32):
        self.salt_size = salt_size
        self.hash_len = hash_len
        
    def hash(self, password: str, salt: bytes = None) -> str:
        if salt is None:
            salt = os.urandom(self.salt_size)
 …
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.