0

是否有针对为了兼容的多余代码的代码检查?

 2 years ago
source link: https://www.v2ex.com/t/810102
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  Python

是否有针对为了兼容的多余代码的代码检查?

  Contextualist · 1 小时 10 分钟前 · 179 次点击

Python 每个新版本中的标准库会新增一些更便捷的功能,但自己在写库时为了兼容旧版本 Python 就不会使用那些最近新增的功能。例如用 pathlib 删除一个文件,无论文件存在与否:

from pathlib import Path

# 写法一 (Python 3.8+)
Path('file').unlink(missing_ok=True)

# 写法二
try:
    Path('file').unlink()
except FileNotFoundError:
    pass

因为 missing_ok 是 Python 3.8 时新增的选项,所以如果要兼容 Python 3.8 以前的版本,就会用写法二。

在最初库写成一段时间后,可能会决定放弃支持一些 Python 的旧版本。在这个例子里,如果我想放弃对 Python 3.7 的支持,如果有工具能找出现有代码中的可能为写法二的部分,提示我考虑写法一,那对维护工作就省心多了。那有这种代码检查吗?


题外话:分享一个解决我这个问题相反问题的工具:vermin。可以用来检查一个 Python 文件 /包所需要的最低 Python 版本。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK