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 fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 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.