简体   繁体   English

输入文件或类文件对象的提示?

[英]Type hint for a file or file-like object?

Is there any correct type hint to use for a file or file-like object in Python?是否有任何正确的类型提示可用于 Python 中的文件或类文件对象? For example, how would I type-hint the return value of this function?例如,我将如何键入提示此函数的返回值?

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

Use either the typing.TextIO or typing.BinaryIO types, for files opened in text mode or binary mode respectively.分别对以文本模式或二进制模式打开的文件使用typing.TextIOtyping.BinaryIO类型。

From the docs :文档

class typing.IOtyping.IO

Wrapper namespace for I/O stream types. I/O 流类型的包装命名空间。

This defines the generic type IO[AnyStr] and aliases TextIO and BinaryIO for respectively IO[str] and IO[bytes] .这分别为IO[str]IO[bytes]定义了泛型类型IO[AnyStr]和别名TextIOBinaryIO These representing the types of I/O streams such as returned by open() .这些表示 I/O 流的类型,例如open()返回的。

The short answer:简短的回答:

  • You need to be explicit.你需要明确。 That is from typing import TextIO not just from typing import * .那是from typing import TextIO而不仅仅是from typing import *
  • Use IO to mean a file without specifying what kind使用IO表示一个文件而不指定什么类型
  • Use TextIO or BinaryIO if you know the type如果您知道类型,请使用TextIOBinaryIO
  • 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给出Expected type 'BinaryIO', got 'TextIO' instead的检查错误(在 PyCharm 中), Expected type 'BinaryIO', got 'TextIO' instead

您可以分别对文本文件和二进制文件使用TextIO和BinaryIO。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM