Pyflakes: Python Static Code Analysis

raw JSON →
3.4.0 verified Sat Apr 11 auth: no python quickstart: verified

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.

pip install pyflakes
error module imported but unused
cause Pyflakes detects an `import` statement for a module that is not subsequently referenced or used anywhere in the code.
fix
Remove the unused import statement to keep the codebase clean and avoid unnecessary dependencies.
error undefined name 'name'
cause This error occurs when a variable, function, or class name is used in the code without being defined or imported in the current scope.
fix
Ensure the 'name' is correctly defined before its first use, or that the necessary module/object containing 'name' is properly imported.
error local variable 'name' referenced before assignment
cause A local variable is accessed or used within a function before any value has been assigned to it in that function's scope.
fix
Initialize the variable with a default value before its first use, or ensure it is assigned a value on all possible code paths before being referenced. If intending to modify a global variable, use the global keyword.
error redefinition of unused name from line N
cause A name (e.g., a variable or function) is defined, but then defined again later in the same scope without its initial definition being used.
fix
Refactor the code to avoid redundant definitions. If the redefinition is intentional, ensure the first definition is used or remove the unnecessary initial definition.
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.
fix Upgrade your Python environment to 3.9 or a newer active version.
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.
fix For combined style and error checking, use `flake8` (`pip install flake8`) which integrates Pyflakes along with other tools like `pycodestyle` (formerly `pep8`) and `mccabe`.
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.
fix If configuration is required, consider using `flake8` which provides extensive configuration options, or integrate Pyflakes into a larger system that manages its invocation and output filtering.
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.
fix Integrators should rely on Pyflakes's standard command-line output parsing where possible, or pin Pyflakes to a specific minor version to prevent unexpected breakage from internal API changes.
gotcha Pyflakes is designed to identify common Python programming errors, including but not limited to, unused imports, variables assigned but never used, and references to undefined names. These findings indicate actual or potential issues in the codebase rather than stylistic concerns.
fix Review the reported issues in your code. Unused imports/variables may indicate dead code or refactoring opportunities. Undefined names are critical runtime errors. Address these directly or, if intentional, consider using appropriate suppression comments (e.g., '# noqa') as per Pyflakes's guidelines.

Demonstrates how to run Pyflakes from the command line on a Python file to detect errors. Pyflakes outputs issues to stdout.

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'