跳到内容

os-path-samefile (PTH121)

派生自 flake8-use-pathlib linter。

作用

检查对 os.path.samefile 的使用。

为什么这不好?

os.path 提供的较低级别 API 相比,pathlib 为路径操作提供了一个更高级别的 API。如果可能,使用 Path 对象方法(例如 Path.samefile())可以提高可读性,优于 os.path 模块的对应方法(例如 os.path.samefile())。

示例

import os

os.path.samefile("f1.py", "f2.py")

建议改为

from pathlib import Path

Path("f1.py").samefile("f2.py")

已知问题

虽然使用 pathlib 可以提高代码的可读性和类型安全性,但与直接使用字符串的较低级替代方案相比,它的性能可能会降低,尤其是在旧版本的 Python 上。

参考