如何从 typeshed 存根文件导入类型定义?

exh*_*uma 10 python type-hinting

我有一个函数可以抽象出身份验证逻辑,并且可以基于 SHA 或 MD5。除了哈希实现之外,其余代码是相同的。核心部分如下所示:

def hasher(hash_impl, arg1, arg1):
    # do stuff with arg1 and arg2
    hash = hash_impl(arg1)
    return hash.digest()

from hashlib import md5
hasher(md5, b"foo", b"bar")
Run Code Online (Sandbox Code Playgroud)

我的问题是关于类型提示的。

该实现hashlib使用存根文件进行输入。

如何使用该_Hash对象对上述函数进行类型提示?

from ? import _Hash  # <-- How can I access _Hash?
from hashlib import md5, sha

def hasher(hash_impl: _Hash, arg1: bytes, args: bytes) -> bytes:
    ... as above ...
Run Code Online (Sandbox Code Playgroud)

Rap*_*ael 2

我尝试为类型检查器创建一个小函数存根,它似乎可以满足您的要求:

from typing import TYPE_CHECKING, overload
from hashlib import md5

if TYPE_CHECKING:
  from hashlib import _Hash

  @overload
  def hasher(hash_impl: _Hash, arg1: bytes, args: bytes) -> bytes: ...

def hasher(hash_impl, arg1, args):
    # do stuff with arg1 and arg2
    hash = hash_impl(arg1)
    return hash.digest()

print(hasher(md5, b"foo", b"bar"))
Run Code Online (Sandbox Code Playgroud)

但在外部使用该导入if TYPE_CHECKING将导致导入错误!

另外,可调用类型不是更合适吗?md5我只是从存根文件中复制了类型定义。(它还需要一个可选的布尔值,您不会将其传递给该函数,因此我暂时忽略它)。
这样,将在返回后hash键入:_Hashhash_impl

from typing import Callable, TYPE_CHECKING, overload
from hashlib import md5

if TYPE_CHECKING:
  from hashlib import _Hash
  from _typeshed import ReadableBuffer

  @overload
  def hasher(hash_impl: Callable[[ReadableBuffer], _Hash], arg1: bytes, args: bytes) -> bytes: ...

def hasher(hash_impl, arg1, args):
    # do stuff with arg1 and arg2
    hash = hash_impl(arg1)
    return hash.digest()

print(hasher(md5, b"foo", b"bar"))
Run Code Online (Sandbox Code Playgroud)

希望这些有帮助!