0
# Core API Functions
1
2
Primary interface for checking Python code, supporting code strings, individual files, and recursive directory analysis. These functions provide the main entry points for integrating Pyflakes into development workflows and can be used programmatically or through command-line interfaces.
3
4
## Capabilities
5
6
### Code String Analysis
7
8
Analyzes Python source code from a string, allowing direct integration into development tools and workflows without requiring file system access.
9
10
```python { .api }
11
def check(codeString: str, filename: str, reporter=None) -> int:
12
"""
13
Check the Python source given by codeString for flakes.
14
15
Parameters:
16
- codeString (str): The Python source to check
17
- filename (str): The name of the file the source came from, used to report errors
18
- reporter (Reporter, optional): A Reporter instance where errors and warnings will be reported
19
20
Returns:
21
int: The number of warnings emitted
22
"""
23
```
24
25
**Usage:**
26
27
```python
28
import pyflakes.api
29
30
code = """
31
import os
32
unused_var = 42
33
print(undefined_var)
34
"""
35
36
# Check with default reporter (prints to stdout/stderr)
37
warnings = pyflakes.api.check(code, 'example.py')
38
print(f"Found {warnings} warnings")
39
40
# Check with custom reporter
41
from pyflakes.reporter import Reporter
42
import io
43
44
warning_stream = io.StringIO()
45
error_stream = io.StringIO()
46
reporter = Reporter(warning_stream, error_stream)
47
48
warnings = pyflakes.api.check(code, 'example.py', reporter)
49
output = warning_stream.getvalue()
50
```
51
52
### File Analysis
53
54
Analyzes individual Python files, automatically handling file reading and encoding detection.
55
56
```python { .api }
57
def checkPath(filename: str, reporter=None) -> int:
58
"""
59
Check the given path, printing out any warnings detected.
60
61
Parameters:
62
- filename (str): Path to the Python file to check
63
- reporter (Reporter, optional): A Reporter instance where errors and warnings will be reported
64
65
Returns:
66
int: The number of warnings printed
67
"""
68
```
69
70
**Usage:**
71
72
```python
73
import pyflakes.api
74
75
# Check a single file
76
warnings = pyflakes.api.checkPath('mymodule.py')
77
78
# Check with custom reporter
79
from pyflakes.reporter import Reporter
80
import sys
81
82
reporter = Reporter(sys.stdout, sys.stderr)
83
warnings = pyflakes.api.checkPath('mymodule.py', reporter)
84
```
85
86
### Recursive Directory Analysis
87
88
Recursively analyzes multiple paths, automatically discovering and checking Python files in directories.
89
90
```python { .api }
91
def checkRecursive(paths: list, reporter) -> int:
92
"""
93
Recursively check all source files in paths.
94
95
Parameters:
96
- paths (list): A list of paths to Python source files and directories containing Python source files
97
- reporter (Reporter): A Reporter where all warnings and errors will be reported
98
99
Returns:
100
int: The number of warnings found
101
"""
102
```
103
104
**Usage:**
105
106
```python
107
import pyflakes.api
108
from pyflakes.reporter import Reporter
109
import sys
110
111
reporter = Reporter(sys.stdout, sys.stderr)
112
113
# Check multiple paths
114
paths = ['src/', 'tests/', 'setup.py']
115
total_warnings = pyflakes.api.checkRecursive(paths, reporter)
116
print(f"Total warnings found: {total_warnings}")
117
```
118
119
### Source Code Discovery
120
121
Iterates over all Python source files in given paths, supporting both files and directories.
122
123
```python { .api }
124
def iterSourceCode(paths: list):
125
"""
126
Iterate over all Python source files in paths.
127
128
Parameters:
129
- paths (list): A list of paths. Directories will be recursed into and any .py files found will be yielded. Any non-directories will be yielded as-is.
130
131
Yields:
132
str: File paths to Python source files
133
"""
134
```
135
136
**Usage:**
137
138
```python
139
import pyflakes.api
140
141
paths = ['src/', 'myfile.py', 'tests/']
142
143
for source_file in pyflakes.api.iterSourceCode(paths):
144
print(f"Found Python file: {source_file}")
145
warnings = pyflakes.api.checkPath(source_file)
146
```
147
148
### Python File Detection
149
150
Determines if a file is a Python source file by examining file extension and shebang lines.
151
152
```python { .api }
153
def isPythonFile(filename: str) -> bool:
154
"""
155
Return True if filename points to a Python file.
156
157
Parameters:
158
- filename (str): Path to file to check
159
160
Returns:
161
bool: True if the file is a Python source file
162
"""
163
```
164
165
**Usage:**
166
167
```python
168
import pyflakes.api
169
170
# Check various files
171
files = ['script.py', 'data.txt', 'script', 'backup.py~']
172
173
for filename in files:
174
if pyflakes.api.isPythonFile(filename):
175
print(f"{filename} is a Python file")
176
pyflakes.api.checkPath(filename)
177
```
178
179
### Command Line Interface
180
181
Entry point for the command-line pyflakes tool, supporting argument parsing and exit code handling.
182
183
```python { .api }
184
def main(prog=None, args=None):
185
"""
186
Entry point for the script "pyflakes".
187
188
Parameters:
189
- prog (str, optional): Program name for argument parser
190
- args (list, optional): Arguments to parse (defaults to sys.argv)
191
192
Raises:
193
SystemExit: Exits with status code 1 if warnings found, 0 otherwise
194
"""
195
```
196
197
**Usage:**
198
199
```python
200
import pyflakes.api
201
202
# Use programmatically
203
pyflakes.api.main(args=['src/', 'tests/'])
204
205
# The main function also supports:
206
# - Reading from stdin when no paths provided
207
# - Version information with -V/--version
208
# - Signal handling for SIGINT and SIGPIPE
209
```
210
211
## Constants
212
213
### Python Shebang Pattern
214
215
Regular expression for detecting Python shebang lines in files.
216
217
```python { .api }
218
PYTHON_SHEBANG_REGEX: re.Pattern
219
```
220
221
Compiled regex pattern: `br'^#!.*\bpython(3(\.\d+)?|w)?[dmu]?\s'`
222
223
**Usage:**
224
225
```python
226
import pyflakes.api
227
228
with open('script', 'rb') as f:
229
first_line = f.read(128)
230
if pyflakes.api.PYTHON_SHEBANG_REGEX.match(first_line):
231
print("This file has a Python shebang")
232
```
233
234
## Error Handling
235
236
All functions handle common error conditions gracefully:
237
238
- **Syntax errors**: Reported through the reporter system with line/column information
239
- **File I/O errors**: Reported as unexpected errors with descriptive messages
240
- **Encoding errors**: Handled during file reading with appropriate error messages
241
- **Signal handling**: SIGINT and SIGPIPE are handled gracefully in the main function
242
243
## Integration Examples
244
245
### Custom Workflow Integration
246
247
```python
248
import pyflakes.api
249
from pyflakes.reporter import Reporter
250
import io
251
252
def lint_code_with_custom_handling(code_string, filename):
253
"""Custom linting with structured error handling."""
254
warning_buffer = io.StringIO()
255
error_buffer = io.StringIO()
256
257
reporter = Reporter(warning_buffer, error_buffer)
258
warning_count = pyflakes.api.check(code_string, filename, reporter)
259
260
warnings = warning_buffer.getvalue().strip().split('\n') if warning_buffer.getvalue() else []
261
errors = error_buffer.getvalue().strip().split('\n') if error_buffer.getvalue() else []
262
263
return {
264
'warning_count': warning_count,
265
'warnings': warnings,
266
'errors': errors
267
}
268
269
# Usage
270
result = lint_code_with_custom_handling("import os\nprint(x)", "test.py")
271
print(f"Found {result['warning_count']} warnings")
272
for warning in result['warnings']:
273
print(f"Warning: {warning}")
274
```
275
276
### Batch Processing
277
278
```python
279
import pyflakes.api
280
from pyflakes.reporter import Reporter
281
import sys
282
283
def batch_check_files(file_list):
284
"""Check multiple files and collect results."""
285
reporter = Reporter(sys.stdout, sys.stderr)
286
results = {}
287
288
for filename in file_list:
289
print(f"Checking {filename}...")
290
warnings = pyflakes.api.checkPath(filename, reporter)
291
results[filename] = warnings
292
293
return results
294
295
# Usage
296
files = ['module1.py', 'module2.py', 'module3.py']
297
results = batch_check_files(files)
298
299
total_warnings = sum(results.values())
300
print(f"Total warnings across all files: {total_warnings}")
301
```
302
303
## Module Exports
304
305
### Public API
306
307
The `pyflakes.api` module exports the following functions:
308
309
```python { .api }
310
__all__ = ['check', 'checkPath', 'checkRecursive', 'iterSourceCode', 'main']
311
```
312
313
### Version Information
314
315
```python { .api }
316
import pyflakes
317
__version__ = pyflakes.__version__ # Current version: '3.4.0'
318
```
319
320
**Usage:**
321
322
```python
323
import pyflakes
324
325
print(f"Pyflakes version: {pyflakes.__version__}")
326
327
# Check what functions are available from api
328
from pyflakes.api import * # Imports: check, checkPath, checkRecursive, iterSourceCode, main
329
```
330
331
## Command Line Usage
332
333
The main function provides command-line interface access:
334
335
```bash
336
# Check single file
337
pyflakes myfile.py
338
339
# Check multiple files/directories
340
pyflakes src/ tests/ setup.py
341
342
# Check via module
343
python -m pyflakes myfile.py
344
345
# Check from stdin
346
cat myfile.py | pyflakes
347
348
# Show version
349
pyflakes --version
350
```