Pylint 是一个用于 Python的静态代码分析器。它会检查错误、强制执行编码标准、寻找代码异味,并可以就如何重构代码提出建议。
pylint 一起使用的项目包括
开发环境中应该使用指定的pylint版本,保证效果统一
效果如下
在任何 Markdown 文件中添加该行即可
[](https://github.com/pylint-dev/pylint)
Pylint 可以通过包管理器进行安装
pip install pylint
如果需要使用pylint提供的拼写检查需要额外安装
pip install pylint[spelling]
pylint 需要检查的文件夹或文件路径
Pylint 支持多种配置文件格式
可以使用 --generate-toml-config 或 --generate-rcfile 生成一个示例配置文件。
# 生成 rc 文件在当前目录 pylint --generate-rcfile > .pylintrc # 生成 toml 文件在当前目录 pylint --generate-toml-config > pyproject.toml
创建时可以预设一些选项
pylint --disable=bare-except,invalid-name --class-rgx='[A-Z][a-z]+' --generate-toml-config
[tool.pylint.main] # 启用持久化缓存 persistent = true # 根据机器的CPU核心数设置, 0 为自动检查核心数 jobs = 0 # 用于版本依赖性检查的最低 python 版本 py-version = "3.11"
[tool.pylint.basic] # 命名风格 variable-naming-style = "snake_case" function-naming-style = "snake_case" class-naming-style = "PascalCase" const-naming-style = "UPPER_CASE" # 禁止使用的变量名 bad-names = ["a", "tmp", "temp", "test"] # 允许的好变量名 good-names = ["i", "j", "k", "ex", "Run", "_"] # 函数、方法至少多少行需要写docling注释,-1为必写,0为不写 docstring-min-length = 5 # 允许在名称中使用的正则表达式(覆盖命名风格) # 比如允许变量名以“_”开头 variable-rgx = "^_?[a-z][a-z0-9_]{2,29}$"
[tool.pylint.design] # 哪些class不计入父类数量计算 ignored-parents = "object,abc.ABC" # 最大函数参数数 max-args = 5 # class字段数量上限,Model/Serializer/Forms 可能有较多字段 max-attributes = 15 # if 语句中的布尔表达式数量 max-bool-expr = 5 # 函数/方法中的分支数量 max-branches = 10 # 局部变量数量 max-locals = 15 # class多重继承数量 max-parents = 5 # 与 max-args 同步 max-positional-arguments = 5 # public方法数量 max-public-methods = 20 # return 数量限制 max-returns = 6 # 一个函数最大行数 max-statements = 60 # class 至少应该有几个public方法 min-public-methods = 1
# 预期的行尾格式,可根据团队环境选择。对于跨平台开发,推荐使用 LF。 expected-line-ending-format = "LF" # 允许行长度超过限制的正则表达式 ignore-long-lines = "^\\s*(# )?<?https?://\\S+>?$" # 括号内要求的缩进空格数 indent-after-paren = 4 # 缩进使用的字符串,推荐使用4个空格 indent-string = " " # 单行最大字符数 max-line-length = 120 # 模块的最大行数 max-module-lines = 1000 # 允许类体只有单一语句时与声明在同一行 # class Configuration: setting = True single-line-class-stmt = false # 允许if体只有单一语句且无else时与测试条件在同一行 # if is_active: status = "Active" single-line-if-stmt = flase
[tool.pylint.imports] # 允许在任何级别导入的模块列表,一般放内置和第三方库 allow-any-import-level = ["os", "sys", "django"] # 分类明确标准库 known-standard-library = [ "os", "sys", "math", "json", "logging", ] # 分类明确第三方库 known-third-party = [ "django", "rest_framework", "enchant", "requests", ]
[tool.pylint."messages control"] # 仅显示以下置信度级别的警告 confidence = [ "HIGH", "CONTROL_FLOW", "INFERENCE", "INFERENCE_FAILURE", "UNDEFINED", ] # 禁用不相关或不必要的消息 disable = [ "raw-checker-failed", "bad-inline-option", "locally-disabled", "file-ignored", "suppressed-message", "useless-suppression", "deprecated-pragma", "use-symbolic-message-instead", "use-implicit-booleaness-not-comparison-to-string", "use-implicit-booleaness-not-comparison-to-zero", "C0103", # 变量命名长度过短或过长(根据需要调整) "W0511", # TODO和FIXME注释(根据团队规范决定是否禁用) ]
常见的注释标签在检查范围内可帮助团队及时发现和处理潜在问题
[tool.pylint.miscellaneous] # 要考虑的注释标签列表 notes = ["FIXME", "XXX", "TODO"] # 注释标签的正则表达式 notes-rgx = "^(FIXME|XXX|TODO)\b"
[tool.pylint.refactoring] # 函数/方法体中嵌套块的最大数量 max-nested-blocks = 5 # 永不返回的函数的完整名称 never-returning-functions = ["sys.exit", "argparse.parse_error"] # 使用非空分隔符连接字符串列表时,Pylint会建议使用str.join方法 suggest-join-with-non-empty-separator = true
[tool.pylint.reports] # 全局评估报告的评价公式 evaluation = "max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10))" # 消息模板 msg-template = "{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}" # 输出格式,用颜色区分不同类型的消息,提升可读性 output-format = "colorized" # 是否显示完整报告 reports = false # 启用评估分数 score = true
一般不进行修改
[tool.pylint.similarities] # 在相似度计算中忽略注释 ignore-comments = true # 在相似度计算中忽略文档字符串 ignore-docstrings = true # 在相似度计算中忽略导入语句 ignore-imports = true # 在相似度计算中忽略函数签名 ignore-signatures = true # 相似度的最小行数 min-similarity-lines = 4
该功能需要安装pylint 的spell检查包
[tool.pylint.spelling] # 限制拼写错误建议的数量 max-spelling-suggestions = 4 # 拼写词典名称(保持为空,使用默认词典) spelling-dict = "" # 忽略拼写检查的注释指令 spelling-ignore-comment-directives = "fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:" # 不进行拼写检查的单词列表(根据项目需求添加) spelling-ignore-words = "POST,GET,PUT,PATCH,DELETE,URL,HTTP" # 私有词典文件路径(如有需要) spelling-private-dict-file = "" # 将未知单词存储到私有词典 spelling-store-unknown-words = false
[tool.pylint.typecheck] # 上下文管理器装饰器列表 contextmanager-decorators = ["contextlib.contextmanager"] # 动态设置的成员列表(根据项目需要添加) generated-members = ["objects", "manager", "verbose_name"] # 忽略mixin类中缺失的成员 ignore-none = true # 对不透明推断的对象忽略成员检查 ignore-on-opaque-inference = true # 忽略mixin成员的检查 ignored-checks-for-mixins = [ "no-member", "not-async-context-manager", "not-context-manager", "attribute-defined-outside-init", ] # 忽略成员检查的类名 ignored-classes = [ "optparse.Values", "thread._local", "_thread._local", "argparse.Namespace", ] # 缺失成员时显示提示 missing-member-hint = true # 缺失成员提示的最小编辑距离 missing-member-hint-distance = 1 # 缺失成员提示的最大选项数 missing-member-max-choices = 1 # 定义mixin类的正则模式 mixin-class-rgx = ".*[Mm]ixin" # 改变被装饰函数签名的装饰器列表(根据项目需要添加) signature-mutators = ["functools.wraps"]
[tool.pylint.variables] # 允许的全局未使用变量 allow-global-unused-variables = true # 允许覆盖内置名称的变量列表 allowed-redefined-builtins = ["len", "id"] # 允许作为回调函数标识的名称前缀或后缀 callbacks = ["cb_", "_cb"] # 匹配虚拟变量名称的正则表达式 dummy-variables-rgx = "_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_" # 忽略的参数名称正则表达式 ignored-argument-names = "_.*|^ignored_|^unused_" # 允许重新定义内置函数的模块列表 redefining-builtins-modules = [ "six.moves", "past.builtins", "future.builtins", "builtins", "io", ]
https://pylint.readthedocs.io/en/latest/user_guide/installation/ide_integration/index.html
https://pylint.readthedocs.io/en/latest/user_guide/installation/pre-commit-integration.html
本文作者:Silon汐冷
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
预览: