Dan*_*bbs 10 binary file type-hinting pycharm python-3.x
我使用 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
Run Code Online (Sandbox Code Playgroud)
但是,我的 IDE(PyCharm 2017.2)在我调用的行上给了我以下警告read_file
:
Expected type 'BinaryIO', got 'FileIO[bytes]' instead
Run Code Online (Sandbox Code Playgroud)
我在这里使用的正确类型是什么?PEP484将 定义BinaryIO
为“的简单子类型IO[bytes]
”。难道FileIO
不符合IO
?
这看起来像是 Pycharm 或模块中的错误typing
。从typing.py
模块:
class BinaryIO(IO[bytes]):
"""Typed version of the return of open() in binary mode."""
...
Run Code Online (Sandbox Code Playgroud)
该文档还指定:
这些表示 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
Run Code Online (Sandbox Code Playgroud)