{"id":6365,"library":"flake8-expression-complexity","title":"flake8-expression-complexity","description":"flake8-expression-complexity is an extension for Flake8 that enforces limits on the complexity of individual expressions within Python code. It works by analyzing abstract syntax tree (AST) nodes to score expressions and reports an `ECE001` error when a configurable threshold is exceeded. The current version is 0.0.11, and it maintains a moderate release cadence, with updates addressing new features and bug fixes.","status":"active","version":"0.0.11","language":"en","source_language":"en","source_url":"https://github.com/best-doctor/flake8-expression-complexity","tags":["flake8","linter","code quality","complexity analysis","expression complexity"],"install":[{"cmd":"pip install flake8-expression-complexity","lang":"bash","label":"Install with pip"}],"dependencies":[{"reason":"This library is a plugin for Flake8 and requires Flake8 to be installed and run.","package":"flake8","optional":false}],"imports":[{"note":"Flake8 plugins are not imported directly in Python code. Instead, they extend the functionality of the `flake8` command-line tool through entry points.","symbol":"Automatic Plugin Discovery","correct":"This plugin is automatically discovered by Flake8 once installed. No direct Python import is needed; it integrates directly with the `flake8` command-line tool."}],"quickstart":{"code":"import datetime\n\nclass User:\n    def __init__(self, is_authorized, credits, subscriptions):\n        self.is_authorized = is_authorized\n        self.total_credits_added = credits\n        self.subscriptions = subscriptions\n\nclass Subscription:\n    def __init__(self, start_date, end_date):\n        self.start_date = start_date\n        self.end_date = end_date\n\n    def exists(self):\n        today = datetime.date.today()\n        return self.start_date < today and self.end_date > today\n\nclass Check:\n    def __init__(self, user, price):\n        self.user = user\n        self.price = price\n\n    @staticmethod\n    def objects_filter_aggregate_sum(user_obj):\n        # Simulate a complex ORM query result for demonstration\n        # In a real scenario, this would involve database interaction\n        if user_obj.is_authorized: # simplified logic\n            return {'check__sum': 100}\n        return {'check__sum': 0}\n\nclass UserAction:\n    def __init__(self, datetime_val):\n        self.datetime = datetime_val\n\n    @staticmethod\n    def objects_filter_last_datetime(user_obj):\n        # Simulate fetching last action datetime\n        # In a real scenario, this would involve database interaction\n        return UserAction(datetime.datetime.now())\n\ndef example_function(user):\n    today = datetime.date.today()\n    # This expression will likely exceed the default complexity threshold\n    if (\n        (user and user.is_authorized)\n        and user.subscriptions.exists() # Simplified to use Subscription.exists\n        and (\n            user.total_credits_added - Check.objects_filter_aggregate_sum(user)['check__sum'] # Simulate aggregate\n        )\n        and UserAction.objects_filter_last_datetime(user).datetime > datetime.datetime.now() - datetime.timedelta(days=10)\n    ):\n        print(\"User meets complex conditions.\")\n\n# To run flake8 with this plugin, save the above code to 'test_complexity.py'\n# and execute in your terminal:\n# flake8 --max-expression-complexity=3 test_complexity.py","lang":"python","description":"After installing, `flake8-expression-complexity` automatically integrates with the `flake8` command. To use it, simply run `flake8` against your Python files. The plugin provides the `ECE001` error code. You can configure the maximum allowed expression complexity using the `--max-expression-complexity` command-line option or in a configuration file (e.g., `setup.cfg`, `tox.ini`, or `.flake8`). The example demonstrates a highly complex `if` condition that would typically trigger an `ECE001` error with a low `max-expression-complexity` setting."},"warnings":[{"fix":"Review the flagged expressions carefully. If the complexity is deemed acceptable for readability, consider increasing the `--max-expression-complexity` threshold or using `# noqa: ECE001` for specific lines. Restructuring chained calls into intermediate variables might also reduce reported complexity.","message":"Chained method calls can result in unexpectedly high complexity scores. The plugin's calculation might consider each method call in a chain as contributing significantly to expression complexity (e.g., `obj.method1().method2().method3()` could be flagged as complex), even if it appears readable.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Adjust the threshold using `--max-expression-complexity=<VALUE>` on the command line or `max-expression-complexity = <VALUE>` in your Flake8 configuration file (`setup.cfg`, `tox.ini`, or `.flake8`). Experiment with values to find a suitable balance for your codebase.","message":"The default `max-expression-complexity` is 7, which may be too strict or too lenient depending on your project's coding style and requirements.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Understand the difference: ECE001 relates to the complexity of a single line/expression, while C901 relates to the number of independent paths through a function. Configure both plugins independently to manage different aspects of code complexity. `flake8-expression-complexity` adds ECE001; `mccabe` adds C901.","message":"This plugin specifically targets expression complexity (ECE001), which is distinct from the cyclomatic complexity of functions (C901) checked by Flake8's built-in `mccabe` plugin. Users often confuse these two, leading to misinterpretations of the reported errors.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Enable the `--ignore-django-orm-queries-complexity` option when running `flake8` or set `ignore-django-orm-queries-complexity = True` in your Flake8 configuration file to prevent false positives on Django ORM queries.","message":"For projects utilizing Django ORM, queries can naturally become long and appear complex, triggering `ECE001` errors despite being semantically straightforward.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-15T00:00:00.000Z","next_check":"2026-07-14T00:00:00.000Z"}