stdlib-module-shadowing (A005) (标准库模块遮蔽)
派生自 flake8-builtins linter。
作用
检查模块是否使用了与 Python 标准库模块相同的名称。
为什么这不好?
将标准库模块名称重复用于模块名称会增加代码阅读和维护的难度,并可能导致不易察觉的错误。读者可能会将第一方模块误认为标准库模块,反之亦然。
标准库模块可以通过 lint.flake8-builtins.allowed-modules
配置选项标记为此规则的例外。
默认情况下,会考虑相对于项目根目录或 src
目录的模块路径,因此顶级的 logging.py
或 logging/__init__.py
将与内置的 logging
模块冲突,但例如 utils/logging.py
则不会。如果将 lint.flake8-builtins.strict-checking
选项设置为 true
,则仅考虑模块名称的最后一个组成部分,因此 logging.py
、utils/logging.py
和 utils/logging/__init__.py
都会触发该规则。
此规则不适用于 stub 文件,因为 stub 模块的名称不受 stub 文件作者的控制。相反,stub 应该旨在忠实地模拟它正在 stub 的运行时模块。
从 Python 3.13 开始,使用与标准库模块相同名称的模块中的错误现在会显示自定义消息。
示例
$ touch random.py
$ python3 -c 'from random import choice'
Traceback (most recent call last):
File "<string>", line 1, in <module>
from random import choice
ImportError: cannot import name 'choice' from 'random' (consider renaming '/random.py' since it has the same name as the standard library module named 'random' and prevents importing that standard library module)