【问题标题】:Python argument type specification for files文件的 Python 参数类型规范
【发布时间】:2022-01-28 23:52:12
【问题描述】:

例如,我知道可以编写一个函数来告知其参数是str

def myfunc(s: str) -> None:

我搜索了typing 的文档,但找不到关于文件作为参数的任何内容。

如何指定如下内容:

def use_file(a_file: ???) -> None:

??? 是一个二进制文件(与open("data", "rb") 创建的一样)?

【问题讨论】:

标签: python-3.x documentation typing


【解决方案1】:

typing 模块为类文件对象提供特定类型。您的问题与this question 重复。

from typing import IO, TextIO, BinaryIO

# Answer to the question
# If your function only accepts files opened in binary mode 
def use_file(a_file: BinaryIO) -> None:
    ...

# If your function only accepts files opened in text mode
def use_file(a_file: TextIO) -> None:
    ...

# If your function accepts files opened in both modes
def use_file(a_file: IO) -> None:
    ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 2011-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多