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

Type hint for a file or file-like object?

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

def foo() -> ???:
    return open('bar')

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

来自 the docs:

class typing.IO

Wrapper namespace for I/O stream types.

This defines the generic type IO[AnyStr] and aliases TextIO and BinaryIO for respectively IO[str] and IO[bytes]. These representing the types of I/O streams such as returned by open().

简短回答:

  • 你需要明确。那是 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)

给出 Expected type 'BinaryIO', got 'TextIO' instead

的检查错误(在 PyCharm 中)