gpt4 book ai didi

python-3.x - Python 类型提示 : How to specify file pointer as an argument?

转载 作者:行者123 更新时间:2023-12-01 13:40:35 25 4
gpt4 key购买 nike

我正在编写一个函数,它将文件指针作为参数并写入它。我想为该参数添加一个类型提示:

def write_some_stuff(fp: _io.TextIOWrapper):
...
_io.TextIOWrapper是什么 type(open(...))给我。

还有什么我应该使用的吗?

最佳答案

您应该使用 typing模块,在 Python 3.5 中引入:
typing.TextIO 最适合这种情况。

Generic type IO[AnyStr] and its subclasses TextIO(IO[str]) and BinaryIO(IO[bytes]) represent the types of I/O streams such as returned by open().



在您的示例中:
from typing import TextIO

def write_some_stuff(fp: TextIO):
...

关于python-3.x - Python 类型提示 : How to specify file pointer as an argument?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40619446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com