为文件或类似文件的对象键入提示?


105

是否有任何正确的类型提示可用于Python中的文件或类似文件的对象?例如,如何键入此函数的返回值?

def foo():
    return open('bar')

Answers:


144

对于分别以文本模式或二进制模式打开的文件,请使用typing.TextIOtyping.BinaryIO类型。

文档

typing.IO

I / O流类型的包装器名称空间。

这定义了通用类型IO[AnyStr]和别名TextIOBinaryIO用于分别IO[str]IO[bytes]。这些代表I / O流的类型,例如由返回open()


一般而言,也许键入.IO作为类型描述?
雍永

2
这些似乎都不适合我:def f() -> IO: return open('test')在PyCharm中给出“预期类型为'IO',而取为'TextIOWrapper [str]'”。

@Marein怎么样IO[str]
韦恩·沃纳

恐怕还是一样。我还注意到,遍历文件中的行会给出“期望的'collections.iterable'”。

1
转载@ Marein在PyCharm社区2017.2问题:i.imgur.com/Ai4sVQl.jpg
让·弗朗索瓦·科贝特

11

简短的答案:

  • 您需要明确。那from typing import TextIO不只是from typing import *
  • 使用IO意味着文件没有指定什么样的
  • 使用TextIOBinaryIO如果您知道类型
  • 您目前无法指定将其打开以进行写入或对其进行编码。

举个例子:

from typing import BinaryIO

def binf(inf: BinaryIO):
    pass

with open('x') as f:
    binf(f)

给出(PyCharm)的检查错误 Expected type 'BinaryIO', got 'TextIO' instead

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.