wemake-python-styleguide

repository·master·Indexed 25 days ago

https://github.com/wemake-services/wemake-python-styleguide

A strict and opinionated flake8 plugin designed to reduce code complexity, enforce best practices, and ensure consistent Python code. It provides a comprehensive set of rules (WPS), a custom formatter, and a CLI tool called `wps` for explaining violations. The package is intended to complement tools like ruff and includes detailed guides for creating new linting rules using AST and tokenize-based visitors.

Tokens
9.2K
Snippets
33
Records
78
Agent score
78%

What's inside wemake-python-styleguide

  1. Understand the wemake-python-styleguide architecture

    master

    The linter operates as a flake8 plugin using a specific sequence of components to identify code issues:

    1. flake8: Runs the Checker alongside other plugins.
    2. Checker: Orchestrates the process by requesting Transformation steps before analysis begins.
    3. Transformation: Performs AST (Abstract Syntax Tree) transformations.
    4. Visitor: The Checker runs various Visitor instances that traverse the code.
    5. Violation: Visitor instances raise Violation objects when bad code is detected, which are then reported by flake8 to the user.
  2. Understand wemake-python-styleguide terminology

    master

    To effectively use or extend wemake-python-styleguide, familiarize yourself with the following core concepts:

    • rule: A specific decision regarding how Python code should or should not be written.
    • violation: A stylistic or semantic error that breaks a rule. Each violation includes reasoning, a solution, and code examples. Some violations are configurable.
    • plugin: An application compatible with flake8.
    • wemake_python_styleguide: A flake8 plugin representing a set of rules used at wemake.services.
    • checker: A flake8-compatible class that serves as a plugin entry point and runs all registered visitors.
    • formatter: A flake8-compatible class that displays results (violations) to the user.
    • visitor: An object that traverses ast, tokenize, or other nodes to identify violations of rules.
    • preset: A collection of visitor classes passed to the checker to be executed.
    • transformation: A method for modifying existing ast nodes (adding properties, fixing errors, deleting, or replacing nodes).
  3. Implement business logic in a visitor

    master

    To implement the actual checking logic, define protected methods within your visitor class that raise a violation. Use self.add_violation(ViolationClass(node)) to report issues.

    If logic is reused across multiple visitors, move it to the logics/ package to decouple it.

    class WrongComprehensionVisitor(BaseNodeVisitor):
        _max_ifs = 1
    
        def _check_ifs(self, node: ast.comprehension) -> None:
            if len(node.ifs) > self._max_ifs:
                # This will restrict to have more than 1 `if`
                # in your comprehensions:
                self.add_violation(MultipleIfsInComprehensionViolation(node))
    
        def visit_comprehension(self, node: ast.comprehension) -> None:
            self._check_ifs(node)
            self.generic_visit(node)
  4. Choose the correct base class for a new visitor

    master

    When writing a built-in extension, you must select a base class from wemake_python_styleguide.visitors.base based on the scope of the linting task:

    • Filename-based visitor: Use this if you need to lint module names (e.g., disallowing numbers in filenames).
    • tokenize-based visitor: Use this for low-level lexical analysis (e.g., disallowing specific characters or tokens like the number 3).
    • ast-based visitor: Use this for structural analysis of the code (e.g., disallowing multiplication of exactly two numbers).
  5. Configure PyCharm LSP server for wemake-python-styleguide

    master

    For the richest IDE integration (inline diagnostics, hover tooltips, and quick fixes), use python-lsp-server with the LSP4IJ plugin.

    1. Install LSP4IJ Plugin

    Go to Settings → Plugins → Marketplace, search for LSP4IJ, and install it.

    2. Install python-lsp-server

    Install the server with the necessary plugins using uv:

    uv tool install \
      --with flake8 \
      --with wemake-python-styleguide \
      --with pyls-flake8 \
      python-lsp-server

    3. Set up the Server Definition

    1. Find the pylsp executable path (run where pylsp or which pylsp).
    2. Open Settings → Languages & Frameworks → Language Server Protocol → Server Definitions.
    3. Click + to add a new server.
    4. Set Name to pylsp-wps and Path to your pylsp executable.
    5. In the Configuration tab, paste the following JSON:
    {
      "pylsp": {
        "plugins": {
          "flake8": {
            "enabled": true,
            "select": ["WPS", "E"]
          },
          "pycodestyle": { "enabled": false },
          "pyflakes": { "enabled": false },
          "mccabe": { "enabled": false }
        }
      }
    }
    1. In Mappings, add Python as the language.
    2. Click OK and restart PyCharm.

    4. Verify

    Open a Python file and introduce an intentional WPS violation to check for inline squiggles and hover tooltips.

  6. Configure PyCharm File Watcher for wemake-python-styleguide

    master

    Use a custom File Watcher to get real-time feedback on every file save. This approach is useful if the Flake8 Support plugin does not pick up your WPS installation.

    1. Open Settings (or Preferences on macOS).
    2. Navigate to Tools → File Watchers.
    3. Click + and choose <custom>.
    4. Configure the following settings:
      • Name: wemake-python-styleguide
      • File type: Python
      • Scope: Project Files
      • Program: flake8 (or the full path to the binary)
      • Arguments: --select=WPS $FilePath$
      • Output paths to refresh: $FilePath$
      • Working directory: $ProjectFileDir$
    5. In the Advanced Options section, enable:
      • Auto-save edited files to trigger the watcher
      • Trigger the watcher on external changes
    6. Click OK.