Skip to content

Improve type annotation compatibility with hashlib - #201

Merged
ifduyue merged 1 commit into
ifduyue:masterfrom
AA-Turner:hashlib-stubs
Oct 18, 2026
Merged

ifduyue merged 1 commit into
ifduyue:masterfrom
AA-Turner:hashlib-stubs

Conversation

@AA-Turner

Copy link
Copy Markdown
Contributor

The hashlib._HashObject stubs take ReadableBuffer in update() and the copy() method returns Self. Per the _typeshed module's README, the ReadableBuffer name can be used freely in stubs.

When running ty check in verbose mode, the following protocol member `copy` is incompatible error is currently reported, which is fixed by this change.

error[invalid-argument-type]: Argument to function `file_digest` is incorrect
  --> bug.py:10:42
   |
10 |     digest = hashlib.file_digest(source, xxhash.xxh128).hexdigest()
   |                                          ^^^^^^^^^^^^^ Expected `str | (() -> _HashObject)`, found `<class 'xxh3_128'>`
info: type `<class 'xxh3_128'>` is not assignable to any element of the union `str | (() -> _HashObject)`
info: ├── type `<class 'xxh3_128'>` has inferred callable type `(input: str | bytes | bytearray | memoryview[int] | array[int] = ..., seed: int = ...) -> xxh3_128`
info: │   └── incompatible return types: `xxh3_128` is not assignable to `_HashObject`
info: │       └── type `xxh3_128` is not assignable to protocol `_HashObject`
info: │           └── protocol member `copy` is incompatible
info: │               └── incompatible return types: `_Hasher` is not assignable to `xxh3_128`
info: └── ... omitted 1 union element without additional context
info: Function defined here
   --> stdlib/hashlib.pyi:161:9
    |
161 |     def file_digest(
    |         ^^^^^^^^^^^
162 |         fileobj: _BytesIOLike | _FileDigestFileObj, digest: str | Callable[[], _HashObject], /, *, _bufsize: int = 262144
    |                                                     --------------------------------------- Parameter declared here
info: rule `invalid-argument-type` is enabled by default

Found 1 diagnostic

The ``hashlib._HashObject`` stubs take ``ReadableBuffer`` in ``update()`` and the  ``copy()`` method returns ``Self``. Per the ``_typeshed`` module's README, the ``ReadableBuffer`` name can be used freely in stubs.
@ifduyue
ifduyue merged commit aba963e into ifduyue:master Oct 18, 2026
@ifduyue

ifduyue commented Oct 18, 2026

Copy link
Copy Markdown
Owner

Thank you!

@AA-Turner
AA-Turner deleted the hashlib-stubs branch October 19, 2026 21:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants