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

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

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

Is there any correct type hint to use for a file or file-like object in Python? For example, how would I type-hint the return value of this function?

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

回答 0

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

文档

typing.IO

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

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

Use either the typing.TextIO or typing.BinaryIO types, for files opened in text mode or binary mode respectively.

From 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().


回答 1

简短的答案:

  • 您需要明确。那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

The short answer:

  • You need to be explicit. That is from typing import TextIO not just from typing import *.
  • Use IO to mean a file without specifying what kind
  • Use TextIO or BinaryIO if you know the type
  • You cannot currently specify it be opened for write or its encoding.

As an example:

from typing import BinaryIO

def binf(inf: BinaryIO):
    pass

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

gives an inspection error (in PyCharm) of Expected type 'BinaryIO', got 'TextIO' instead


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。