如何在Cookiecutter模板中抑制mypy的无效包名错误?
问题背景
我正在为Python包构建Cookiecutter模板,通过pre-commit对模板仓库执行检查,仓库结构如下:
my_cookiecutter_template | .pre-commit-config.yaml | cookiecutter.json | |___ {{cookiecutter.project_slug}} | pyproject.toml | |____ {{cookiecutter.project_slug}} | __init__.py
使用mypy钩子时触发错误:
{{cookiecutter.project_slug}} is not a valid Python package name
原因是模板中的{{cookiecutter.project_slug}}目录包含__init__.py,但该目录名是Cookiecutter占位符,仅在模板实例化后才会被替换为合法包名,mypy当前将其识别为实际包名进行检查,因此报错。
可行解决方案
方法1:在mypy全局配置中排除模板目录
在项目根目录的mypy.ini或pyproject.toml中添加排除规则,让mypy跳过模板目录的扫描:
- 若使用
mypy.ini:
[mypy] exclude = ^.*{{cookiecutter\.project_slug}}.*$
- 若使用
pyproject.toml:
[tool.mypy] exclude = [".*{{cookiecutter\.project_slug}}.*"]
方法2:修改pre-commit钩子参数
直接在.pre-commit-config.yaml中给mypy钩子添加--exclude参数,指定跳过模板目录:
repos: - repo: https://github.com/python/mypy rev: v1.5.1 hooks: - id: mypy args: [--exclude, '.*{{cookiecutter\.project_slug}}.*']
方法3:给模板目录添加局部忽略配置
在模板的{{cookiecutter.project_slug}}目录下创建.mypy.ini文件,内容如下:
[mypy] ignore_errors = True
这种方式仅让mypy忽略该目录下的所有错误,不会影响仓库中其他文件的检查。
注意事项
- 正则表达式中的
.和{}需要转义,避免被识别为正则特殊字符。 - 如果仅需跳过包名合法性错误而非全部检查,可结合
disable_error_codes配置,但实现复杂度较高,通常直接排除整个模板目录更高效。
内容的提问来源于stack exchange,提问作者Ben Jeffrey
相关产品推荐
相关产品推荐

