### Install wemake-python-styleguide using pip Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_sources/pages/usage/setup This snippet shows the command to install the wemake-python-styleguide package using pip. It's a straightforward installation process. ```bash pip install wemake-python-styleguide ``` -------------------------------- ### Install Dependencies with Poetry Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/api/contributing Installs project dependencies using the poetry package manager. Ensure poetry is installed before running this command. ```bash poetry install ``` -------------------------------- ### Install wemake-python-styleguide Source: https://wemake-python-styleguide.readthedocs.io/en/latest/index Installs the wemake-python-styleguide package using pip. This is the first step to using the linter in your Python project. ```bash pip install wemake-python-styleguide ``` -------------------------------- ### Basic wemake-python-styleguide GitHub Action Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/integrations/github-actions Demonstrates the fundamental setup for using the wemake-python-styleguide action in a GitHub workflow. This is the simplest way to include the style guide check. ```yaml - name: wemake-python-styleguide uses: wemake-services/wemake-python-styleguide ``` -------------------------------- ### Travis CI Configuration for Wemake Python Styleguide Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_sources/pages/usage/integrations/ci This YAML configuration sets up Travis CI to use Python 3.7 and install the wemake-python-styleguide. It then runs flake8 against the project. ```yaml dist: xenial language: python python: 3.7 install: pip install wemake-python-styleguide script: flake8 . ``` -------------------------------- ### Improve docs: readme ready for release Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/changelog/index This documentation improvement indicates that the README file is now ready for release. This suggests updates to project information, setup instructions, or usage examples in the README. ```text Improves docs: readme is now ready for the release ``` -------------------------------- ### Run Docker Container Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_sources/pages/usage/integrations/docker Runs the wemake-python-styleguide Docker container. This command executes the style guide on the current directory. ```bash docker run --rm wemakeservices/wemake-python-styleguide . ``` -------------------------------- ### Gitlab CI Configuration for Wemake Python Styleguide Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_sources/pages/usage/integrations/ci This Gitlab CI configuration uses a Python 3.12 Docker image. It first installs the wemake-python-styleguide and then executes flake8. ```yaml image: python3.12 test: before_script: pip install wemake-python-styleguide script: flake8 . ``` -------------------------------- ### Improve docs: add plugin development guide Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/changelog/index This documentation improvement introduces a guide for plugin development. This assists users who wish to extend the project's functionality by creating their own plugins. ```text Improves docs: adds new plugin development guide ``` -------------------------------- ### Python AST Visitor Example Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/api/tutorial Demonstrates subclassing an AST-based visitor for code linting. This is useful for analyzing the structure of Python code. ```python from wemake_python_styleguide.visitors.ast import ASTVisitor class MyAwesomeVisitor(ASTVisitor): pass ``` -------------------------------- ### BaseVisitor API Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/visitors/base Documentation for the BaseVisitor abstract class, which serves as the foundation for all visitors in the style guide. It outlines initialization, violation handling, and the abstract run method. ```APIDOC ## BaseVisitor ### Description Abstract base class for different types of visitors. Handles options, filename, and collects violations. ### Class `BaseVisitor` ### Methods #### `__init__(self, options: ValidatedOptions, filename: str = constants.STDIN)` Initializes the BaseVisitor instance with options and filename. #### `from_checker(cls: type['BaseVisitor'], checker) -> 'BaseVisitor'` Constructs a visitor instance from a checker object. Requires concrete visitor classes to implement their specific instantiation logic. #### `add_violation(self, violation: BaseViolation)` Adds a `BaseViolation` instance to the visitor's violations list. It asserts that the violation is not disabled. #### `run(self)` Abstract method that concrete visitors must implement to define their execution logic. #### `_post_visit(self)` Hook method executed after all nodes have been visited. Intended for post-processing or statistics. Does nothing by default. ### Attributes - **options**: `ValidatedOptions` - The parsed options for the style guide. - **filename**: `str` - The name of the file being processed. - **violations**: `list[BaseViolation]` - A list to store collected violations. ``` -------------------------------- ### Install Spell Checking Tools Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/api/contributing Installs codespell and flake8-spellcheck for identifying spelling and grammar errors in the project. ```bash pip install codespell flake8-spellcheck ``` -------------------------------- ### Basic GitHub Action Setup Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_sources/pages/usage/integrations/github-actions This snippet shows the most basic way to integrate the wemake-python-styleguide GitHub Action into a workflow. It uses the default settings and does not specify a version, implying the latest available version will be used. ```yaml - name: wemake-python-styleguide uses: wemake-services/wemake-python-styleguide ``` -------------------------------- ### Python Tokenize Visitor Example Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/api/tutorial Shows how to subclass a tokenize-based visitor. This approach is suitable for linting based on the token stream of Python code. ```python from wemake_python_styleguide.visitors.tokenize import TokenVisitor class MyAwesomeVisitor(TokenVisitor): pass ``` -------------------------------- ### Run Linting with Flake8 Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/api/contributing Performs linting on the current directory using flake8 to check for style guide violations. ```bash flake8 . ``` -------------------------------- ### Python Violation Example Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/api/tutorial Provides an example of creating a new violation. The base class for the violation depends on the chosen visitor type. ```python from wemake_python_styleguide.violations import ASTViolation class MyAwesomeViolation(ASTViolation): pass ``` -------------------------------- ### Python Filename Visitor Example Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/api/tutorial Illustrates subclassing a filename-based visitor. This is helpful for rules that depend on the file's name or path. ```python from wemake_python_styleguide.visitors.filename import FileNameVisitor class MyAwesomeVisitor(FileNameVisitor): pass ``` -------------------------------- ### Pre-commit Configuration for Wemake Python Styleguide Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_sources/pages/usage/integrations/ci This YAML configuration adds the wemake-python-styleguide as a pre-commit hook. It specifies the repository, revision, and hook ID. ```yaml repos: - repo: https://github.com/wemake-services/wemake-python-styleguide rev: ... hooks: - id: wemake-python-styleguide ``` -------------------------------- ### Add Complex Example to ParametersIndentationViolation (Python) Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/changelog/index Includes a more complex example for the ParametersIndentationViolation rule to better illustrate its usage and expected formatting. This helps users understand and fix indentation issues in function parameters. ```Python * Add more complex example to `ParametersIndentationViolation` #1021 ``` -------------------------------- ### GitHub Action - Using Outputs Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_sources/pages/usage/integrations/github-actions This example demonstrates how to capture and use the outputs from the wemake-python-styleguide Action in subsequent steps of a GitHub Actions workflow. The output is accessed via the 'steps..outputs.' syntax. ```yaml - name: wemake-python-styleguide uses: wememake-services/wemake-python-styleguide - name: Custom Action runs: echo "{{ steps.wemake-python-styleguide.outputs.output }}" ``` -------------------------------- ### Improve tests: add many new examples Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/changelog/index This test improvement involves adding a significant number of new examples. This enhances test coverage and provides more comprehensive validation of the project's functionality. ```text Improves tests: adds many new examples ``` -------------------------------- ### ProtectedModuleMemberViolation Example Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/violations/best_practices Provides examples of correct and incorrect ways to import members from Python modules, focusing on avoiding protected members. ```python # Correct: from some.public.module import FooClass # Wrong: from some.module import _protected from some.module import _protected as not_protected ``` -------------------------------- ### Add wemake-python-styleguide badge (Markdown) Source: https://wemake-python-styleguide.readthedocs.io/en/latest/index Provides the Markdown code to include a badge in your README file, indicating that your project uses wemake-python-styleguide. This visually communicates your project's adherence to the style guide. ```markdown [![wemake-python-styleguide](https://img.shields.io/badge/style-wemake-000000.svg)](https://github.com/wemake-services/wemake-python-styleguide) ``` -------------------------------- ### Install ondivi using pip Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_sources/pages/usage/integrations/ondivi Installs the 'ondivi' Python package using pip. It's recommended to use 'poetry' for package management. ```bash pip install ondivi ``` -------------------------------- ### Add Flakehell Base Config (Python) Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/changelog/index Includes a base configuration file for `flakehell`. This simplifies the setup and usage of `flakehell` for managing multiple linters. ```Python * Adds `flakehell` base config ``` -------------------------------- ### Ignoring Violations in setup.cfg - INI Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_sources/pages/usage/configuration This example demonstrates how to ignore specific violations in the setup.cfg file for flake8. It shows how to use the `per-file-ignores` option to disable checks for a particular file pattern. ```INI [flake8] per-file-ignores = # There are multiple `assert`s in tests, we allow them: tests/*.py: S101 ``` -------------------------------- ### Ruff Linter Configuration Example Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/violations/naming This snippet demonstrates how a rule is defined within the Wemake Python Styleguide, using 'ruff' linter. It specifies an error code and a descriptive template for reporting builtin shadowing. ```python error_template = 'Found builtin shadowing: {0}' code = 125 disabled_since = '1.0.0' ``` -------------------------------- ### Specify Custom Path for Style Guide Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/integrations/github-actions Illustrates how to set a custom path for the wemake-python-styleguide action. This allows the action to look for configuration files in a specific directory. ```yaml - name: wemake-python-styleguide uses: wemake-services/wemake-python-styleguide with: path: './your/custom/path' ``` -------------------------------- ### IncorrectExceptOrderViolation Example Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/violations/best_practices Illustrates the correct and incorrect order of exception handling in Python's try-except blocks. ```python # Correct: try: ... except ValueError: ... except Exception: ... # Wrong: try: ... except Exception: ... except ValueError: ... ``` -------------------------------- ### Configure wemake-python-styleguide via setup.cfg Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/configuration Shows how to configure wemake-python-styleguide settings within the setup.cfg file, which is the recommended approach for persistent project-wide configurations. ```ini [flake8] max-returns = 2 max-arguments = 4 ``` -------------------------------- ### Pass Action Output to Another Step Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/integrations/github-actions Example of how to capture the output of the wemake-python-styleguide action and use it in a subsequent step within a GitHub workflow. It echoes the output using `steps..outputs.`. ```yaml - name: wemake-python-styleguide uses: wemake-services/wemake-python-styleguide - name: Custom Action runs: echo "{{ steps.wemake-python-styleguide.outputs.output }}" ``` -------------------------------- ### Forbid starting lines with a dot (Python) Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/violations/consistency Enforces consistent line breaking by disallowing lines that begin with a dot, often related to method chaining. Uses parentheses for complex expressions. ```python # Correct: some = MyModel.objects.filter( # ... ).exclude( # ... ).annotate( # ... ) # Wrong: some = ( MyModel.objects.filter(...) .exclude(...) .annotate(...) ) ``` -------------------------------- ### Activate Virtual Environment with Poetry Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/api/contributing Activates the virtual environment managed by poetry for the current project. ```bash poetry env activate ``` -------------------------------- ### Python: Forbid unnecessary operators Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/violations/consistency Aims to eliminate the use of unnecessary operators in numeric literals and boolean expressions for consistency. Examples include leading plus signs (`+5.4`), double negations (`--5.4`), or double `not` (`not not foo`). ```python profit = 3.33 profit = -3.33 inverse = ~5 complement = not foo ``` -------------------------------- ### Enable Interactive Debugging with ipdb Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_sources/pages/api/debugging Set up and start an interactive debugging session using `ipdb`. This involves setting an environment variable and placing `breakpoint()` calls in the code to pause execution. ```bash export PYTHONBREAKPOINT=ipdb.set_trace ``` ```python breakpoint() ``` -------------------------------- ### Forbid reversed order complex comparison expressions in Python Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/violations/consistency This rule flags complex comparison expressions where the order of comparators starts from the largest element. It recommends reversing the order to ensure the smallest element comes first, improving readability. ```python # Correct: if three < two < one: ... # Wrong: if one > two > three: ... ``` -------------------------------- ### Forbid vague imports (Python) Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/violations/consistency This rule flags imports that may cause confusion, including common names like `dumps`, names starting with `to_` or `from_`, and overly short names (except `_`). It suggests using package-level imports or aliases for clarity. It is enforced by checking against `VAGUE_IMPORTS_BLACKLIST`. ```Python # Correct: import json import dumps # package names are not checked from json import loads as json_loads ``` -------------------------------- ### Run flake8 with wemake-python-styleguide Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/setup Demonstrates how to run the flake8 linter with the wemake-python-styleguide plugin enabled. It shows commands for running on the current directory, a single file, and a package. ```bash flake8 . flake8 your_module.py flake8 your_package ``` -------------------------------- ### Run flake8 with wemake-python-styleguide Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_sources/pages/usage/setup These commands demonstrate how to run the flake8 linter with the wemake-python-styleguide plugin. It covers running on the current directory, a single file, or a package. ```bash flake8 . ``` ```bash flake8 your_module.py ``` ```bash flake8 your_package ``` -------------------------------- ### after_init Method - Python Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/api/formatter The after_init method is called after the original init method is used to set extra fields within the WemakeFormatter. It returns None and is used for post-initialization setup. ```python def after_init(): """Called after the original `init` is used to set extra fields.""" pass ``` -------------------------------- ### Enable showing source code in setup.cfg Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/formatter Demonstrates configuring the '--show-source' option within the setup.cfg file to always display the problematic source code lines in flake8 reports. ```ini [flake8] show-source = True ``` -------------------------------- ### Run wemake-python-styleguide Docker Container Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/integrations/docker This snippet demonstrates running the wemake-python-styleguide Docker container. It includes options for specifying the source code directory. ```bash docker run --rm wemakeservices/wemake-python-styleguide . docker run --rm wemakeservices/wemake-python-styleguide -v `pwd`:/code /code ``` -------------------------------- ### Documentation: Add docs about `black` Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/changelog/index Includes documentation related to the `black` code formatter. This likely explains how `black` integrates with the project or provides guidance on its usage. ```documentation Adds docs about `black` ``` -------------------------------- ### ModuloStringFormatViolation Example (Python) Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/violations/consistency Highlights the preferred use of the `.format()` string method over the older C-style `%` formatting. This rule enforces a modern and consistent string formatting approach in Python projects. ```python class ASTViolation: error_template = '' code = 0 disabled_since = '' @final class ModuloStringFormatViolation(ASTViolation): error_template = 'Found `%` string formatting' code = 323 disabled_since = '1.0.0' # Correct: 'some string', 'your name: {0}', 'data: {data}' # Wrong: 'my name is: %s', 'data: %(data)d' ``` -------------------------------- ### Release New Version Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/api/contributing Steps to release a new version of the project, including updating the changelog, bumping versions in configuration files, committing changes, tagging the release, and publishing to PyPI using poetry. ```shell git commit -a -m 'Version x.y.z release' && git tag -a x.y.x -m 'Version x.y.z' && git push && git push --tags ``` ```shell poetry publish --build ``` -------------------------------- ### GitHub Action with 'github-pr-review' reporter and GITHUB_TOKEN Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_sources/pages/usage/integrations/github-actions This example demonstrates configuring the wemake-python-styleguide Action to use the 'github-pr-review' reporter for inline comments in pull requests. It requires the GITHUB_TOKEN environment variable to be set. ```yaml - name: wemake-python-styleguide uses: wemake-services/wemake-python-styleguide with: reporter: 'github-pr-review' env: GITHUB_TOKEN: ${{ secrets.github_token }} ``` -------------------------------- ### Forbid Starting Lines with Dot (Python) Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/changelog/index Prohibits lines from starting with a period (`.`). This is often a syntax error or indicates a stylistic issue that can be improved. ```Python * Forbids to start lines with `.` ``` -------------------------------- ### Create a flake8 Plugin for Out-of-Scope Functionality Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_sources/pages/api/tutorial For rules that are specific to a particular technology or case (e.g., pytest, Django, Scrapy) and not general Python, create a separate flake8 plugin. Users can then install these plugins individually based on their needs. ```text flake8-pytest-style flake8-django flake8-scrapy ``` -------------------------------- ### Display all Flake8 supported options Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/configuration A command to display all available configuration options supported by flake8, including those provided by plugins like wemake-python-styleguide. This helps in discovering and understanding the full range of configurable settings. ```bash flake8 --help ``` -------------------------------- ### Run wemake-python-styleguide with flake8 Source: https://wemake-python-styleguide.readthedocs.io/en/latest/index Executes the flake8 linter with the wemake-python-styleguide plugin enabled. The --select=WPS flag ensures that only rules from this plugin are applied. ```bash flake8 your_module.py --select=WPS ``` -------------------------------- ### Zero Division Violation Example Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/violations/consistency This example shows how to avoid explicit division or modulo by zero in Python. It suggests using `ZeroDivisionError` or ensuring the divisor is not zero to prevent runtime errors. ```python # Correct: raise ZeroDivisionError() # Wrong: 1 / 0 1 % 0 ``` -------------------------------- ### Configure wemake formatter in setup.cfg Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/formatter Shows how to configure the 'wemake' formatter by setting the 'format' option within the setup.cfg file. This provides a persistent way to use the custom formatter. ```ini [flake8] format = wemake ``` -------------------------------- ### Run All Tests Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/api/contributing Executes all defined tests for the project using pytest. This is a crucial step for quality control. ```bash pytest ``` -------------------------------- ### Operation Sign Negation Violation Example Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/violations/consistency This example demonstrates how to avoid double negation or mixed sign operations in Python. It shows the correct way to handle positive and negative numbers to maintain clarity. ```python # Correct: number = 3 + 1 number += 6 number -= 2 # Wrong: number = 3 - -1 number -= -6 number += -2 ``` -------------------------------- ### Pull Docker Image Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_sources/pages/usage/integrations/docker Pulls the official wemake-python-styleguide Docker image from DockerHub. This is the first step before running the container. ```bash docker pull wemakeservices/wemake-python-styleguide ``` -------------------------------- ### Meaningless Number Operation Violation Example Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/violations/consistency This snippet provides examples of meaningless arithmetic operations with 0 and 1 in Python that can be removed. It highlights redundant operations like adding zero or multiplying by one. ```python # Correct: number = 1 zero = 0 one = 1 three = 3 # Wrong: number = 1 + 0 * 1 zero = some * 0 / 1 one = some ** 0 ** 1 three = 3 ^ 0 three = 3 | 0 three = 3 % 1 ``` -------------------------------- ### Python: Forbid starting lines with a dot Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/violations/consistency This rule, now historical, aimed to prevent lines starting with a dot, which indicated a violation of line-breaking rules in complex expressions. The solution was to use parentheses for line breaks. ```python # Correct: some = MyModel.objects.filter( # ..., ).exclude( # ..., ).annotate( # ..., ) # Wrong: some = ( MyModel.objects.filter(...) .exclude(...) .annotate(...) ) ``` -------------------------------- ### Run wemake-python-styleguide with ruff Source: https://wemake-python-styleguide.readthedocs.io/en/latest/index Demonstrates how to use wemake-python-styleguide in conjunction with ruff for both checking and formatting code. It shows the ruff check and ruff format commands, followed by the flake8 command to ensure compatibility. ```bash ruff check && ruff format flake8 . --select=WPS ``` -------------------------------- ### Enable statistics in setup.cfg Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/formatter Shows the configuration for enabling the '--statistics' option in setup.cfg, allowing for aggregated violation counts and locations to be displayed in flake8 reports. ```ini [flake8] statistics = True ``` -------------------------------- ### Implicit Raw String Violation Example Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/violations/consistency This example illustrates the use of raw strings in Python to handle escape sequences more readably. It shows how to correctly use raw strings versus regular strings with double backslashes. ```python # Correct: escaped = [r'\n', '\n'] # Wrong: escaped = '\\n' ``` -------------------------------- ### GitHub Action with Custom Current Working Directory (cwd) Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_sources/pages/usage/integrations/github-actions This example illustrates setting a custom current working directory (cwd) for the wemake-python-styleguide Action. This allows the action to change its working directory before executing, which can be useful for projects with specific subfolder configurations. ```yaml - name: wemake-python-styleguide uses: wemake-services/wemake-python-styleguide with: cwd: './your/custom/path' ``` -------------------------------- ### Reassigning Variable to Itself Violation Example (Python) Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/violations/best_practices Provides examples of correct and incorrect variable assignments in Python. The rule flags self-assignments like `x = x` as unnecessary and potentially indicative of errors or dead code. ```Python # Correct: some = some + 1 x_coord, y_coord = y_coord, x_coord flag = not flag # Wrong: some = some x_coord, y_coord = x_coord, y_coord ``` -------------------------------- ### Run All Checks with Make Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/api/contributing Execute all pre-submission checks, including tests, type checking, and linting, by running the 'make test' command. This command orchestrates multiple tools to ensure code quality and style. ```shell make test ``` -------------------------------- ### Enable showing source code with wemake formatter Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/formatter Explains how to enable the '--show-source' option, either via the command line or in setup.cfg, to display the exact line of code where a violation occurs. This aids in faster debugging. ```bash flake8 . --format=wemake --show-source ``` -------------------------------- ### Fix OverusedExpressionViolation and TooManyExpressionsViolation Docs (Python) Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/changelog/index Corrects documentation for `OverusedExpressionViolation` and `TooManyExpressionsViolation`. This ensures accurate explanations and examples for these rules. ```Python * Fixes `OverusedExpressionViolation` and `TooManyExpressionsViolation` docs ``` -------------------------------- ### FloatKeyViolation Example Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/violations/best_practices Shows the correct and incorrect usage of float types as dictionary keys in Python. ```python # Correct: some = {1: 'a'} some[1] # Wrong: some = {1.0: 'a'} some[1.0] ``` -------------------------------- ### Configure wemake-python-styleguide via Flake8 CLI Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/configuration Demonstrates how to set configuration options for wemake-python-styleguide directly through the flake8 command-line interface. This is useful for temporary overrides or quick adjustments. ```bash flake8 --max-returns=2 --max-arguments=4 ``` -------------------------------- ### Pre-commit Configuration for Wemake-Python-Styleguide Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_sources/pages/usage/integrations/plugins This YAML configuration is for the .pre-commit-config.yaml file. It sets up a local hook to run flake8 with a specific configuration file (setup.cfg), enforcing the wemake-python-styleguide. ```yaml repos: - repo: local hooks: - id: flake8 name: flake8 description: wemake-python-styleguide enforcement entry: flake8 args: ["--config=setup.cfg"] language: python types: [python] ``` -------------------------------- ### PositionalOnlyArgumentsViolation Example Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/violations/best_practices Demonstrates the correct and incorrect usage of positional-only arguments (using '/') in Python function definitions. ```python # Correct: def my_function(first, second): ... # Wrong: def my_function(first, /, second): ... ``` -------------------------------- ### Run Type Checks with MyPy Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/api/contributing Executes static type checking on the wemake_python_styleguide codebase using mypy. ```bash mypy wemake_python_styleguide ``` -------------------------------- ### StringConstantRedefinedViolation Example Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/violations/best_practices Demonstrates the correct and incorrect usage of string constants, specifically forbidding the redefinition of alphabet strings. ```python import string UPPERCASE_ALPH = string.ascii_uppercase LOWERCASE_ALPH = string.ascii_lowercase # Wrong: GUESS_MY_NAME = "abcde...WXYZ" UPPERCASE_ALPH = "ABCD...WXYZ" LOWERCASE_ALPH = "abcd...wxyz" ``` -------------------------------- ### Running WPS and Ruff linters together Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/changelog/index Provides the command-line instructions to simultaneously run Ruff's formatter and checker, followed by flake8 with WPS specific rules. This ensures comprehensive code linting and formatting. ```bash ruff format && ruff check && flake8 --select=WPS . ``` -------------------------------- ### Activate Wemake Formatter with Flake8 Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_sources/pages/usage/formatter Demonstrates how to activate the 'wemake' formatter for flake8. This can be done via the command line or by configuring the 'setup.cfg' file. ```bash flake8 --format=wemake your_module.py ``` ```ini [flake8] format = wemake ``` -------------------------------- ### Checker Initialization Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/checker Details the initialization of the Checker class with AST tree, file tokens, and filename. ```APIDOC ## POST /api/checker/initialize ### Description Initializes a new instance of the Checker class. This method is called by flake8 and expects specific parameters. ### Method POST ### Endpoint /api/checker/initialize ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **tree** (ast.AST) - Required - The Abstract Syntax Tree parsed by flake8. - **file_tokens** (Sequence[tokenize.TokenInfo]) - Required - A sequence of token information parsed from the file. - **filename** (str) - Optional - The name of the file being processed. Defaults to `constants.STDIN` if not provided. ### Request Example ```json { "tree": { ... ast.AST object ... }, "file_tokens": [ ... list of tokenize.TokenInfo ... ], "filename": "example.py" } ``` ### Response #### Success Response (200) - **message** (str) - Indicates successful initialization. #### Response Example ```json { "message": "Checker initialized successfully." } ``` ``` -------------------------------- ### Fix Invalid Docs for BracketBlankLineViolation (Python) Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/changelog/index Corrects inaccurate documentation for the BracketBlankLineViolation rule. This provides users with correct examples and explanations for this specific linting rule. ```Python * Fixes invalid docs for `BracketBlankLineViolation` #1020 ``` -------------------------------- ### WPS401: Forbid empty doc comments (``#:``) Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/violations/best_practices This rule forbids the use of empty doc comments, specifically those starting with ``#:``. It is part of the wemake-python-styleguide. ```python NAMES_WHITELIST = ['feature', 'bug', 'research'] full_code_: ClassVar[str]__ = 'WPS401' summary_: ClassVar[str]__ = 'Forbid empty doc comments (``#:``).' ``` -------------------------------- ### Fix Docs About Implicit Yield Violation (Python) Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/changelog/index Corrects documentation pertaining to implicit `yield` violations. This provides clearer explanations and examples for this specific linting rule. ```Python * Fixes docs about implicit `yield` violation ``` -------------------------------- ### Forbid Redundant Subscripts (Python) Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/changelog/index Prohibits the use of redundant subscripting, such as `[0:7]` or `[3:None]`, when simpler alternatives exist. For example, `a[len(a) - 1]` should be replaced with `a[-1]`. ```Python * Forbids to use redundant subscripts (e.g., `[0:7]` or `[3:None]`) ``` -------------------------------- ### Run Docker Container with Volume Mount Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_sources/pages/usage/integrations/docker Runs the wemake-python-styleguide Docker container and mounts the current directory as a volume named '/code'. This allows the container to access and process the source code. ```bash docker run --rm wemakeservices/wemake-python-styleguide -v `pwd`:/code /code ``` -------------------------------- ### Build: Add `Makefile` Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/changelog/index Includes a `Makefile` in the project. This file defines common build and development tasks, automating processes like testing, linting, and building. ```build Adds `Makefile` ``` -------------------------------- ### Python: Example of Deep Attribute Access Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/violations/complexity Demonstrates a deeply nested attribute access chain which is considered a violation due to its complexity. The code accesses nested methods and attributes sequentially. ```python manager.filter().exclude().annotate().values().first() # Wrong: access level = 5 self.attr.inner.wrapper.method.call() # Wrong: access level = 5 # `obj` has access level of 2: # `.attr`, `.call` # `call()` has access level of 5: # `.other`, `[0]`, `.field`, `.type`, `.boom` obj.attr.call().other[0].field.type.boom ``` -------------------------------- ### Show Links to Documentation for Violations Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_sources/pages/usage/formatter Demonstrates how to enable '--show-violation-links' to display links to documentation pages for specific violations, allowing users to click and open the respective docs. ```bash flake8 . --format=wemake --show-source --show-violation-links ``` -------------------------------- ### Too Deep Access Violation Example (Python) Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/violations/complexity Illustrates acceptable and potentially problematic nested attribute and subscript access. The TooDeepAccessViolation rule discourages excessively deep data access chains. ```python # Correct: access level = 4 self.attr.inner.wrapper[1] # Correct: access level = 1 ``` -------------------------------- ### Forbid useless blank lines before and after brackets (Python) Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/violations/consistency Enforces consistency by disallowing blank lines immediately before or after brackets within collections. ```python # Correct: arr = [ 1, 2, ] ``` -------------------------------- ### Enforce Architecture with Import Linter Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/api/contributing Checks the project's import structure against defined architectural contracts using import-linter. ```bash lint-imports ``` -------------------------------- ### Whitelist of Common Magic Numbers Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/api/constants A set of commonly used numeric literals that are exempt from being flagged as 'magic numbers' by the style guide. This includes essential constants for various operations. ```python MAGIC_NUMBERS_WHITELIST_: Final_ _ = frozenset({0, 0.1, 0.5, 1.0, 100, 1000, 1024, 1j, 24, 60}) ``` -------------------------------- ### Python BaseVisitor Class Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/api/visitors Defines the abstract base class for visitors, handling options, filenames, and violations. Includes methods for adding violations and running the visitor. ```Python class _BaseVisitor(_options_ , _filename ='stdin'_){ Bases: `ABC` Abstract base class for different types of visitors. options¶ contains the options objects passed and parsed by `flake8`. filename¶ filename passed by `flake8`, each visitor has a file name. violations¶ list of violations for the specific visitor. _classmethod _from_checker(_checker_)[source]¶ Constructs visitor instance from the checker. Each unique visitor class should know how to construct itself from the checker instance. Generally speaking, each visitor class needs to eject required parameters from checker and then run its constructor with these parameters. Return type: `BaseVisitor` _final _add_violation(_violation_)[source]¶ Adds violation to the visitor. Return type: `None` _abstract _run()[source]¶ Runs a visitor. Each visitor should know what exactly it needs to do when it was told to `run`. Return type: `None` ``` -------------------------------- ### Blacklist of Magic Methods for Generators Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/api/constants Defines a set of magic methods that are not permitted to be implemented as generators. This helps enforce specific patterns for method behavior within the style guide. ```python YIELD_MAGIC_METHODS_BLACKLIST_: Final_ _ = frozenset({ '__abs__', '__add__', '__aenter__', '__aexit__', '__and__', '__anext__', '__annotate__', '__attrs_init__', '__attrs_post_init__', '__attrs_pre_init__', '__await__', '__bool__', '__bytes__', '__ceil__', '__class_getitem__', '__cmp__', '__coerce__', '__complex__', '__contains__', '__copy__', '__deepcopy__', '__del__', '__delattr__', '__delete__', '__delitem__', '__dir__', '__divmod__', '__enter__', '__eq__', '__exit__', '__float__', '__floor__', '__floordiv__', '__format__', '__fspath__', '__ge__', '__get__', '__getattr__', '__getattribute__', '__getinitargs__', '__getitem__', '__getnewargs__', '__getnewargs_ex__', '__getstate__', '__gt__', '__hash__', '__hex__', '__iadd__', '__iand__', '__ifloordiv__', '__ilshift__', '__imatmul__', '__imod__', '__imul__', '__index__', '__init__', '__init_subclass__', '__instancecheck__', '__int__', '__invert__', '__ior__', '__ipow__', '__irshift__', '__isub__', '__itruediv__', '__ixor__', '__le__', '__len__', '__length_hint__', '__long__', '__lshift__', '__lt__', '__matmul__', '__missing__', '__mod__', '__mro_entries__', '__mul__', '__ne__', '__neg__', '__new__', '__next__', '__nonzero__', '__oct__', '__or__', '__pos__', '__post_init__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__replace__', '__repr__', '__reversed__', '__rfloordiv__', '__rlshift__', '__rmatmul__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__set__', '__set_name__', '__setattr__', '__setitem__', '__setstate__', '__signature__', '__sizeof__', '__str__', '__sub__', '__subclasscheck__', '__truediv__', '__trunc__', '__unicode__', '__xor__', }) ``` -------------------------------- ### Checker Execution: run Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/checker Details the execution of the Checker, which runs registered visitors and yields violations. ```APIDOC ## GET /api/checker/run ### Description This method is the core execution method called by flake8. It iterates through all registered visitors, runs them against the checker's context, and yields any violations found. ### Method GET ### Endpoint /api/checker/run ### Parameters None ### Request Example ```json {} // No request body needed for GET request ``` ### Response #### Success Response (200) - **Iterator[CheckResult]** - An iterator yielding violation tuples. Each tuple typically contains: - `line_number` (int) - `column_number` (int) - `message` (str) - `type` (class) #### Response Example ```json [ [10, 4, "WPS001: Found violation message", ], [25, 1, "WPS100: Another violation", ] ] ``` ``` -------------------------------- ### format Method - Python Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/api/formatter The format method is called to format each individual violation detected by the style guide. It returns a string representing the formatted error message. ```python def format(_error_): """Called to format each individual violation.""" return str ``` -------------------------------- ### Too Many Base Classes Violation Example (Python) Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/violations/complexity Demonstrates the correct and incorrect usage of base classes according to the TooManyBaseClassesViolation rule. The rule aims to prevent overly complex inheritance hierarchies. ```python class SomeClassName(First, Second, Mixin): ... class SomeClassName( FirstParentClass, SecondParentClass, ThirdParentClass, CustomClass, AddedClass, ): ... ``` -------------------------------- ### Activate wemake formatter via command line Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/formatter Demonstrates how to activate the custom 'wemake' formatter for flake8 using a command-line argument. This changes how flake8 reports violations. ```bash flake8 --format=wemake your_module.py ``` -------------------------------- ### Python Self Comparison Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/violations/consistency Shows examples of comparing a variable to itself, which is considered a mistake. The correct approach is to remove such comparisons, as they always result in a predictable boolean value. ```python # Correct: do_something() # Wrong: if a < a: do_something() else: do_something_else() ``` -------------------------------- ### Implicit Elif Condition Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/violations/refactoring Provides an example of an 'implicit elif' condition, where a nested if statement within an else block can be refactored for better readability. The correct pattern uses an 'elif' at the same indentation level. ```python if some: ... else: if other: ... ``` -------------------------------- ### Python: Forbid '%' formatting on strings (WPS323) Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/violations/consistency This rule prohibits the use of the '%' operator for string formatting, encouraging the use of the `.format()` method for consistency. ```python # Correct: 'some string', 'your name: {0}', 'data: {data}' # Wrong: 'my name is: %s', 'data: %(data)d' ``` -------------------------------- ### GitHub Action with Custom Path Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_sources/pages/usage/integrations/github-actions This configuration snippet shows how to specify a custom path for the wemake-python-styleguide Action to operate on. This is useful if your project structure or configuration files are not in the root directory. ```yaml - name: wemake-python-styleguide uses: wemake-services/wemake-python-styleguide with: path: './your/custom/path' ``` -------------------------------- ### Run Ruff Checks and Formatting Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/integrations/auto-formatters This command demonstrates how to run both checking and formatting tasks using the ruff tool. It's compatible with wemake-python-styleguide, ensuring no conflicts. ```shell ruff check && ruff format ``` -------------------------------- ### Incorrectly Nested Ternary Expression Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_modules/wemake_python_styleguide/violations/refactoring Illustrates an incorrect use of nested ternary expressions, which can lead to debugging and testing difficulties. The example shows a nested ternary within an if statement, highlighting the problematic pattern. ```python if x if cond() else y: ... ``` -------------------------------- ### Test-Driven Development Workflow with pytest and ast.dump Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/api/debugging Explains a test-driven development approach for designing and debugging code. It involves writing failing tests, running them with `pytest`, inspecting abstract syntax trees with `ast.dump`, and iterating until the code functions correctly. ```bash pytest tests/full/path/to/your/test_module.py ``` ```python print(ast.dump(node)) ``` -------------------------------- ### Forbid blacklisted module names (WPS100) Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/violations/naming This rule forbids the use of blacklisted module names to encourage more expressive naming. Examples of correct and incorrect module names are provided. ```python # Correct: github.py views.py # Wrong: utils.py helpers.py ``` -------------------------------- ### Configure pre-commit for wemake-python-styleguide Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/usage/integrations/plugins A sample configuration for `.pre-commit-config.yaml` to enforce wemake-python-styleguide using the `flake8` entry. It specifies the `flake8` command with a configuration file and identifies the language as Python. ```yaml repos: - repo: local hooks: - id: flake8 name: flake8 description: wemake-python-styleguide enforcement entry: flake8 args: ["--config=setup.cfg"] language: python types: [python] ``` -------------------------------- ### Configuration: Add `--show-source` to default config Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/changelog/index Updates the default configuration to include the `--show-source` flag. This flag likely provides more detailed output or source code context when running the linter. ```configuration Adds `--show-source` to the default recommended configuration ``` -------------------------------- ### Python: Forbidding Collection Element by Unpacking Source: https://wemake-python-styleguide.readthedocs.io/en/latest/pages/changelog/index This snippet addresses a rule that forbids getting collection elements by unpacking, as mentioned in issue #1824. This aims to prevent potential errors or confusion. ```Python # Example that might be flagged by the rule against unpacking collection elements my_tuple = (1, 2, 3) first, second, third = my_tuple # Alternative: first = my_tuple[0] ``` -------------------------------- ### Python Visitor Pattern for Code Analysis Source: https://wemake-python-styleguide.readthedocs.io/en/latest/_sources/pages/api/tutorial Demonstrates a Python visitor pattern implementation for analyzing abstract syntax tree (AST) nodes, specifically checking for multiple 'if' conditions within comprehensions. It utilizes the `ast` module and a custom `BaseNodeVisitor` class. ```python 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) ```