Pyflakes: Python Static Code Analysis

3.4.0 · active · verified Sat Mar 28

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

Install

Quickstart

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'

view raw JSON →