Python函数多类型参数类型提示语法及scan函数path参数标注方法
问题与解决方案
原代码
import os def scan(path) -> os.DirEntry : return os.scandir(path)
该函数的path参数应如何添加正确的类型提示?
根据Python官方文档说明:
path可以是类路径对象。若path为
bytes类型(直接或通过PathLike接口间接实现),每个os.DirEntry的name和path属性类型为bytes;其他情况则为str类型。
也就是说,path可以是表示路径的str或bytes对象,或是实现os.PathLike协议的对象,以下是正确的类型提示写法:
兼容多版本的写法(Python 3.9及更早)
import os from typing import Union, PathLike def scan(path: Union[str, bytes, PathLike[str], PathLike[bytes]]) -> os.DirEntry: return os.scandir(path)
Python 3.10+ 简化写法
import os from typing import PathLike def scan(path: str | bytes | PathLike[str] | PathLike[bytes]) -> os.DirEntry: return os.scandir(path)
说明
PathLike[str]对应会生成字符串类型路径条目的类路径对象,PathLike[bytes]对应生成字节类型路径条目的类路径对象- 上述写法完整覆盖了所有合法输入类型,能被mypy等类型检查工具正确识别
内容的提问来源于stack exchange,提问作者Sun Bear
相关产品推荐
相关产品推荐

