Zac*_*030 9 python typing type-hinting pathlib
在从文件读取的python3中注释这个简单的实用程序函数的正确方法是什么?它应该接受pathlib.Path对象以及任何其他传递路径的常见方式。
def read_json(path: <TYPE HINT>):
with open(path, 'rb') as f:
data = json.load(f)
return data
Run Code Online (Sandbox Code Playgroud)
在我看来,这个话题似乎在不断变化,我找不到收集这些信息的好地方。我对如何在 python 3.6、3.7 和 3.8 中处理这个感兴趣。
Chr*_*uer 17
我假设典型的路径对象是Paths 或strs,因此您可以使用Union:
import pathlib
typing.Union[str, pathlib.Path]
Run Code Online (Sandbox Code Playgroud)