python
20 lines · 6 steps
Streaming SHA-256 checksums in Python
Hash a file in fixed-size chunks so you never load the whole thing into memory, then verify it against an expected value.
Explained by
highlit
1import hashlib
2from pathlib import Path
3
4
5def sha256_checksum(path, chunk_size=65536):
6 digest = hashlib.sha256()
7 with open(path, "rb") as f:
8 for chunk in iter(lambda: f.read(chunk_size), b""):
9 digest.update(chunk)
10 return digest.hexdigest()
11
12
13def verify_checksum(path, expected):
14 actual = sha256_checksum(path)
15 if actual != expected.lower():
16 raise ValueError(
17 f"checksum mismatch for {Path(path).name}: "
18 f"expected {expected}, got {actual}"
19 )
20 return True
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Reading a file in chunks keeps memory flat regardless of file size.
- 2The two-argument form of iter() turns a repeated read into a clean sentinel-terminated loop.
- 3Normalizing case before comparing hex digests avoids spurious mismatches.
Related explainers
python
from flask import Blueprint, jsonify, request, abort v1 = Blueprint("users_v1", __name__) v2 = Blueprint("users_v2", __name__)
Versioning a Flask API with Blueprints
api versioning
blueprints
rest
Intermediate
7 steps
php
<?php namespace App\Http\Controllers;
Streaming a filtered CSV export in Laravel
streaming
csv-export
query-builder
Intermediate
9 steps
python
import time import threading from enum import Enum from functools import wraps
Building a circuit breaker in Python
circuit-breaker
resilience
decorators
Advanced
7 steps
python
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector from django.core.cache import cache from django.db.models import F from django.http import JsonResponse
Ranked full-text search in Django
full-text-search
debouncing
caching
Advanced
9 steps
python
import os from datetime import timedelta
Class-based config in a Flask app factory
configuration
app-factory
inheritance
Intermediate
7 steps
python
import time from flask import Flask, g, request
Timing requests with Flask hooks
middleware
request-lifecycle
instrumentation
Intermediate
5 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/streaming-sha-256-checksums-in-python-explained-python-2f18/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.