A tool for refurbishing and modernizing Python codebases
npx @tessl/cli install tessl/pypi-refurb@2.1.00
# Refurb
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: refurb
7
- **Language**: Python
8
- **Installation**: `pip install refurb`
9
10
## Core Imports
11
12
```python
13
import refurb
14
```
15
16
For the main CLI interface:
17
18
```python
19
from refurb.main import main, run_refurb
20
```
21
22
For plugin development:
23
24
```python
25
from refurb.error import Error
26
from refurb.settings import Settings
27
from refurb.visitor import RefurbVisitor
28
from refurb.checks.common import is_equivalent, stringify
29
```
30
31
## Basic Usage
32
33
### Command Line Usage
34
35
```bash
36
# Analyze files or directories
37
refurb src/
38
39
# Ignore specific error codes
40
refurb --ignore FURB105,FURB123 src/
41
42
# Enable additional checks
43
refurb --enable FURB999 src/
44
45
# Load custom checks
46
refurb --load my_custom_checks src/
47
48
# Output as GitHub annotations
49
refurb --format github src/
50
51
# Get explanation for an error
52
refurb --explain FURB105
53
54
# Generate boilerplate for new check
55
refurb gen
56
```
57
58
### Programmatic Usage
59
60
```python
61
from refurb.main import run_refurb
62
from refurb.settings import load_settings
63
64
# Load settings from command line args
65
settings = load_settings(["src/", "--ignore", "FURB105"])
66
67
# Run refurb analysis
68
errors = run_refurb(settings)
69
70
# Process results
71
for error in errors:
72
if isinstance(error, str):
73
print(f"Error: {error}")
74
else:
75
print(f"{error.filename}:{error.line}:{error.column} [{error.prefix}{error.code}]: {error.msg}")
76
```
77
78
## Architecture
79
80
Refurb uses a multi-phase architecture built on Mypy's AST and type analysis:
81
82
- **Settings System**: Handles CLI parsing and configuration file loading
83
- **Check Loader**: Discovers and loads built-in and plugin checks
84
- **Mypy Integration**: Leverages Mypy's type checker for AST parsing and type information
85
- **Visitor Pattern**: Traverses AST nodes to run applicable checks
86
- **Error System**: Collects, filters, and formats analysis results
87
88
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.
89
90
## Capabilities
91
92
### Command Line Interface
93
94
Primary interface for code analysis with comprehensive options for configuration, error filtering, output formatting, and integration with development workflows.
95
96
```python { .api }
97
def main(args: list[str]) -> int:
98
"""
99
Main CLI entry point.
100
101
Parameters:
102
- args: Command line arguments
103
104
Returns:
105
Exit code (0 for success, 1 for errors)
106
"""
107
108
def usage() -> None:
109
"""Display comprehensive help information."""
110
111
def version() -> str:
112
"""Get version information for refurb and mypy."""
113
```
114
115
[Command Line Interface](./cli.md)
116
117
### Core Analysis Engine
118
119
The heart of refurb's code analysis, managing the integration with Mypy, check execution, and error collection.
120
121
```python { .api }
122
def run_refurb(settings: Settings) -> Sequence[Error | str]:
123
"""
124
Execute refurb analysis on specified files.
125
126
Parameters:
127
- settings: Configuration object containing all analysis options
128
129
Returns:
130
Sequence of Error objects or error strings
131
"""
132
```
133
134
[Core Analysis](./analysis.md)
135
136
### Error System
137
138
Comprehensive error handling including error definitions, classification, filtering, and formatting for various output targets.
139
140
```python { .api }
141
class Error:
142
"""Base error class for all refurb findings."""
143
line: int
144
column: int
145
msg: str
146
filename: str | None
147
line_end: int | None
148
column_end: int | None
149
150
class ErrorCode:
151
"""Error code identifier."""
152
id: int
153
prefix: str
154
path: str | None
155
156
class ErrorCategory:
157
"""Error category for grouping related checks."""
158
value: str
159
path: str | None
160
```
161
162
[Error System](./errors.md)
163
164
### Settings and Configuration
165
166
Powerful configuration system supporting CLI arguments, TOML configuration files, and path-specific amendment rules.
167
168
```python { .api }
169
class Settings:
170
"""Main configuration class containing all analysis options."""
171
files: list[str]
172
ignore: set[ErrorClassifier]
173
enable: set[ErrorClassifier]
174
disable: set[ErrorClassifier]
175
load: list[str]
176
# ... extensive configuration options
177
178
def load_settings(args: list[str]) -> Settings:
179
"""Parse CLI args and config files into Settings object."""
180
```
181
182
[Configuration](./configuration.md)
183
184
### Plugin Development Framework
185
186
Complete framework for developing custom checks with AST analysis utilities, type checking helpers, and visitor patterns.
187
188
```python { .api }
189
class RefurbVisitor:
190
"""Main visitor for running checks on AST nodes."""
191
def __init__(self, checks: defaultdict[type[Node], list[Check]], settings: Settings): ...
192
def run_check(self, node: Node, check: Check) -> None: ...
193
194
def load_checks(settings: Settings) -> defaultdict[type[Node], list[Check]]:
195
"""Load and filter checks based on settings."""
196
```
197
198
[Plugin Development](./plugins.md)
199
200
### AST Analysis Utilities
201
202
Comprehensive utilities for AST node analysis, type checking, and code pattern matching used by built-in checks and available for custom checks.
203
204
```python { .api }
205
def is_equivalent(lhs: Node | None, rhs: Node | None) -> bool:
206
"""Compare AST nodes for equivalence."""
207
208
def stringify(node: Node) -> str:
209
"""Convert AST node to string representation."""
210
211
def get_mypy_type(node: Node) -> Type | SymbolNode | None:
212
"""Get Mypy type information for AST node."""
213
214
def is_same_type(ty: Type | SymbolNode | None, *expected: TypeLike) -> bool:
215
"""Check if type matches any of the expected types."""
216
```
217
218
[AST Utilities](./ast-utilities.md)
219
220
## Built-in Check Categories
221
222
Refurb includes 94 comprehensive checks organized into focused categories:
223
224
- **builtin** (21 checks): Core Python builtin improvements
225
- **readability** (22 checks): Code readability and clarity
226
- **pathlib** (15 checks): Modern path manipulation
227
- **string** (7 checks): String operation optimizations
228
- **flow** (4 checks): Control flow improvements
229
- **logical** (3 checks): Logical expression simplification
230
- **itertools** (2 checks), **math** (2 checks), **regex** (2 checks): Standard library optimizations
231
- **datetime** (2 checks), **hashlib** (2 checks): Specialized improvements
232
- Plus additional categories for collections, contextlib, decimal, function, functools, iterable, pattern matching, secrets, shlex, and third-party FastAPI support
233
234
## Types
235
236
```python { .api }
237
from typing import Callable, Sequence
238
from collections import defaultdict
239
from mypy.nodes import Node
240
241
# Type aliases for check system
242
Check = Callable[[Node, list[Error]], None] | Callable[[Node, list[Error], Settings], None]
243
Checks = defaultdict[type[Node], list[Check]]
244
ErrorClassifier = ErrorCategory | ErrorCode
245
```