Skip to content

Unable to use typehint for hashlib.sha256() #2928

@JohnVillalovos

Description

@JohnVillalovos
  • Are you reporting a bug, or opening a feature request?
    Bug

  • Please insert below the code you are checking with mypy,

#!/usr/bin/python3 -ttu
import hashlib
import sys

def main() -> int:
    m = hashlib.sha256()
    print("type:", type(m.digest()))
    print("len:", len(m.digest()))
    print("sizeof:", sys.getsizeof(m))
    print("type:", type(m))
    print(hashlib._hashlib.HASH)
    reveal_type(m)

    return 0

def check_hash(hash_obj: hashlib._Hash) -> hashlib._Hash:
    hash_obj.update(b"0")
    return hash_obj


if '__main__' == __name__:
    sys.exit(main())
  • What is the actual behavior/output?
$ mypy tt.py
tt.py:11: error: Module has no attribute "_hashlib"
tt.py:12: error: Revealed type is 'hashlib._Hash'

$ ./tt.py
Traceback (most recent call last):
  File "./tt.py.save", line 17, in <module>
    def check_hash(hash_obj: hashlib._Hash) -> hashlib._Hash:
AttributeError: module 'hashlib' has no attribute '_Hash'
  • What is the behavior/output you expect?
    That mypy would understand hashlib._hashlib.HASH as a valid type OR that when running the code Python would not complain that there is no 'hashlib._Hash' attribute.

  • What are the versions of mypy and Python you are using?
    mypy 0.701
    Python 3.7.3 on Fedora 29

  • What are the mypy flags you are using? (For example --strict-optional)
    No flags used

When trying to use a type annotation in Python 3.7 for an object created with hashlib.sha256() I can not seem to find a combination that will work with both running it with Python and running mypy to validate the code. Please see above my results.

Note that mypy complains that it does not know about: hashlib._hashlib

And Python has an error as it can't find: hashlib._Hash

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions