是否有任何正确的类型提示可用于Python中的文件或类似文件的对象?例如,如何键入此函数的返回值?
def foo():
return open('bar')
Answers:
对于分别以文本模式或二进制模式打开的文件,请使用typing.TextIO或typing.BinaryIO类型。
从文档:
类
typing.IOI / O流类型的包装器名称空间。
这定义了通用类型
IO[AnyStr]和别名TextIO和BinaryIO用于分别IO[str]和IO[bytes]。这些代表I / O流的类型,例如由返回open()。
IO[str]?
简短的答案:
from typing import TextIO不只是from typing import *。IO意味着文件没有指定什么样的TextIO或BinaryIO如果您知道类型举个例子:
from typing import BinaryIO
def binf(inf: BinaryIO):
pass
with open('x') as f:
binf(f)
给出(PyCharm)的检查错误 Expected type 'BinaryIO', got 'TextIO' instead