在Python中注释“文件类型”的正确方法

2024-04-26 23:19:28 发布

您现在位置:Python中文网/ 问答频道 /正文

根据PEP 484,在现代版本的Ppython中,可以使用函数注释进行静态类型分析。这是通过打字模块变得容易。在

现在我想知道如何给“文件流”一个“类型提示”。在

def myfunction(file: FILETYPE):
    pass

with open(fname) as file:
    myfunction(file)

我将插入什么作为FILETYPE?在

使用print(type(file))返回{},这一点都不清楚。在

难道没有通用的“文件”类型吗?在


Tags: 模块文件函数版本类型defwith静态
3条回答

要么这样:

from typing import TextIO # or IO or BinaryIO

def myfunction(file: TextIO ):
    pass

这个

^{pr2}$

第二种方法将避免在执行期间导入类。虽然python在执行过程中仍然需要导入TYPE_CHECKING,但是最好避免只为类型提示而导入类:(1)不会执行(只是解析),并且(2)它可以避免循环导入。在

您可以使用typing.IOtyping.TextIOtyping.BinaryIO来表示不同类型的I/O流。引用documentation

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 represent the types of I/O streams such
    as returned by open().

    These types are also accessible directly as typing.IO, typing.TextIO, and
typing.BinaryIO.

我认为您需要^{},“[t]所有I/O类的抽象基类,作用于字节流。”

请注意,这还包括内存中的流,如io.StringIO和{}。有关详细信息,请阅读module ^{}上的文档。在

相关问题 更多 >