0
# Core Linting API
1
2
Main entry points and core functionality for running pylint analysis programmatically. These functions and classes provide the foundation for static code analysis, configuration management, and result collection.
3
4
## Capabilities
5
6
### Main Entry Points
7
8
Primary functions for running pylint analysis from Python code, providing programmatic access to pylint's command-line functionality.
9
10
```python { .api }
11
def run_pylint(argv=None):
12
"""
13
Run pylint analysis from command line arguments.
14
15
Args:
16
argv (list, optional): Command line arguments. If None, uses sys.argv[1:]
17
18
Example:
19
run_pylint(['mymodule.py', '--output-format=json'])
20
"""
21
22
def run_pyreverse(argv=None):
23
"""
24
Run pyreverse UML diagram generation.
25
26
Args:
27
argv (list, optional): Command line arguments. If None, uses sys.argv[1:]
28
29
Example:
30
run_pyreverse(['mypackage/', '--output-format=svg'])
31
"""
32
33
def run_symilar(argv=None):
34
"""
35
Run symilar duplicate code detection.
36
37
Args:
38
argv (list, optional): Command line arguments. If None, uses sys.argv[1:]
39
40
Example:
41
run_symilar(['mymodule.py', '--min-lines=5'])
42
"""
43
```
44
45
### System Path Management
46
47
Utility function for managing Python's module search path to prevent import conflicts during analysis.
48
49
```python { .api }
50
def modify_sys_path():
51
"""
52
Modify sys.path for execution as Python module.
53
54
Removes the current working directory from sys.path to prevent
55
pylint from inadvertently importing user code with the same names
56
as stdlib or pylint's own modules.
57
"""
58
```
59
60
### PyLinter Class
61
62
Main controller class that manages the entire checking process, configuration, checkers, and message collection.
63
64
```python { .api }
65
class PyLinter:
66
"""
67
Main linter class controlling the checking process.
68
69
Inherits from ArgumentsManager, MessageStateHandler,
70
ReportsHandlerMixIn, and BaseChecker.
71
"""
72
73
def check(self, files_or_modules):
74
"""
75
Check files or modules for issues.
76
77
Args:
78
files_or_modules (list): List of file paths or module names to check
79
"""
80
81
def register_checker(self, checker):
82
"""
83
Register a new checker with the linter.
84
85
Args:
86
checker: Instance of BaseChecker or subclass
87
"""
88
89
def get_checkers(self):
90
"""
91
Get all available checkers.
92
93
Returns:
94
dict: Mapping of checker names to checker instances
95
"""
96
97
def add_message(self, msgid, line=None, node=None, args=None,
98
confidence=None, col_offset=None):
99
"""
100
Add a message/warning to the results.
101
102
Args:
103
msgid (str): Message identifier (e.g., 'unused-variable')
104
line (int, optional): Line number
105
node (astroid.Node, optional): AST node
106
args (tuple, optional): Message arguments
107
confidence (str, optional): Confidence level
108
col_offset (int, optional): Column offset
109
"""
110
111
def check_astroid_module(self, ast_node, walker, rawcheckers):
112
"""
113
Check an astroid AST module.
114
115
Args:
116
ast_node: Astroid AST node
117
walker: AST walker instance
118
rawcheckers: List of raw file checkers
119
"""
120
121
def generate_reports(self):
122
"""Generate analysis reports."""
123
124
def set_reporter(self, reporter):
125
"""
126
Set the message reporter.
127
128
Args:
129
reporter: Instance of BaseReporter or subclass
130
"""
131
132
def load_default_plugins(self):
133
"""Load default plugin checkers."""
134
```
135
136
### Command Line Interface
137
138
Handler class for processing command-line arguments and executing the linter.
139
140
```python { .api }
141
class Run:
142
"""
143
Command-line interface handler for pylint.
144
145
Processes command-line arguments, configures the linter,
146
and executes the checking process.
147
"""
148
149
def __init__(self, args, reporter=None, exit=True, do_exit=None):
150
"""
151
Initialize and run pylint.
152
153
Args:
154
args (list): Command line arguments
155
reporter: Custom reporter instance
156
exit (bool): Whether to call sys.exit()
157
do_exit: Deprecated, use exit parameter
158
"""
159
```
160
161
### Parallel Processing
162
163
Functions for running pylint checks in parallel to improve performance on large codebases.
164
165
```python { .api }
166
def check_parallel(linter, jobs, files, extra_packages_paths=None):
167
"""
168
Run checking in parallel across multiple processes.
169
170
Args:
171
linter: PyLinter instance
172
jobs (int): Number of parallel jobs
173
files: Iterable of FileItem objects to check
174
extra_packages_paths (list, optional): Additional package paths
175
176
Returns:
177
None: Results are collected via the linter's reporter
178
"""
179
```
180
181
### Module Discovery
182
183
Utilities for expanding module names and discovering package paths.
184
185
```python { .api }
186
def expand_modules(files_or_modules, source_roots, ignore_list, ignore_list_re, ignore_list_paths_re):
187
"""
188
Expand module names to actual file paths.
189
190
Args:
191
files_or_modules (list): Module names or file paths to expand
192
source_roots (list): Source root directories for module discovery
193
ignore_list (list): File patterns to ignore
194
ignore_list_re (list): Compiled regex patterns to ignore files
195
ignore_list_paths_re (list): Compiled regex patterns to ignore paths
196
197
Returns:
198
tuple: (modules_dict, errors_list) where modules_dict maps module names
199
to module description dictionaries and errors_list contains
200
error descriptions for files that couldn't be processed
201
"""
202
203
def discover_package_path(modulepath, source_roots):
204
"""
205
Discover package path from a module path and source roots.
206
207
Args:
208
modulepath (str): Path to the module file or directory
209
source_roots (list): Source root directories to search
210
211
Returns:
212
str: Discovered package path
213
"""
214
```
215
216
### Result Caching
217
218
Functions for saving and loading analysis results to improve performance on repeated runs.
219
220
```python { .api }
221
def load_results(base):
222
"""
223
Load cached analysis results.
224
225
Args:
226
base (str): Base path for cache files
227
228
Returns:
229
dict: Cached results if available
230
"""
231
232
def save_results(results, base):
233
"""
234
Save analysis results to cache.
235
236
Args:
237
results: Analysis results to save
238
base (str): Base path for cache files
239
"""
240
```
241
242
## Usage Examples
243
244
### Basic Programmatic Usage
245
246
```python
247
import pylint
248
from pylint.lint import PyLinter
249
from pylint.reporters import TextReporter
250
import io
251
252
# Using the main entry point
253
pylint.run_pylint(['mymodule.py', '--errors-only'])
254
255
# Using PyLinter directly
256
output = io.StringIO()
257
reporter = TextReporter(output)
258
linter = PyLinter()
259
linter.set_reporter(reporter)
260
linter.check(['mymodule.py'])
261
print(output.getvalue())
262
```
263
264
### Custom Configuration
265
266
```python
267
from pylint.lint import PyLinter
268
from pylint.reporters import JSONReporter
269
270
linter = PyLinter()
271
linter.set_reporter(JSONReporter())
272
273
# Register custom checker
274
from mylinter.custom_checker import MyCustomChecker
275
linter.register_checker(MyCustomChecker(linter))
276
277
# Configure options
278
linter.config.max_line_length = 120
279
linter.config.disable = ['missing-docstring']
280
281
linter.check(['mypackage/'])
282
```
283
284
### Parallel Processing
285
286
```python
287
from pylint.lint import PyLinter, check_parallel
288
import multiprocessing
289
290
linter = PyLinter()
291
files = ['module1.py', 'module2.py', 'module3.py']
292
jobs = multiprocessing.cpu_count()
293
294
stats = check_parallel(files, linter, jobs)
295
print(f"Total errors: {stats.error}")
296
print(f"Total warnings: {stats.warning}")
297
```