New
List
Guide
Editing upload 'monkey-pony-lion'
Content
import hashlib import json from datetime import datetime, date, time from functools import wraps def canonicalize(obj): """Recursively convert data to deterministic, JSON-serializable form.""" if isinstance(obj, dict): return {k: canonicalize(obj[k]) for k in sorted(obj)} elif isinstance(obj, list): return [canonicalize(v) for v in obj] elif isinstance(obj, set): return sorted(canonicalize(v) for v in obj) elif isinstance(obj, (datetime, date, time)): return obj.isoformat() else: return obj def with_stable_hash(cls): """Decorator that adds a stable_hash() method to a Pydantic model.""" def stable_hash(self): # Pydantic v2: model_dump() ; v1: dict() data = canonicalize(self.model_dump() if hasattr(self, "model_dump") else self.dict()) json_bytes = json.dumps(data, separators=(",", ":")).encode("utf-8") return hashlib.sha256(json_bytes).hexdigest() cls.stable_hash = stable_hash return cls ---------- from pydantic import BaseModel from datetime import datetime @with_stable_hash class User(BaseModel): name: str age: int tags: set[str] created: datetime --- from functools import cached_property def with_stable_hash(cls): @cached_property def stable_hash(self): data = canonicalize(self.model_dump() if hasattr(self, "model_dump") else self.dict()) json_bytes = json.dumps(data, separators=(",", ":")).encode("utf-8") return hashlib.sha256(json_bytes).hexdigest() cls.stable_hash = stable_hash return cls
MicroBin
by Dániel Szabó and the FOSS Community. Let's keep the Web
compact
,
accessible
and
humane
!