Python mypy 类型提示 shutil.copyfileobj() 具有不兼容的类型 "Union[HTTPResponse, BinaryIO]";预期 IO[任何]

Python mypy Type Hinting shutil.copyfileobj() has incompatible type "Union[HTTPResponse, BinaryIO]"; expected IO[Any]

我收到以下代码的以下 mypy 错误。我怎样才能正确地转换响应对象,以便 mypy 对我将它传递给 shutil.copyfileobj 方法感到满意?

error:Argument 1 to "copyfileobj" has incompatible type "Union[HTTPResponse, BinaryIO]"; expected IO[Any]

以下代码将 Web 请求的响应流式传输到文件。

request = urllib.request.Request(get_file_url, headers=self.data_api_headers)

with urllib.request.urlopen(request) as response:
    with open(export_file_path, 'wb') as out_file:

        shutil.copyfileobj(response, out_file)

这是a bug in typeshed

HTTPResponse 存根没有从 BinaryIO 扩展,因此不被认为是采用 IO[bytes] 的函数的候选者 -- 这已被修复

此修复应该会出现在 mypy 的下一个版本中(如果我猜对了他们的版本方案,应该是 0.620)。或者,您可以 运行 mypy--custom-typeshed-dir 来更快地获得更改