or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

analysis.mdast-utilities.mdcli.mdconfiguration.mderrors.mdindex.mdplugins.md
tile.json

tessl/pypi-refurb

A tool for refurbishing and modernizing Python codebases

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/refurb@2.1.x

To install, run

npx @tessl/cli install tessl/pypi-refurb@2.1.0

index.mddocs/

Refurb

A Python code analysis tool that specializes in modernizing and refurbishing Python codebases by detecting opportunities to make code more elegant, readable, and Pythonic. Built on Mypy for robust type analysis, Refurb identifies patterns where code can be simplified using modern Python features and idioms.

Package Information

  • Package Name: refurb
  • Language: Python
  • Installation: pip install refurb

Core Imports

import refurb

For the main CLI interface:

from refurb.main import main, run_refurb

For plugin development:

from refurb.error import Error
from refurb.settings import Settings
from refurb.visitor import RefurbVisitor
from refurb.checks.common import is_equivalent, stringify

Basic Usage

Command Line Usage

# Analyze files or directories
refurb src/

# Ignore specific error codes
refurb --ignore FURB105,FURB123 src/

# Enable additional checks
refurb --enable FURB999 src/

# Load custom checks
refurb --load my_custom_checks src/

# Output as GitHub annotations
refurb --format github src/

# Get explanation for an error
refurb --explain FURB105

# Generate boilerplate for new check
refurb gen

Programmatic Usage

from refurb.main import run_refurb
from refurb.settings import load_settings

# Load settings from command line args
settings = load_settings(["src/", "--ignore", "FURB105"])

# Run refurb analysis
errors = run_refurb(settings)

# Process results
for error in errors:
    if isinstance(error, str):
        print(f"Error: {error}")
    else:
        print(f"{error.filename}:{error.line}:{error.column} [{error.prefix}{error.code}]: {error.msg}")

Architecture

Refurb uses a multi-phase architecture built on Mypy's AST and type analysis:

  • Settings System: Handles CLI parsing and configuration file loading
  • Check Loader: Discovers and loads built-in and plugin checks
  • Mypy Integration: Leverages Mypy's type checker for AST parsing and type information
  • Visitor Pattern: Traverses AST nodes to run applicable checks
  • Error System: Collects, filters, and formats analysis results

The tool includes 94 built-in checks organized into 20+ categories, covering everything from basic readability improvements to advanced standard library usage patterns. A comprehensive plugin system allows custom checks to be easily integrated.

Capabilities

Command Line Interface

Primary interface for code analysis with comprehensive options for configuration, error filtering, output formatting, and integration with development workflows.

def main(args: list[str]) -> int:
    """
    Main CLI entry point.
    
    Parameters:
    - args: Command line arguments
    
    Returns:
    Exit code (0 for success, 1 for errors)
    """

def usage() -> None:
    """Display comprehensive help information."""

def version() -> str:
    """Get version information for refurb and mypy."""

Command Line Interface

Core Analysis Engine

The heart of refurb's code analysis, managing the integration with Mypy, check execution, and error collection.

def run_refurb(settings: Settings) -> Sequence[Error | str]:
    """
    Execute refurb analysis on specified files.
    
    Parameters:
    - settings: Configuration object containing all analysis options
    
    Returns:
    Sequence of Error objects or error strings
    """

Core Analysis

Error System

Comprehensive error handling including error definitions, classification, filtering, and formatting for various output targets.

class Error:
    """Base error class for all refurb findings."""
    line: int
    column: int
    msg: str
    filename: str | None
    line_end: int | None
    column_end: int | None

class ErrorCode:
    """Error code identifier."""
    id: int
    prefix: str
    path: str | None

class ErrorCategory:
    """Error category for grouping related checks."""
    value: str
    path: str | None

Error System

Settings and Configuration

Powerful configuration system supporting CLI arguments, TOML configuration files, and path-specific amendment rules.

class Settings:
    """Main configuration class containing all analysis options."""
    files: list[str]
    ignore: set[ErrorClassifier]
    enable: set[ErrorClassifier]
    disable: set[ErrorClassifier]
    load: list[str]
    # ... extensive configuration options

def load_settings(args: list[str]) -> Settings:
    """Parse CLI args and config files into Settings object."""

Configuration

Plugin Development Framework

Complete framework for developing custom checks with AST analysis utilities, type checking helpers, and visitor patterns.

class RefurbVisitor:
    """Main visitor for running checks on AST nodes."""
    def __init__(self, checks: defaultdict[type[Node], list[Check]], settings: Settings): ...
    def run_check(self, node: Node, check: Check) -> None: ...

def load_checks(settings: Settings) -> defaultdict[type[Node], list[Check]]:
    """Load and filter checks based on settings."""

Plugin Development

AST Analysis Utilities

Comprehensive utilities for AST node analysis, type checking, and code pattern matching used by built-in checks and available for custom checks.

def is_equivalent(lhs: Node | None, rhs: Node | None) -> bool:
    """Compare AST nodes for equivalence."""

def stringify(node: Node) -> str:
    """Convert AST node to string representation."""

def get_mypy_type(node: Node) -> Type | SymbolNode | None:
    """Get Mypy type information for AST node."""

def is_same_type(ty: Type | SymbolNode | None, *expected: TypeLike) -> bool:
    """Check if type matches any of the expected types."""

AST Utilities

Built-in Check Categories

Refurb includes 94 comprehensive checks organized into focused categories:

  • builtin (21 checks): Core Python builtin improvements
  • readability (22 checks): Code readability and clarity
  • pathlib (15 checks): Modern path manipulation
  • string (7 checks): String operation optimizations
  • flow (4 checks): Control flow improvements
  • logical (3 checks): Logical expression simplification
  • itertools (2 checks), math (2 checks), regex (2 checks): Standard library optimizations
  • datetime (2 checks), hashlib (2 checks): Specialized improvements
  • Plus additional categories for collections, contextlib, decimal, function, functools, iterable, pattern matching, secrets, shlex, and third-party FastAPI support

Types

from typing import Callable, Sequence
from collections import defaultdict
from mypy.nodes import Node

# Type aliases for check system
Check = Callable[[Node, list[Error]], None] | Callable[[Node, list[Error], Settings], None]
Checks = defaultdict[type[Node], list[Check]]
ErrorClassifier = ErrorCategory | ErrorCode