【问题标题】:What is the correct way in python to annotate a path with type hints? [duplicate]python中用类型提示注释路径的正确方法是什么? [复制]
【发布时间】:2020-02-20 19:33:10
【问题描述】:

在 python3 中注释这个从文件读取的简单实用程序函数的正确方法是什么? 它应该接受pathlib.Path 对象以及任何其他常见的路径传递方式。

def read_json(path: <TYPE HINT>):
    with open(path, 'rb') as f:
        data = json.load(f)
    return data

在我看来,这个话题似乎在不断变化,我找不到收集这些信息的好地方。我对如何在 python 3.6、3.7 和 3.8 中处理这个感兴趣。

【问题讨论】:

    标签: python type-hinting typing pathlib


    【解决方案1】:

    我假设典型的路径对象是Paths 或strs,因此您可以使用Union

    import pathlib
    import typing
    
    typing.Union[str, pathlib.Path]
    

    【讨论】:

    • 是否有任何地方显示标准函数和类型注释?我找不到,但是“复制open 的注释将是一个很好的答案。
    • open 使用file: _OpenFile 作为注解,也就是联合Union[AnyPath, int]
    • 我用这个PathLike = TypeVar("PathLike", str, pathlib.Path, None)
    • import typing 不在答案中
    猜你喜欢
    • 1970-01-01
    • 2021-10-08
    • 2012-11-30
    • 2011-01-22
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    相关资源
    最近更新 更多