Pyflakes: Python Static Code Analysis
Pyflakes is a fast, lightweight static analysis tool that meticulously checks Python code for common programming errors without executing it. It primarily identifies issues such as unused imports, undefined names, and redefined variables. Focusing solely on error detection, rather than code style, it aims for speed and minimizes false positives. Currently at version 3.4.0, Pyflakes supports Python 3.9 and newer, and is actively maintained by the PyCQA organization.
Warnings
- breaking Pyflakes 3.x and newer officially supports Python 3.9+. Older Python versions (e.g., 2.x or Python 3.8 and below) are no longer supported, requiring users to upgrade their Python environment.
- gotcha Pyflakes is a static *error* checker, not a *style* checker. It will not report on PEP 8 violations, line length, or other stylistic concerns. Users expecting comprehensive linting (style + errors) should use tools like Flake8, which bundles Pyflakes.
- gotcha Pyflakes does not support configuration files for customizing rules, ignoring specific warnings, or defining project-specific settings. Its behavior is largely fixed by its code.
- breaking Pyflakes's internal API, particularly the structure of its error messages (e.g., `pyflakes.messages`), is not considered stable. Updates can change or remove message types, which may break third-party tools that integrate deeply with Pyflakes's programmatic output or internal modules.
Install
-
pip install pyflakes
Quickstart
import subprocess
import os
# Create a dummy Python file with an error
code_to_check = """
import os
def my_func():
x = 10
# y is used but not defined, 'os' is imported but unused
print(y)
"""
file_path = "temp_code.py"
with open(file_path, "w") as f:
f.write(code_to_check)
# Run pyflakes on the file
try:
result = subprocess.run(
["pyflakes", file_path],
capture_output=True,
text=True,
check=False # pyflakes exits with non-zero on errors
)
print("Pyflakes Output:\n" + result.stdout)
if result.stderr:
print("Pyflakes Error (stderr):\n" + result.stderr)
finally:
# Clean up the dummy file
if os.path.exists(file_path):
os.remove(file_path)
# Expected output might look like:
# temp_code.py:2: 'os' imported but unused
# temp_code.py:6: undefined name 'y'