Skip to content

hashlib add Protocol for hash-objects  #101106

Open
@randolf-scholz

Description

@randolf-scholz

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions