python / python/cpython

`hashlib` add Protocol for hash-objects

Open
#101,106 8 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib topic-typing type-feature
Dominant language
Python
Stars
77.2k
Forks
36k
PR merge metrics
PR metrics pending

Description

Feature or enhancement

hashlib describes a Protocol for hash objects without implementing it.
The proposal is simply to create a concreate Hash or HashObject protocol that makes it explicit.

Pitch

Using the Buffer Protocol (PEP 688) this should look something like

@runtime_checkable
class Hash(Protocol):
    name: str

    def digest_size(self) -> int:
        """Return the size of the hash in bytes."""

    def block_size(self) -> int:
        """Return the internal block size of the hash in bytes."""

    def update(self, data: Buffer) -> None:
        """Update this hash object's state with the provided string."""

    def digest(self) -> bytes:
        """Return the digest value as a string of binary data."""

    def hexdigest(self) -> str:
        """Return the digest value as a string of hexadecimal digits."""

    def copy(self) -> Self:
        """Return a copy ("clone") of the hash object."""

Having a Protocol class instead of prose makes it clear how exactly a hash-function needs to look like.

A second suggestion would be to change hashlib.algorithms_guaranteed and hashlib.algorithms_available from set[str] to dict[str, type[Hash]] objects.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the hashlib documentation and the referenced PEP 688 Buffer Protocol to compare the proposed Hash interface with existing hash objects. Resolve whether to add a runtime-checkable protocol and whether algorithms_guaranteed and algorithms_available should change from sets to mappings. Done means the accepted API is specified and implemented with appropriate coverage for the supported hash objects.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
cryptography
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.