Logo Py Code Health

Py Code Health

Cộng đồng
l-mb
py-code-health

Detect and remove dead code, duplicate code, and unused imports. Consolidate similar code patterns into parametrized functions.

Tổng quan

Nhà phát hànhl-mb
Kho mãpython-refactoring-skills
Tên kỹ năngpy-code-health
Sao
57
Bản fork
1
Tệp đi kèm
Chỉ có hướng dẫn
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI là Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Đầy đủ trong hướng dẫn

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được l-mb công bố trên GitHub. Hãy đọc nội dung nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Py Code Health trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL thư mục kỹ năng bên dưới và xác nhận.
    https://github.com/l-mb/python-refactoring-skills/tree/main/skills/py-code-health
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/l-mb/python-refactoring-skills.git /tmp/python-refactoring-skills
mkdir -p .claude/skills
cp -r /tmp/python-refactoring-skills/skills/py-code-health .claude/skills/py-code-health
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Py Code Health trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự tải Py Code Health ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên Py Code Health không bị giới hạn ở mô hình mà kỹ năng này được viết cho. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên kỹ năng chưa dùng không tốn chi phí.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Python Code Health Maintenance

Remove dead code and consolidate duplication to keep codebase clean and maintainable.

Objectives

  1. Detect unused code (functions, classes, variables)
  2. Find and remove dead code with high confidence
  3. Identify duplicate code across files
  4. Consolidate similar code into parametrized functions
  5. Remove redundant imports and commented-out code

Required Tools

Add to [dependency-groups] dev: "vulture", "pylint"

  • vulture: AST-based dead code detection
  • pylint: Duplicate code detection

Permissions: Run py-quality-setup first to configure .claude/settings.local.json with all needed tool permissions.

Dead Code Detection

Find Unused Code

bash
# Using vulture (primary tool)
vulture .                              # Find all unused code
vulture . --min-confidence 80          # High confidence only
vulture . --min-confidence 80 --sort-by-size  # Largest dead code first
vulture . --exclude=tests/,venv/,.venv/ # Exclude directories

# Generate report
vulture . --min-confidence 80 > dead_code_report.txt

Interpret Vulture Output

unused function 'calculate_tax' (80% confidence)
src/billing.py:45

unused class 'LegacyProcessor' (90% confidence)
src/processors.py:123

unused variable 'debug_mode' (60% confidence)
src/config.py:12

Confidence levels:

  • 60-70%: May be false positive (dynamic imports, metaclasses, etc.)
  • 80-89%: Likely unused, verify before removing
  • 90-100%: Almost certainly unused

Handle False Positives

Vulture may flag code that's actually used:

1. Dynamic imports/calls:

python
# Flagged as unused but called dynamically
def plugin_handler():
    pass

# Called via: getattr(module, 'plugin_handler')()

2. Framework conventions:

python
# Django models - fields used by ORM
class User(models.Model):
    email = models.EmailField()  # May be flagged but used by Django

3. Public API:

python
# Part of library's public API, used by external code
def public_function():
    pass

Solutions:

  • Add to whitelist file: vulture . whitelist.py
  • Add comment: # pragma: no cover or custom marker
  • Accept false positives for public APIs
  1. Code that should be used, but isn't:

For example, constants, magic numbers, type definitions, or even functions may appear unused. But this may in fact be the issue! (Consider partial refactoring, or other causes.)

Before eliminating apparently dead code, validate that no similar patterns that should reference it exist. If they do, instead fix the call/use sites.

Remove Dead Code

python
# BEFORE - Unused functions cluttering codebase
def old_calculate_price(item):  # Last used 2 years ago
    return item.cost * 1.1

def deprecated_handler(data):  # Replaced by new_handler
    pass

# AFTER - Clean, only active code remains
# (Dead code completely removed)

Duplicate Code Detection

Find Duplicates

bash
# Using pylint (detects similar code blocks)
pylint --disable=all --enable=duplicate-code --recursive=y .

# Configure minimum similar lines (default: 4)
pylint --disable=all --enable=duplicate-code --duplicate-code-min-lines=6 --recursive=y .

# JSON output for parsing
pylint --disable=all --enable=duplicate-code --output-format=json --recursive=y . > duplication.json

Interpret Pylint Output

Similar lines in 2 files
src/auth.py:45-60
src/admin.py:123-138

def validate_credentials(username, password):
    if not username or not password:
        return False
    user = db.get_user(username)
    if not user:
        return False
    return check_password(password, user.password_hash)

Consolidation Patterns

Parametrize Similar Functions

python
# BEFORE - Duplicate code with slight variations
def process_user(data: dict) -> User:
    if not data.get("email"):
        raise ValueError("Missing email")
    if not data.get("name"):
        raise ValueError("Missing name")
    return User(email=data["email"], name=data["name"])

def process_admin(data: dict) -> Admin:
    if not data.get("email"):
        raise ValueError("Missing email")
    if not data.get("name"):
        raise ValueError("Missing name")
    return Admin(email=data["email"], name=data["name"])

# AFTER - Single parametrized function
T = TypeVar('T', User, Admin)

def process_entity(data: dict, entity_class: type[T]) -> T:
    if not data.get("email"):
        raise ValueError("Missing email")
    if not data.get("name"):
        raise ValueError("Missing name")
    return entity_class(email=data["email"], name=data["name"])

# Usage
user = process_entity(data, User)
admin = process_entity(data, Admin)

Extract Common Logic

python
# BEFORE - Duplicated validation in multiple functions
def create_user(email: str, age: int) -> User:
    if not email or "@" not in email:
        raise ValueError("Invalid email")
    if age < 0 or age > 150:
        raise ValueError("Invalid age")
    return User(email=email, age=age)

def update_user(user_id: int, email: str, age: int) -> User:
    if not email or "@" not in email:
        raise ValueError("Invalid email")
    if age < 0 or age > 150:
        raise ValueError("Invalid age")
    user = get_user(user_id)
    user.email = email
    user.age = age
    return user

# AFTER - Extract common validation
def validate_email(email: str) -> None:
    if not email or "@" not in email:
        raise ValueError("Invalid email")

def validate_age(age: int) -> None:
    if age < 0 or age > 150:
        raise ValueError("Invalid age")

def create_user(email: str, age: int) -> User:
    validate_email(email)
    validate_age(age)
    return User(email=email, age=age)

def update_user(user_id: int, email: str, age: int) -> User:
    validate_email(email)
    validate_age(age)
    user = get_user(user_id)
    user.email = email
    user.age = age
    return user

Use Configuration Over Duplication

python
# BEFORE - Similar handlers with different values
def process_csv_file(path: str) -> list:
    return parse_file(path, delimiter=",", encoding="utf-8", skip_header=True)

def process_tsv_file(path: str) -> list:
    return parse_file(path, delimiter="\t", encoding="utf-8", skip_header=True)

def process_psv_file(path: str) -> list:
    return parse_file(path, delimiter="|", encoding="utf-8", skip_header=True)

# AFTER - Configuration-driven
FILE_CONFIGS = {
    "csv": {"delimiter": ",", "encoding": "utf-8", "skip_header": True},
    "tsv": {"delimiter": "\t", "encoding": "utf-8", "skip_header": True},
    "psv": {"delimiter": "|", "encoding": "utf-8", "skip_header": True},
}

def process_file(path: str, file_type: str) -> list:
    config = FILE_CONFIGS[file_type]
    return parse_file(path, **config)

Remove Commented Code

Commented-out code is a form of dead code:

python
# BEFORE - Cluttered with old code
def calculate_total(items: list) -> float:
    # Old implementation - kept for reference
    # total = 0
    # for item in items:
    #     total += item.price * item.quantity
    # return total

    # Another old version
    # return sum(item.price * item.quantity for item in items)

    # Current implementation
    return sum(item.total_price() for item in items)

# AFTER - Clean, rely on git history
def calculate_total(items: list) -> float:
    return sum(item.total_price() for item in items)

Rationale: Git history preserves old implementations. Commented code creates noise.

Verification Checklist

  • vulture . --min-confidence 80 reports no dead code (or only accepted false positives)
  • pylint --disable=all --enable=duplicate-code reports no duplicate blocks >6 lines
  • No commented-out code blocks remain
  • All tests pass after removals
  • Code coverage maintained or improved
  • Whitelist file created for intentional false positives (if needed)

Examples

Example: Code health cleanup workflow

1. Scan: vulture . --min-confidence 80; pylint --disable=all --enable=duplicate-code --recursive=y .
2. Found: 5 unused functions (67 lines), 3 duplicate blocks (45 lines)
3. Remove: Verify unused code with Explore agent, delete confirmed dead code
4. Consolidate: Extract duplicates to shared utilities
5. Result: -112 lines total, tests pass, coverage improved to 86%

Example: Handle false positives

1. Scan: vulture . --min-confidence 80
2. Found: public_api_function flagged as unused (actually part of library API)
3. Create whitelist.py with: public_api_function  # Used by external consumers
4. Re-scan: vulture . whitelist.py --min-confidence 80
5. Result: False positive suppressed, real dead code still detected

Example: Consolidate duplicate validation

1. Scan: pylint --disable=all --enable=duplicate-code --recursive=y .
2. Found: Same validation logic in create_user() and update_user()
3. Extract: Create validate_user_data() helper function
4. Update: Both functions now call validate_user_data()
5. Result: -15 lines, single source of truth for validation

Related Skills

  • Prerequisites: py-quality-setup (tool configuration), py-test-quality (safety net before removing code)
  • Next steps: py-complexity (reduce complexity after cleanup)
  • See also: py-security (check security before major changes)

Câu hỏi thường gặp

Kỹ năng AI Py Code Health làm được gì?

Detect and remove dead code, duplicate code, and unused imports. Consolidate similar code patterns into parametrized functions.

Vì sao nên dùng Py Code Health trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Py Code Health là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Py Code Health trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/l-mb/python-refactoring-skills/tree/main/skills/py-code-health. TypingMind đọc tệp SKILL.md và cài đặt thành một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Py Code Health?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Bạn có thể dùng Py Code Health với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Py Code Health với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Py Code Health có miễn phí không?

Có. Kỹ năng này được l-mb phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp cho mô hình các công cụ mới để gọi — mã được chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và tiêu chí của đầu ra tốt. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇