【问题标题】:Correct type for binary file-like object二进制文件类对象的正确类型
【发布时间】:2018-01-27 16:07:44
【问题描述】:

我使用 Python 类型提示定义了以下函数:

from typing import BinaryIO

def do_something(filename: str):
    my_file = open(filename, "rb")
    read_data(my_file)

def read_data(some_binary_readable_thing: BinaryIO):
    pass

但是我的 IDE (PyCharm 2017.2) 在我调用 read_file 的行上给了我以下警告:

Expected type 'BinaryIO', got 'FileIO[bytes]' instead

我在这里使用的正确类型是什么? PEP484BinaryIO 定义为“IO[bytes] 的简单子类型”。 FileIO不符合IO吗?

【问题讨论】:

    标签: python-3.x file binary pycharm type-hinting


    【解决方案1】:

    这看起来像是 Pycharm 或 typing 模块中的错误。来自typing.py 模块:

    class BinaryIO(IO[bytes]):
        """Typed version of the return of open() in binary mode."""
        ...
    

    documentation 还指定:

    这些代表I/O流的类型,比如open()返回的。

    所以它应该按说明工作。目前,一种解决方法是显式使用FileIO

    from io import FileIO
    
    def do_something(filename: str):
        my_file = open(filename, "rb")
        read_data(my_file)
    
    def read_data(some_binary_readable_thing: FileIO[bytes]):
        pass
    

    【讨论】:

      猜你喜欢
      • 2010-10-11
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      • 2014-12-08
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2021-07-25
      相关资源
      最近更新 更多