Static analysis tool that detects errors in Python code without importing it.
—
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.
Analyzes Python source code from a string, allowing direct integration into development tools and workflows without requiring file system access.
def check(codeString: str, filename: str, reporter=None) -> int:
"""
Check the Python source given by codeString for flakes.
Parameters:
- codeString (str): The Python source to check
- filename (str): The name of the file the source came from, used to report errors
- reporter (Reporter, optional): A Reporter instance where errors and warnings will be reported
Returns:
int: The number of warnings emitted
"""Usage:
import pyflakes.api
code = """
import os
unused_var = 42
print(undefined_var)
"""
# Check with default reporter (prints to stdout/stderr)
warnings = pyflakes.api.check(code, 'example.py')
print(f"Found {warnings} warnings")
# Check with custom reporter
from pyflakes.reporter import Reporter
import io
warning_stream = io.StringIO()
error_stream = io.StringIO()
reporter = Reporter(warning_stream, error_stream)
warnings = pyflakes.api.check(code, 'example.py', reporter)
output = warning_stream.getvalue()Analyzes individual Python files, automatically handling file reading and encoding detection.
def checkPath(filename: str, reporter=None) -> int:
"""
Check the given path, printing out any warnings detected.
Parameters:
- filename (str): Path to the Python file to check
- reporter (Reporter, optional): A Reporter instance where errors and warnings will be reported
Returns:
int: The number of warnings printed
"""Usage:
import pyflakes.api
# Check a single file
warnings = pyflakes.api.checkPath('mymodule.py')
# Check with custom reporter
from pyflakes.reporter import Reporter
import sys
reporter = Reporter(sys.stdout, sys.stderr)
warnings = pyflakes.api.checkPath('mymodule.py', reporter)Recursively analyzes multiple paths, automatically discovering and checking Python files in directories.
def checkRecursive(paths: list, reporter) -> int:
"""
Recursively check all source files in paths.
Parameters:
- paths (list): A list of paths to Python source files and directories containing Python source files
- reporter (Reporter): A Reporter where all warnings and errors will be reported
Returns:
int: The number of warnings found
"""Usage:
import pyflakes.api
from pyflakes.reporter import Reporter
import sys
reporter = Reporter(sys.stdout, sys.stderr)
# Check multiple paths
paths = ['src/', 'tests/', 'setup.py']
total_warnings = pyflakes.api.checkRecursive(paths, reporter)
print(f"Total warnings found: {total_warnings}")Iterates over all Python source files in given paths, supporting both files and directories.
def iterSourceCode(paths: list):
"""
Iterate over all Python source files in paths.
Parameters:
- 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.
Yields:
str: File paths to Python source files
"""Usage:
import pyflakes.api
paths = ['src/', 'myfile.py', 'tests/']
for source_file in pyflakes.api.iterSourceCode(paths):
print(f"Found Python file: {source_file}")
warnings = pyflakes.api.checkPath(source_file)Determines if a file is a Python source file by examining file extension and shebang lines.
def isPythonFile(filename: str) -> bool:
"""
Return True if filename points to a Python file.
Parameters:
- filename (str): Path to file to check
Returns:
bool: True if the file is a Python source file
"""Usage:
import pyflakes.api
# Check various files
files = ['script.py', 'data.txt', 'script', 'backup.py~']
for filename in files:
if pyflakes.api.isPythonFile(filename):
print(f"{filename} is a Python file")
pyflakes.api.checkPath(filename)Entry point for the command-line pyflakes tool, supporting argument parsing and exit code handling.
def main(prog=None, args=None):
"""
Entry point for the script "pyflakes".
Parameters:
- prog (str, optional): Program name for argument parser
- args (list, optional): Arguments to parse (defaults to sys.argv)
Raises:
SystemExit: Exits with status code 1 if warnings found, 0 otherwise
"""Usage:
import pyflakes.api
# Use programmatically
pyflakes.api.main(args=['src/', 'tests/'])
# The main function also supports:
# - Reading from stdin when no paths provided
# - Version information with -V/--version
# - Signal handling for SIGINT and SIGPIPERegular expression for detecting Python shebang lines in files.
PYTHON_SHEBANG_REGEX: re.PatternCompiled regex pattern: br'^#!.*\bpython(3(\.\d+)?|w)?[dmu]?\s'
Usage:
import pyflakes.api
with open('script', 'rb') as f:
first_line = f.read(128)
if pyflakes.api.PYTHON_SHEBANG_REGEX.match(first_line):
print("This file has a Python shebang")All functions handle common error conditions gracefully:
import pyflakes.api
from pyflakes.reporter import Reporter
import io
def lint_code_with_custom_handling(code_string, filename):
"""Custom linting with structured error handling."""
warning_buffer = io.StringIO()
error_buffer = io.StringIO()
reporter = Reporter(warning_buffer, error_buffer)
warning_count = pyflakes.api.check(code_string, filename, reporter)
warnings = warning_buffer.getvalue().strip().split('\n') if warning_buffer.getvalue() else []
errors = error_buffer.getvalue().strip().split('\n') if error_buffer.getvalue() else []
return {
'warning_count': warning_count,
'warnings': warnings,
'errors': errors
}
# Usage
result = lint_code_with_custom_handling("import os\nprint(x)", "test.py")
print(f"Found {result['warning_count']} warnings")
for warning in result['warnings']:
print(f"Warning: {warning}")import pyflakes.api
from pyflakes.reporter import Reporter
import sys
def batch_check_files(file_list):
"""Check multiple files and collect results."""
reporter = Reporter(sys.stdout, sys.stderr)
results = {}
for filename in file_list:
print(f"Checking {filename}...")
warnings = pyflakes.api.checkPath(filename, reporter)
results[filename] = warnings
return results
# Usage
files = ['module1.py', 'module2.py', 'module3.py']
results = batch_check_files(files)
total_warnings = sum(results.values())
print(f"Total warnings across all files: {total_warnings}")The pyflakes.api module exports the following functions:
__all__ = ['check', 'checkPath', 'checkRecursive', 'iterSourceCode', 'main']import pyflakes
__version__ = pyflakes.__version__ # Current version: '3.4.0'Usage:
import pyflakes
print(f"Pyflakes version: {pyflakes.__version__}")
# Check what functions are available from api
from pyflakes.api import * # Imports: check, checkPath, checkRecursive, iterSourceCode, mainThe main function provides command-line interface access:
# Check single file
pyflakes myfile.py
# Check multiple files/directories
pyflakes src/ tests/ setup.py
# Check via module
python -m pyflakes myfile.py
# Check from stdin
cat myfile.py | pyflakes
# Show version
pyflakes --versionInstall with Tessl CLI
npx tessl i tessl/pypi-pyflakes