Flake8 Comprehensions

3.17.0 · active · verified Sat Apr 11

A Flake8 plugin designed to help developers write more efficient and Pythonic list, set, and dictionary comprehensions. It detects common anti-patterns and suggests idiomatic alternatives. The current version is 3.17.0, and it maintains a regular release cadence with updates to rules and Python compatibility.

Warnings

Install

Imports

Quickstart

After installing `flake8` and `flake8-comprehensions`, run `flake8` on your Python files. The plugin will automatically integrate. If you use Flake8's `select` option, ensure you include the `C4` prefix to enable its checks.

import os

def analyze_code(file_content):
    # Simulate a file for flake8
    with open('temp_code.py', 'w') as f:
        f.write(file_content)
    
    # Run flake8 with the plugin
    # In a real scenario, you'd run 'flake8 temp_code.py' from the command line
    # This example demonstrates the plugin's effect.
    print(f"Running flake8 on:\n---\n{file_content}\n---")
    # To actually run flake8 programmatically and capture output, 
    # one would typically use subprocess.run(['flake8', 'temp_code.py'], capture_output=True)
    # For this quickstart, we'll illustrate the problematic code.


# Example of code that flake8-comprehensions would flag
bad_list_comp = """
def get_numbers():
    items = range(5)
    # C400: Unnecessary generator - rewrite as a list comprehension
    result = list(x for x in items)
    # C403: Unnecessary list comprehension - rewrite as a set comprehension
    another = set([x * 2 for x in items])
    # C404: Unnecessary list comprehension - rewrite as a dict comprehension
    mapping = dict([(i, str(i)) for i in items])
    # C416: Unnecessary list comprehension - rewrite using list()
    unchanged = [x for x in items]
    return result, another, mapping, unchanged
"""

# In a terminal, after 'pip install flake8 flake8-comprehensions':
# Save the above 'bad_list_comp' content to 'my_module.py'
# Then run: flake8 my_module.py
# This will output warnings like:
# my_module.py:5:14: C400 Unnecessary generator - rewrite as a list comprehension.
# my_module.py:7:17: C403 Unnecessary list comprehension - rewrite as a set comprehension.
# my_module.py:9:17: C404 Unnecessary list comprehension - rewrite as a dict comprehension.
# my_module.py:11:15: C416 Unnecessary list comprehension - rewrite using list().

# For illustrative purposes, not actual execution of flake8
# analyze_code(bad_list_comp)

view raw JSON →