我正在为向接受 os.DirEntry 对象(这些由 os.scandir() 生成)的函数添加类型提示而苦苦挣扎。这是一个接受 DirEntry 对象的简单访问者类:
class FileSystemVisitor:
def visit_dir(self, entry) -> None:
...
def visit_file(self, entry) -> None:
...
FileSystemVisitor 的实例被提供给遍历给定目录子树的 visit() 函数:
def traverse(path: Union[str, pathlib.Path], visitor: FileSystemVisitor) -> None:
for entry in os.scandir(str(path)):
if entry.is_dir(follow_symlinks=False):
visitor.visit_dir(entry)
traverse(entry.path, visitor)
else:
visitor.visit_file(entry)
如何在 FileSystemVisitor.visit_{dir(),file()} 函数中为 entry 参数添加类型提示?为此,我无法导入 DirEntry。
$ python3.5 -c "from os import DirEntry"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: cannot import name 'DirEntry'
我能想到的一件事是编写一个模拟 DirEntry 的虚拟类并将其用于类型提示:
class DirEntryType:
name = None # type: str
path = None # type: str
def inode(self) -> int:
...
def is_dir(self) -> bool:
...
def is_file(self) -> bool:
...
def is_symlink(self) -> bool:
...
def stat(self) -> os.stat_result:
...
但是,为类型提示添加整个类是否很聪明?
如果这很重要,我坚持使用 python3.5,所以 python3.6 的功能不可用。
编辑
正如 avigil 指出的那样在注释中,DirEntry可以在python3.6中导入:
$ python3.6 -c "from os import DirEntry; print(DirEntry)"
<class 'posix.DirEntry'>
因此,向后兼容的解决方案可以是例如:
# typing_utils.py
class DirEntryStub:
name = None # type: str
path = None # type: str
def inode(self) -> int:
raise NotImplementedError('This class is used for type hints only')
def is_dir(self, follow_symlinks: bool = False) -> bool:
raise NotImplementedError('This class is used for type hints only')
def is_file(self, follow_symlinks: bool = False) -> bool:
raise NotImplementedError('This class is used for type hints only')
def is_symlink(self) -> bool:
raise NotImplementedError('This class is used for type hints only')
def stat(self) -> os.stat_result:
raise NotImplementedError('This class is used for type hints only')
现在我可以输入 FileSystemVisitor:
try:
from os import DirEntry
except ImportError:
from typing_utils import DirEntryStub as DirEntry
class FileSystemVisitor:
def visit_dir(self, entry: DirEntry) -> None:
...
def visit_file(self, entry: DirEntry) -> None:
...
请您参考如下方法:
DirEntry 在 posix 模块中用 C 语言实现,但不幸的是直到 3.6 版本才在 python 中公开。参见 bpo-27038对于相关的 python 错误跟踪器问题。
对于较早的版本,您可以按照您的建议进行并将其 stub ,除非您足够关心自己编译 patched version .这实际上不会太难,因为scandir 实现最初来自scandir。可以修补并作为支持标准库实现的依赖项引入的包。
