输入文件或类文件对象的提示? [英] Type hint for a file or file-like object?

查看:18
本文介绍了输入文件或类文件对象的提示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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')

推荐答案

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

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

来自文档:

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

class typing.IO

Wrapper namespace for I/O stream types.

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

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

这篇关于输入文件或类文件对象的提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆