python-quality-checker

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python Quality Checker Skill

Python代码质量检查Skill

Purpose

用途

This skill provides comprehensive Python code quality validation including formatting (Black), type checking (mypy), linting (flake8/ruff), security analysis (bandit), and complexity analysis. Ensures code meets Python best practices and project standards.
本Skill提供全面的Python代码质量验证,包括格式化(Black)、类型检查(mypy)、代码静态分析(flake8/ruff)、安全扫描(bandit)以及复杂度分析。确保代码符合Python最佳实践和项目标准。

When to Use

使用场景

  • Validating Python code quality before commit
  • Running pre-commit quality checks
  • CI/CD quality gate validation
  • Code review preparation
  • Ensuring PEP 8 compliance
  • Type safety validation
  • Security vulnerability detection
  • 提交代码前验证Python代码质量
  • 运行提交前的质量检查
  • CI/CD流程中的质量门验证
  • 代码评审准备
  • 确保符合PEP 8规范
  • 类型安全验证
  • 安全漏洞检测

Quality Check Workflow

质量检查流程

1. Environment Setup

1. 环境搭建

Verify Tools Installed:
bash
undefined
验证工具是否已安装:
bash
undefined

Check Python version

Check Python version

python --version
python --version

Check quality tools

Check quality tools

black --version mypy --version flake8 --version bandit --version
black --version mypy --version flake8 --version bandit --version

Or install missing tools

Or install missing tools

pip install black mypy flake8 bandit ruff

**Install Development Dependencies:**
```bash
pip install black mypy flake8 bandit ruff

**安装开发依赖:**
```bash

Install all dev tools

Install all dev tools

pip install -e ".[dev]"
pip install -e ".[dev]"

Or from requirements

Or from requirements

pip install -r requirements-dev.txt

**Deliverable:** Quality tools ready

---
pip install -r requirements-dev.txt

**交付物:** 质量检查工具已就绪

---

2. Code Formatting Check (Black)

2. 代码格式化检查(Black)

Check Formatting:
bash
undefined
检查格式化情况:
bash
undefined

Check if code is formatted

Check if code is formatted

black --check src/ tests/
black --check src/ tests/

Check with diff

Check with diff

black --check --diff src/ tests/
black --check --diff src/ tests/

Check specific files

Check specific files

black --check src/tools/feature/core.py
black --check src/tools/feature/core.py

Check with color output

Check with color output

black --check --color src/ tests/

**Auto-Format Code:**
```bash
black --check --color src/ tests/

**自动格式化代码:**
```bash

Format all code

Format all code

black src/ tests/
black src/ tests/

Format specific directory

Format specific directory

black src/tools/feature/
black src/tools/feature/

Format with specific line length

Format with specific line length

black --line-length 100 src/
black --line-length 100 src/

Preview changes without applying

Preview changes without applying

black --check --diff src/

**Configuration (pyproject.toml):**
```toml
[tool.black]
line-length = 88
target-version = ['py311']
include = '\.pyi?$'
extend-exclude = '''
/(
  # Directories
  \.eggs
  | \.git
  | \.venv
  | build
  | dist
)/
'''
Deliverable: Formatting validation report

black --check --diff src/

**配置(pyproject.toml):**
```toml
[tool.black]
line-length = 88
target-version = ['py311']
include = '\.pyi?$'
extend-exclude = '''
/(
  # Directories
  \.eggs
  | \.git
  | \.venv
  | build
  | dist
)/
'''
交付物: 格式化验证报告

3. Type Checking (mypy)

3. 类型检查(mypy)

Run Type Checks:
bash
undefined
运行类型检查:
bash
undefined

Check entire codebase

Check entire codebase

mypy src/
mypy src/

Check specific module

Check specific module

mypy src/tools/feature/
mypy src/tools/feature/

Check with stricter settings

Check with stricter settings

mypy --strict src/
mypy --strict src/

Show error codes

Show error codes

mypy --show-error-codes src/
mypy --show-error-codes src/

Generate HTML report

Generate HTML report

mypy --html-report mypy-report/ src/

**Common Type Issues:**
```bash
mypy --html-report mypy-report/ src/

**常见类型问题检查:**
```bash

Check for missing type hints

Check for missing type hints

mypy --disallow-untyped-defs src/
mypy --disallow-untyped-defs src/

Check for Any types

Check for Any types

mypy --disallow-any-explicit src/
mypy --disallow-any-explicit src/

Check for incomplete definitions

Check for incomplete definitions

mypy --check-untyped-defs src/

**Configuration (pyproject.toml):**
```toml
[tool.mypy]
python_version = "3.11"
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
disallow_incomplete_defs = true
check_untyped_defs = true
no_implicit_optional = true
warn_redundant_casts = true
warn_unused_ignores = true
warn_no_return = true
warn_unreachable = true
strict_equality = true
show_error_codes = true

[[tool.mypy.overrides]]
module = "tests.*"
disallow_untyped_defs = false
Deliverable: Type checking report

mypy --check-untyped-defs src/

**配置(pyproject.toml):**
```toml
[tool.mypy]
python_version = "3.11"
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
disallow_incomplete_defs = true
check_untyped_defs = true
no_implicit_optional = true
warn_redundant_casts = true
warn_unused_ignores = true
warn_no_return = true
warn_unreachable = true
strict_equality = true
show_error_codes = true

[[tool.mypy.overrides]]
module = "tests.*"
disallow_untyped_defs = false
交付物: 类型检查报告

4. Linting (flake8/ruff)

4. 代码静态分析(flake8/ruff)

Flake8 Linting:
bash
undefined
Flake8静态分析:
bash
undefined

Lint entire codebase

Lint entire codebase

flake8 src/ tests/
flake8 src/ tests/

Lint with statistics

Lint with statistics

flake8 --statistics src/
flake8 --statistics src/

Lint with detailed output

Lint with detailed output

flake8 --show-source --show-pep8 src/
flake8 --show-source --show-pep8 src/

Generate HTML report

Generate HTML report

flake8 --format=html --htmldir=flake8-report/ src/

**Ruff Linting (Faster Alternative):**
```bash
flake8 --format=html --htmldir=flake8-report/ src/

**Ruff静态分析(更快的替代方案):**
```bash

Lint with ruff

Lint with ruff

ruff check src/ tests/
ruff check src/ tests/

Auto-fix issues

Auto-fix issues

ruff check --fix src/ tests/
ruff check --fix src/ tests/

Show violations

Show violations

ruff check --output-format=full src/
ruff check --output-format=full src/

Specific rules

Specific rules

ruff check --select=E,F,I src/

**Flake8 Configuration (.flake8):**
```ini
[flake8]
max-line-length = 88
extend-ignore = E203, W503
exclude =
    .git,
    __pycache__,
    .venv,
    venv,
    build,
    dist
max-complexity = 10
per-file-ignores =
    __init__.py:F401
Ruff Configuration (pyproject.toml):
toml
[tool.ruff]
line-length = 88
target-version = "py311"
select = [
    "E",  # pycodestyle errors
    "W",  # pycodestyle warnings
    "F",  # pyflakes
    "I",  # isort
    "N",  # pep8-naming
    "UP", # pyupgrade
    "B",  # flake8-bugbear
    "C4", # flake8-comprehensions
]
ignore = ["E203", "W503"]
exclude = [
    ".git",
    "__pycache__",
    ".venv",
    "build",
    "dist",
]

[tool.ruff.per-file-ignores]
"__init__.py" = ["F401"]
Deliverable: Linting report

ruff check --select=E,F,I src/

**Flake8配置(.flake8):**
```ini
[flake8]
max-line-length = 88
extend-ignore = E203, W503
exclude =
    .git,
    __pycache__,
    .venv,
    venv,
    build,
    dist
max-complexity = 10
per-file-ignores =
    __init__.py:F401
Ruff配置(pyproject.toml):
toml
[tool.ruff]
line-length = 88
target-version = "py311"
select = [
    "E",  # pycodestyle errors
    "W",  # pycodestyle warnings
    "F",  # pyflakes
    "I",  # isort
    "N",  # pep8-naming
    "UP", # pyupgrade
    "B",  # flake8-bugbear
    "C4", # flake8-comprehensions
]
ignore = ["E203", "W503"]
exclude = [
    ".git",
    "__pycache__",
    ".venv",
    "build",
    "dist",
]

[tool.ruff.per-file-ignores]
"__init__.py" = ["F401"]
交付物: 静态分析报告

5. Security Analysis (bandit)

5. 安全扫描(bandit)

Run Security Checks:
bash
undefined
运行安全检查:
bash
undefined

Basic security scan

Basic security scan

bandit -r src/
bandit -r src/

Detailed report

Detailed report

bandit -r src/ -f json -o bandit-report.json
bandit -r src/ -f json -o bandit-report.json

Exclude test files

Exclude test files

bandit -r src/ --exclude tests/
bandit -r src/ --exclude tests/

Specific confidence level

Specific confidence level

bandit -r src/ -ll # Low confidence bandit -r src/ -l # Medium confidence bandit -r src/ # All levels
bandit -r src/ -ll # Low confidence bandit -r src/ -l # Medium confidence bandit -r src/ # All levels

Skip specific issues

Skip specific issues

bandit -r src/ -s B101,B601

**Common Security Issues:**
```bash
bandit -r src/ -s B101,B601

**常见安全问题检查:**
```bash

Check for hardcoded passwords

Check for hardcoded passwords

bandit -r src/ -t B105,B106
bandit -r src/ -t B105,B106

Check for SQL injection

Check for SQL injection

bandit -r src/ -t B608
bandit -r src/ -t B608

Check for command injection

Check for command injection

bandit -r src/ -t B602,B603
bandit -r src/ -t B602,B603

Check for unsafe YAML loading

Check for unsafe YAML loading

bandit -r src/ -t B506

**Configuration (.bandit):**
```yaml
bandit -r src/ -t B506

**配置(.bandit):**
```yaml

.bandit

.bandit

exclude_dirs:
  • /tests/
  • /venv/
  • /.venv/
skips:
  • B101 # Skip assert warnings in production code
  • B601 # Skip shell=True warnings (if justified)
tests:
  • B201 # flask_debug_true
  • B501 # request_with_no_cert_validation
  • B502 # ssl_with_bad_version

**Deliverable:** Security analysis report

---
exclude_dirs:
  • /tests/
  • /venv/
  • /.venv/
skips:
  • B101 # Skip assert warnings in production code
  • B601 # Skip shell=True warnings (if justified)
tests:
  • B201 # flask_debug_true
  • B501 # request_with_no_cert_validation
  • B502 # ssl_with_bad_version

**交付物:** 安全扫描报告

---

6. Import Sorting (isort)

6. 导入排序(isort)

Check Import Organization:
bash
undefined
检查导入组织情况:
bash
undefined

Check imports

Check imports

isort --check-only src/ tests/
isort --check-only src/ tests/

Check with diff

Check with diff

isort --check-only --diff src/ tests/
isort --check-only --diff src/ tests/

Auto-fix imports

Auto-fix imports

isort src/ tests/

**Configuration (pyproject.toml):**
```toml
[tool.isort]
profile = "black"
line_length = 88
multi_line_output = 3
include_trailing_comma = true
force_grid_wrap = 0
use_parentheses = true
ensure_newline_before_comments = true
Deliverable: Import sorting validation

isort src/ tests/

**配置(pyproject.toml):**
```toml
[tool.isort]
profile = "black"
line_length = 88
multi_line_output = 3
include_trailing_comma = true
force_grid_wrap = 0
use_parentheses = true
ensure_newline_before_comments = true
交付物: 导入排序验证结果

7. Complexity Analysis

7. 复杂度分析

Check Code Complexity:
bash
undefined
检查代码复杂度:
bash
undefined

Cyclomatic complexity with radon

Cyclomatic complexity with radon

pip install radon radon cc src/ -a
pip install radon radon cc src/ -a

Show complex functions (>10)

Show complex functions (>10)

radon cc src/ -nc
radon cc src/ -nc

Maintainability index

Maintainability index

radon mi src/
radon mi src/

Raw metrics

Raw metrics

radon raw src/

**McCabe Complexity (via flake8):**
```bash
radon raw src/

**McCabe复杂度检查(通过flake8):**
```bash

Check complexity with flake8

Check complexity with flake8

flake8 --max-complexity=10 src/
flake8 --max-complexity=10 src/

Show complexity metrics

Show complexity metrics

pip install flake8-mccabe flake8 --statistics --select=C src/

**Deliverable:** Complexity analysis report

---
pip install flake8-mccabe flake8 --statistics --select=C src/

**交付物:** 复杂度分析报告

---

8. Comprehensive Quality Check

8. 全面质量检查

Run All Checks:
bash
#!/bin/bash
运行所有检查:
bash
#!/bin/bash

scripts/quality-check.sh

scripts/quality-check.sh

set -e # Exit on first error
echo "=== Python Quality Checks ==="
echo "1. Code Formatting (Black)..." black --check src/ tests/
echo "2. Import Sorting (isort)..." isort --check-only src/ tests/
echo "3. Type Checking (mypy)..." mypy src/
echo "4. Linting (ruff)..." ruff check src/ tests/
echo "5. Security Analysis (bandit)..." bandit -r src/ -ll
echo "6. Complexity Check..." radon cc src/ -nc
echo "=== All Quality Checks Passed ✅ ==="

**Make script executable:**
```bash
chmod +x scripts/quality-check.sh
./scripts/quality-check.sh
Deliverable: Comprehensive quality report

set -e # Exit on first error
echo "=== Python Quality Checks ==="
echo "1. Code Formatting (Black)..." black --check src/ tests/
echo "2. Import Sorting (isort)..." isort --check-only src/ tests/
echo "3. Type Checking (mypy)..." mypy src/
echo "4. Linting (ruff)..." ruff check src/ tests/
echo "5. Security Analysis (bandit)..." bandit -r src/ -ll
echo "6. Complexity Check..." radon cc src/ -nc
echo "=== All Quality Checks Passed ✅ ==="

**设置脚本可执行权限:**
```bash
chmod +x scripts/quality-check.sh
./scripts/quality-check.sh
交付物: 全面质量检查报告

Quality Standards

质量标准

Code Formatting

代码格式化

  • All code formatted with Black
  • Line length ≤ 88 characters
  • Imports sorted with isort
  • Trailing whitespace removed
  • Consistent string quotes
  • 所有代码已通过Black格式化
  • 行长度 ≤ 88字符
  • 导入已通过isort排序
  • 已移除尾随空格
  • 字符串引号风格一致

Type Checking

类型检查

  • All functions have type hints
  • No
    Any
    types (except justified)
  • No missing return types
  • No implicit Optional
  • mypy passes with no errors
  • 所有函数均有类型提示
  • Any
    类型(合理情况除外)
  • 无缺失的返回类型
  • 无隐式Optional类型
  • mypy检查无错误

Linting

静态分析

  • No PEP 8 violations
  • No undefined names
  • No unused imports
  • No unused variables
  • Complexity ≤ 10 per function
  • 无PEP 8规范违反
  • 无未定义名称
  • 无未使用的导入
  • 无未使用的变量
  • 每个函数的复杂度 ≤ 10

Security

安全

  • No hardcoded secrets/passwords
  • No SQL injection vulnerabilities
  • No command injection risks
  • Safe YAML/pickle usage
  • Proper input validation
  • 无硬编码的密钥/密码
  • 无SQL注入漏洞
  • 无命令注入风险
  • YAML/pickle加载方式安全
  • 输入验证规范

Code Quality

代码质量

  • Functions < 50 lines
  • Files < 500 lines
  • Classes < 300 lines
  • Max nesting depth: 4
  • Cyclomatic complexity < 10

  • 函数行数 < 50行
  • 文件行数 < 500行
  • 类行数 < 300行
  • 最大嵌套深度:4
  • 圈复杂度 < 10

Quality Check Matrix

质量检查矩阵

CheckToolThresholdAuto-Fix
FormattingBlackMust passYes
Type hintsmypy0 errorsNo
Lintingruff/flake80 errorsPartial
ImportsisortMust passYes
Securitybandit0 high severityNo
Complexityradon≤ 10No

检查项工具阈值自动修复
格式化Black必须通过
类型提示mypy0错误
静态分析ruff/flake80错误部分支持
导入排序isort必须通过
安全扫描bandit0高风险问题
复杂度radon≤10

Pre-commit Integration

提交前钩子集成

Setup pre-commit hooks:
yaml
undefined
配置提交前钩子:
yaml
undefined

.pre-commit-config.yaml

.pre-commit-config.yaml

repos:

**Install and run:**
```bash
repos:

**安装并运行:**
```bash

Install pre-commit

Install pre-commit

pip install pre-commit
pip install pre-commit

Install hooks

Install hooks

pre-commit install
pre-commit install

Run manually

Run manually

pre-commit run --all-files

**Deliverable:** Pre-commit hooks configured

---
pre-commit run --all-files

**交付物:** 提交前钩子已配置完成

---

CI/CD Integration

CI/CD集成

GitHub Actions Example:
yaml
undefined
GitHub Actions示例:
yaml
undefined

.github/workflows/quality.yml

.github/workflows/quality.yml

name: Python Quality Checks
on: [push, pull_request]
jobs: quality: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3
  - name: Set up Python
    uses: actions/setup-python@v4
    with:
      python-version: '3.11'

  - name: Install dependencies
    run: |
      pip install black mypy ruff bandit isort radon
      pip install -r requirements.txt

  - name: Check formatting
    run: black --check src/ tests/

  - name: Check imports
    run: isort --check-only src/ tests/

  - name: Type checking
    run: mypy src/

  - name: Linting
    run: ruff check src/ tests/

  - name: Security scan
    run: bandit -r src/ -ll

  - name: Complexity check
    run: radon cc src/ -nc

**Deliverable:** CI/CD quality pipeline

---
name: Python Quality Checks
on: [push, pull_request]
jobs: quality: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3
  - name: Set up Python
    uses: actions/setup-python@v4
    with:
      python-version: '3.11'

  - name: Install dependencies
    run: |
      pip install black mypy ruff bandit isort radon
      pip install -r requirements.txt

  - name: Check formatting
    run: black --check src/ tests/

  - name: Check imports
    run: isort --check-only src/ tests/

  - name: Type checking
    run: mypy src/

  - name: Linting
    run: ruff check src/ tests/

  - name: Security scan
    run: bandit -r src/ -ll

  - name: Complexity check
    run: radon cc src/ -nc

**交付物:** CI/CD质量检查流水线

---

Quality Check Troubleshooting

质量检查故障排除

Black Formatting Failures

Black格式化失败

bash
undefined
bash
undefined

Check what would change

Check what would change

black --check --diff src/
black --check --diff src/

Apply fixes

Apply fixes

black src/
black src/

Check specific file

Check specific file

black --check src/tools/feature/core.py
undefined
black --check src/tools/feature/core.py
undefined

mypy Type Errors

mypy类型错误

bash
undefined
bash
undefined

Show detailed error

Show detailed error

mypy --show-error-codes src/
mypy --show-error-codes src/

Check specific file

Check specific file

mypy src/tools/feature/core.py
mypy src/tools/feature/core.py

Ignore specific error (last resort)

Ignore specific error (last resort)

type: ignore[error-code]

type: ignore[error-code]

undefined
undefined

Ruff/Flake8 Violations

Ruff/Flake8违规

bash
undefined
bash
undefined

Show violation details

Show violation details

ruff check --output-format=full src/
ruff check --output-format=full src/

Auto-fix safe violations

Auto-fix safe violations

ruff check --fix src/
ruff check --fix src/

Ignore specific line (last resort)

Ignore specific line (last resort)

noqa: F401

noqa: F401

undefined
undefined

Bandit Security Issues

Bandit安全问题

bash
undefined
bash
undefined

Show detailed report

Show detailed report

bandit -r src/ -f json
bandit -r src/ -f json

Skip false positives

Skip false positives

nosec B101

nosec B101

Exclude specific tests

Exclude specific tests

bandit -r src/ -s B101,B601

---
bandit -r src/ -s B101,B601

---

Quality Report Template

质量报告模板

markdown
undefined
markdown
undefined

Python Quality Check Report

Python Quality Check Report

Summary

Summary

  • Status: ✅ All checks passed
  • Date: 2024-01-15
  • Code Base: src/
  • Status: ✅ All checks passed
  • Date: 2024-01-15
  • Code Base: src/

Checks Performed

Checks Performed

Formatting (Black)

Formatting (Black)

  • Status: ✅ PASS
  • Files Checked: 45
  • Issues: 0
  • Status: ✅ PASS
  • Files Checked: 45
  • Issues: 0

Type Checking (mypy)

Type Checking (mypy)

  • Status: ✅ PASS
  • Files Checked: 45
  • Errors: 0
  • Warnings: 0
  • Status: ✅ PASS
  • Files Checked: 45
  • Errors: 0
  • Warnings: 0

Linting (ruff)

Linting (ruff)

  • Status: ✅ PASS
  • Files Checked: 45
  • Violations: 0
  • Status: ✅ PASS
  • Files Checked: 45
  • Violations: 0

Security (bandit)

Security (bandit)

  • Status: ✅ PASS
  • Files Scanned: 45
  • High Severity: 0
  • Medium Severity: 0
  • Low Severity: 2 (acceptable)
  • Status: ✅ PASS
  • Files Scanned: 45
  • High Severity: 0
  • Medium Severity: 0
  • Low Severity: 2 (acceptable)

Complexity (radon)

Complexity (radon)

  • Status: ✅ PASS
  • Average Complexity: 4.2
  • Max Complexity: 8
  • Files > 10: 0
  • Status: ✅ PASS
  • Average Complexity: 4.2
  • Max Complexity: 8
  • Files > 10: 0

Details

Details

All Python quality checks passed successfully. Code is well-formatted, type-safe, lint-free, secure, and maintainable.
All Python quality checks passed successfully. Code is well-formatted, type-safe, lint-free, secure, and maintainable.

Recommendations

Recommendations

  • Continue maintaining type hints for all new functions
  • Keep cyclomatic complexity below 10
  • Run pre-commit hooks before commits

---
  • Continue maintaining type hints for all new functions
  • Keep cyclomatic complexity below 10
  • Run pre-commit hooks before commits

---

Integration with Code Quality Specialist

与代码质量专家集成

Input: Python codebase quality check request Process: Run all Python quality tools and analyze results Output: Comprehensive quality report with pass/fail status Next Step: Report to code-quality-specialist for consolidation

输入: Python代码库质量检查请求 流程: 运行所有Python质量检查工具并分析结果 输出: 包含通过/未通过状态的全面质量报告 下一步: 将报告提交给代码质量专家进行整合

Best Practices

最佳实践

Development

开发阶段

  • Run Black on save (IDE integration)
  • Enable mypy in IDE for real-time feedback
  • Use pre-commit hooks
  • Fix linting issues immediately
  • 在IDE中配置Black自动格式化(保存时触发)
  • 在IDE中启用mypy以获取实时反馈
  • 使用提交前钩子
  • 立即修复静态分析问题

Pre-Commit

提交前

  • Run full quality check script
  • Ensure all checks pass
  • Fix issues before pushing
  • Review security warnings
  • 运行完整的质量检查脚本
  • 确保所有检查通过
  • 推送代码前修复所有问题
  • 审核安全警告

CI/CD

CI/CD流程

  • Run quality checks on every PR
  • Fail build on quality violations
  • Generate quality reports
  • Track quality metrics over time
  • 对每个PR运行质量检查
  • 若存在质量违规则终止构建
  • 生成质量报告
  • 跟踪质量指标变化趋势

Code Review

代码评审

  • Verify quality checks passed
  • Review type hints
  • Check security scan results
  • Validate complexity metrics

  • 验证质量检查已通过
  • 评审类型提示
  • 检查安全扫描结果
  • 验证复杂度指标

Supporting Resources

支持资源

Success Metrics

成功指标

  • All code formatted with Black
  • All type checks passing
  • Zero linting violations
  • No high-severity security issues
  • Complexity under threshold
  • All quality checks automated
  • 所有代码已通过Black格式化
  • 所有类型检查已通过
  • 无静态分析违规
  • 无高风险安全问题
  • 复杂度低于阈值
  • 所有质量检查已自动化