codewatch-scan 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codewatch/__init__.py +0 -0
- codewatch/__main__.py +14 -0
- codewatch/asgi.py +16 -0
- codewatch/settings.py +175 -0
- codewatch/urls.py +40 -0
- codewatch/wsgi.py +16 -0
- codewatch_scan-0.1.0.dist-info/METADATA +81 -0
- codewatch_scan-0.1.0.dist-info/RECORD +136 -0
- codewatch_scan-0.1.0.dist-info/WHEEL +5 -0
- codewatch_scan-0.1.0.dist-info/entry_points.txt +4 -0
- codewatch_scan-0.1.0.dist-info/licenses/LICENSE +21 -0
- codewatch_scan-0.1.0.dist-info/top_level.txt +2 -0
- core/__init__.py +0 -0
- core/analyzers/__init__.py +19 -0
- core/analyzers/accessibility.py +199 -0
- core/analyzers/base.py +192 -0
- core/analyzers/body_models.py +154 -0
- core/analyzers/codewatch_checks.py +394 -0
- core/analyzers/constant_branches.py +251 -0
- core/analyzers/containers.py +316 -0
- core/analyzers/coverage.py +131 -0
- core/analyzers/dependencies.py +347 -0
- core/analyzers/drf_serializers.py +65 -0
- core/analyzers/else_branches.py +106 -0
- core/analyzers/extra.py +400 -0
- core/analyzers/flask_resources.py +65 -0
- core/analyzers/inline_scripts.py +50 -0
- core/analyzers/jinja_sandboxes.py +63 -0
- core/analyzers/match_statements.py +148 -0
- core/analyzers/multi_tools.py +888 -0
- core/analyzers/php_template_sinks.py +444 -0
- core/analyzers/project_checks.py +150 -0
- core/analyzers/python_tools.py +333 -0
- core/analyzers/route_converters.py +237 -0
- core/analyzers/slices.py +94 -0
- core/analyzers/starred_targets.py +42 -0
- core/analyzers/stored_fields.py +386 -0
- core/analyzers/summaries.py +1387 -0
- core/analyzers/template_sinks.py +162 -0
- core/api.py +360 -0
- core/apps.py +6 -0
- core/benchmark.py +955 -0
- core/bundled/catalog/codewatch/rules/javascript-crypto.yml +224 -0
- core/bundled/catalog/codewatch/rules/javascript-injection.yml +116 -0
- core/bundled/catalog/codewatch/rules/javascript-taint.yml +1539 -0
- core/bundled/catalog/codewatch/rules/javascript-web.yml +562 -0
- core/bundled/catalog/codewatch/rules/php-web.yml +719 -0
- core/bundled/catalog/codewatch/rules/python-crypto.yml +203 -0
- core/bundled/catalog/codewatch/rules/python-django.yml +267 -0
- core/bundled/catalog/codewatch/rules/python-injection.yml +115 -0
- core/bundled/catalog/codewatch/rules/python-web.yml +3382 -0
- core/bundled/catalog/custom/mappings.json +360 -0
- core/bundled/catalog/custom/overrides.json +4 -0
- core/bundled/catalog/custom/rules/django-settings.yml +19 -0
- core/bundled/catalog/imported/changes.json +5 -0
- core/bundled/catalog/imported/docs.json +1143 -0
- core/bundled/catalog/imported/meta.json +54 -0
- core/bundled/catalog/imported/rules.json +85421 -0
- core/bundled/catalog/imported/standards.json +11191 -0
- core/bundled/tools/analyzers.lock +786 -0
- core/bundled/tools/axe-scan.mjs +45 -0
- core/bundled/tools/checkov.lock +2463 -0
- core/bundled/tools/codewatch-checks.mjs +99 -0
- core/bundled/tools/eslint-a11y.config.js +16 -0
- core/bundled/tools/eslint-quality.config.js +63 -0
- core/bundled/tools/eslint-typed.config.js +18 -0
- core/bundled/tools/package-lock.json +6102 -0
- core/bundled/tools/package.json +32 -0
- core/bundled/tools/rule-metadata.mjs +56 -0
- core/bundled/tools/semgrep.lock +1232 -0
- core/bundled/tools/stylelint.config.json +11 -0
- core/catalog/__init__.py +190 -0
- core/catalog/build.py +84 -0
- core/catalog/merge.py +122 -0
- core/catalog/sources.py +418 -0
- core/catalog/standards.py +119 -0
- core/catalog/update.py +99 -0
- core/catalog_views.py +115 -0
- core/client.py +645 -0
- core/collect.py +518 -0
- core/duplicates.py +60 -0
- core/fingerprint.py +25 -0
- core/folders.py +73 -0
- core/gate.py +77 -0
- core/git.py +149 -0
- core/jobs.py +86 -0
- core/management/__init__.py +0 -0
- core/management/commands/__init__.py +0 -0
- core/management/commands/addproject.py +40 -0
- core/management/commands/buildcatalog.py +15 -0
- core/management/commands/scan.py +74 -0
- core/management/commands/updatecatalog.py +14 -0
- core/mcp_server.py +140 -0
- core/middleware.py +17 -0
- core/migrations/0001_initial.py +115 -0
- core/migrations/0002_auth_tokens_a11y.py +60 -0
- core/migrations/0003_default_admin.py +43 -0
- core/migrations/0004_project_members.py +28 -0
- core/migrations/0005_uploads_and_sources.py +55 -0
- core/migrations/0006_thresholds.py +28 -0
- core/migrations/0007_also_reported_by.py +18 -0
- core/migrations/0008_new_code_period.py +18 -0
- core/migrations/0009_resolution_safe.py +18 -0
- core/migrations/0010_analysis_progress.py +18 -0
- core/migrations/0011_overall_gate_conditions.py +20 -0
- core/migrations/__init__.py +0 -0
- core/models.py +323 -0
- core/network.py +41 -0
- core/paths.py +29 -0
- core/ratings.py +67 -0
- core/runner.py +168 -0
- core/templates/core/account.html +30 -0
- core/templates/core/analysis.html +49 -0
- core/templates/core/base.html +121 -0
- core/templates/core/form_table.html +12 -0
- core/templates/core/gate_badge.html +1 -0
- core/templates/core/index.html +26 -0
- core/templates/core/issues.html +38 -0
- core/templates/core/login.html +13 -0
- core/templates/core/new_project.html +27 -0
- core/templates/core/password_change.html +10 -0
- core/templates/core/project.html +40 -0
- core/templates/core/rating.html +1 -0
- core/templates/core/ratings.html +32 -0
- core/templates/core/rule.html +33 -0
- core/templates/core/rules.html +42 -0
- core/templates/core/scan_progress.html +2 -0
- core/templates/core/settings.html +36 -0
- core/templates/core/source.html +15 -0
- core/templates/core/standards.html +30 -0
- core/templates/core/user_edit.html +15 -0
- core/templates/core/users.html +18 -0
- core/templatetags/__init__.py +0 -0
- core/templatetags/codewatch.py +42 -0
- core/tool_setup.py +68 -0
- core/views.py +564 -0
|
@@ -0,0 +1,1143 @@
|
|
|
1
|
+
{
|
|
2
|
+
"ruff/AIR001": "## What it does\nChecks that the task variable name matches the `task_id` value for\nAirflow Operators.\n\n## Why is this bad?\nWhen initializing an Airflow Operator, for consistency, the variable\nname should match the `task_id` value. This makes it easier to\nfollow the flow of the Dag.\n\n## Example\n```python\nfrom airflow.operators import PythonOperator\n\n\nincorrect_name = PythonOperator(task_id=\"my_task\")\n```\n\nUse instead:\n```python\nfrom airflow.operators import PythonOperator\n\n\nmy_task = PythonOperator(task_id=\"my_task\")\n```\n",
|
|
3
|
+
"ruff/AIR002": "## What it does\nChecks for a `DAG()` class or `@dag()` decorator without an explicit\n`schedule` (or `schedule_interval` for Airflow 1) parameter.\n\n## Why is this bad?\nThe default value of the `schedule` parameter on Airflow 2 and\n`schedule_interval` on Airflow 1 is `timedelta(days=1)`, which is almost\nnever what a user is looking for. Airflow 3 changed the default value to `None`,\nand would break existing Dags using the implicit default.\n\nIf your Dag does not have an explicit `schedule` / `schedule_interval` argument,\nAirflow 2 schedules a run for it every day (at the time determined by `start_date`).\nSuch a Dag will no longer be scheduled on Airflow 3 at all, without any\nexceptions or other messages visible to the user.\n\n## Example\n```python\nfrom airflow import DAG\n\n\n# Using the implicit default schedule.\ndag = DAG(dag_id=\"my_dag\")\n```\n\nUse instead:\n```python\nfrom datetime import timedelta\n\nfrom airflow import DAG\n\n\ndag = DAG(dag_id=\"my_dag\", schedule=timedelta(days=1))\n```\n",
|
|
4
|
+
"ruff/AIR003": "## What it does\nChecks for `Variable.get()` calls outside of Airflow task execution\ncontext (i.e., outside `@task`-decorated functions and operator\n`execute()` methods).\n\n## Why is this bad?\nCalling `Variable.get()` at module level or in operator constructor\narguments causes a database query every time the Dag file is parsed\nby the scheduler. This can degrade Dag parsing performance and, in\nsome cases, cause the Dag file to time out before it is fully parsed.\n\nInstead, pass Airflow Variables to operators via Jinja templates\n(`{{ var.value.my_var }}` or `{{ var.json.my_var }}`), which defer\nthe lookup until task execution.\n\n`Variable.get()` inside `@task`-decorated functions and operator\n`execute()` methods is fine because those only run during task\nexecution, not during Dag parsing.\n\nNote that this rule may produce false positives for helper functions\nthat are only invoked at task execution time (e.g., passed as\n`python_callable` to `PythonOperator`). In such cases, suppress the\ndiagnostic with `# noqa: AIR003`.\n\n## Example\n```python\nfrom airflow.sdk import Variable\nfrom airflow.operators.bash import BashOperator\n\n\nfoo = Variable.get(\"foo\")\nBashOperator(task_id=\"bad\", bash_command=\"echo $FOO\", env={\"FOO\": foo})\n```\n\nUse instead:\n```python\nfrom airflow.operators.bash import BashOperator\n\n\nBashOperator(\n task_id=\"good\",\n bash_command=\"echo $FOO\",\n env={\"FOO\": \"{{ var.value.foo }}\"},\n)\n```\n",
|
|
5
|
+
"ruff/AIR004": "## What it does\nChecks for branching logic that could be replaced with a short-circuit\npattern, either via `@task.branch` decorated functions or\n`BranchPythonOperator` callables.\n\n## Why is this bad?\nWhen a branch function has at least two `return` statements and exactly\none of them returns a non-empty list, the function is effectively acting\nas a short-circuit operator. Using `@task.short_circuit` or\n`ShortCircuitOperator` is simpler and more readable in such cases.\n\n## Example\n\nUsing the `TaskFlow` API:\n```python\nfrom airflow.decorators import task\n\n\n@task.branch\ndef my_task():\n if condition:\n return [\"my_downstream_task\"]\n return []\n```\n\nUse instead:\n```python\nfrom airflow.decorators import task\n\n\n@task.short_circuit\ndef my_task():\n return condition\n```\n\nUsing the standard operator API:\n```python\nfrom airflow.operators.python import BranchPythonOperator\n\n\ndef my_callable():\n if condition:\n return [\"my_downstream_task\"]\n return []\n\n\ntask = BranchPythonOperator(task_id=\"my_task\", python_callable=my_callable)\n```\n\nUse instead:\n```python\nfrom airflow.operators.python import ShortCircuitOperator\n\n\ndef my_callable():\n return condition\n\n\ntask = ShortCircuitOperator(task_id=\"my_task\", python_callable=my_callable)\n```\n",
|
|
6
|
+
"ruff/AIR201": "## What it does\nChecks for Airflow operator keyword arguments that use a Jinja template\nstring containing a single `xcom_pull` call to retrieve another task's\noutput.\n\n## Why is this bad?\nUsing `{{ ti.xcom_pull(task_ids='some_task') }}` as a string template to\naccess the output of an upstream task is less readable and more\nerror-prone than using the `.output` attribute on the task object\ndirectly. The `.output` attribute provides better IDE support and makes\ntask dependencies more explicit.\n\n## Example\n```python\nfrom airflow.operators.python import PythonOperator\n\n\ntask_1 = PythonOperator(task_id=\"task_1\", python_callable=my_func)\ntask_2 = PythonOperator(\n task_id=\"task_2\",\n op_args=\"{{ ti.xcom_pull(task_ids='task_1') }}\",\n)\n```\n\nUse instead:\n```python\nfrom airflow.operators.python import PythonOperator\n\n\ntask_1 = PythonOperator(task_id=\"task_1\", python_callable=my_func)\ntask_2 = PythonOperator(\n task_id=\"task_2\",\n op_args=task_1.output,\n)\n```\n\n## Fix safety\nThe fix is always unsafe because the variable in scope that matches the\ntask ID may not be the Airflow task object that produced the `XCom` value.\n",
|
|
7
|
+
"ruff/AIR202": "## What it does\nChecks for `@task`-decorated functions whose `multiple_outputs` behavior is\ndetermined by Airflow's runtime inference rather than being set explicitly.\n\n## Why is this bad?\nAt runtime, Airflow infers `multiple_outputs` from the return type\nannotation: if it resolves to a subclass of `collections.abc.Mapping`, the\nreturn value is split into one `XCom` per key; otherwise it is stored as a\nsingle `XCom`. This couples typing to `XCom` layout in a non-obvious way \u2014\nrenaming, removing, or refining the return annotation silently changes the\nDag's `XCom` behavior.\n\nPassing `multiple_outputs=` explicitly makes the author's intent clear,\ninsulates the Dag from future changes to inference, and increases\nawareness of the parameter.\n\n## Example\n```python\nfrom airflow.sdk import task\n\n\n@task\ndef extract() -> dict:\n return {\"x\": 1, \"y\": 2}\n```\n\nUse instead:\n```python\nfrom airflow.sdk import task\n\n\n@task(multiple_outputs=True)\ndef extract() -> dict:\n return {\"x\": 1, \"y\": 2}\n```\n\n## Fix safety\nThe fix is always marked unsafe: the inserted value mirrors Airflow's\ncurrent inference (`True` when the return annotation is a `Mapping`\nsubclass, `False` otherwise), but the author may have intended a different\n`XCom` layout, and a function with multiple return paths may not always\nreturn a dict.\n",
|
|
8
|
+
"ruff/AIR301": "## What it does\nChecks for uses of deprecated Airflow functions and values.\n\n## Why is this bad?\nAirflow 3.0 removed various deprecated functions, members, and other\nvalues. Some have more modern replacements. Others are considered too niche\nand not worth continued maintenance in Airflow.\n\n## Example\n```python\nfrom airflow.utils.dates import days_ago\n\n\nyesterday = days_ago(today, 1)\n```\n\nUse instead:\n```python\nfrom datetime import timedelta\n\n\nyesterday = today - timedelta(days=1)\n```\n",
|
|
9
|
+
"ruff/AIR302": "## What it does\nChecks for uses of Airflow functions and values that have been moved to its providers\n(e.g., `apache-airflow-providers-fab`).\n\n## Why is this bad?\nAirflow 3.0 moved various deprecated functions, members, and other\nvalues to its providers. The user needs to install the corresponding provider and replace\nthe original usage with the one in the provider.\n\n## Example\n```python\nfrom airflow.auth.managers.fab.fab_auth_manager import FabAuthManager\n\nfab_auth_manager_app = FabAuthManager().get_fastapi_app()\n```\n\nUse instead:\n```python\nfrom airflow.providers.fab.auth_manager.fab_auth_manager import FabAuthManager\n\nfab_auth_manager_app = FabAuthManager().get_fastapi_app()\n```\n",
|
|
10
|
+
"ruff/AIR303": "## What it does\nChecks for Airflow function calls that will raise a runtime error in Airflow 3.0\ndue to function signature changes, such as functions that changed to accept only\nkeyword arguments, parameter reordering, or parameter type changes.\n\n## Why is this bad?\nAirflow 3.0 introduces changes to function signatures. Code that\nworked in Airflow 2.x will raise a runtime error if not updated in Airflow\n3.0.\n\n## Example\n```python\nfrom airflow.lineage.hook import HookLineageCollector\n\ncollector = HookLineageCollector()\n# Passing positional arguments will raise a runtime error in Airflow 3.0\ncollector.create_asset(\"s3://bucket/key\")\n```\n\nUse instead:\n```python\nfrom airflow.lineage.hook import HookLineageCollector\n\ncollector = HookLineageCollector()\n# Passing arguments as keyword arguments instead of positional arguments\ncollector.create_asset(uri=\"s3://bucket/key\")\n```\n",
|
|
11
|
+
"ruff/AIR304": "## What it does\nChecks for calls to runtime-varying functions (such as `datetime.now()`)\nused as arguments in Airflow Dag or task constructors.\n\n## Why is this bad?\nUsing runtime-varying values as arguments to Dag or task constructors\ncauses the serialized Dag hash to change on every parse, creating\ninfinite Dag versions in the `dag_version` and `serialized_dag` tables.\nThis leads to unbounded database growth and can eventually cause\nout-of-memory conditions.\n\n## Example\n```python\nfrom datetime import datetime\n\nfrom airflow import DAG\n\ndag = DAG(dag_id=\"my_dag\", start_date=datetime.now())\n```\n\nUse instead:\n```python\nfrom datetime import datetime\n\nfrom airflow import DAG\n\ndag = DAG(dag_id=\"my_dag\", start_date=datetime(2024, 1, 1))\n```\n",
|
|
12
|
+
"ruff/AIR311": "## What it does\nChecks for uses of deprecated Airflow functions and values that still have\na compatibility layer.\n\n## Why is this bad?\nAirflow 3.0 removed various deprecated functions, members, and other\nvalues. Some have more modern replacements. Others are considered too niche\nand not worth continued maintenance in Airflow.\nEven though these symbols still work fine on Airflow 3.0, they are expected to be removed in a future version.\nWhere available, users should replace the removed functionality with the new alternatives.\n\n## Example\n```python\nfrom airflow import Dataset\n\n\nDataset(uri=\"test://test/\")\n```\n\nUse instead:\n```python\nfrom airflow.sdk import Asset\n\n\nAsset(uri=\"test://test/\")\n```\n",
|
|
13
|
+
"ruff/AIR312": "## What it does\nChecks for uses of Airflow functions and values that have been moved to its providers\nbut still have a compatibility layer (e.g., `apache-airflow-providers-standard`).\n\n## Why is this bad?\nAirflow 3.0 moved various deprecated functions, members, and other\nvalues to its providers. Even though these symbols still work fine on Airflow 3.0,\nthey are expected to be removed in a future version. The user is suggested to install\nthe corresponding provider and replace the original usage with the one in the provider.\n\n## Example\n```python\nfrom airflow.operators.python import PythonOperator\n\n\ndef print_context(ds=None, **kwargs):\n print(kwargs)\n print(ds)\n\n\nprint_the_context = PythonOperator(\n task_id=\"print_the_context\", python_callable=print_context\n)\n```\n\nUse instead:\n```python\nfrom airflow.providers.standard.operators.python import PythonOperator\n\n\ndef print_context(ds=None, **kwargs):\n print(kwargs)\n print(ds)\n\n\nprint_the_context = PythonOperator(\n task_id=\"print_the_context\", python_callable=print_context\n)\n```\n",
|
|
14
|
+
"ruff/AIR321": "## What it does\nChecks for uses of deprecated or moved Airflow functions and values in Airflow 3.1.\n\n## Why is this bad?\nAirflow 3.1 deprecated or moved various functions, members, and other values.\n\n## Example\n```python\nfrom airflow.utils.timezone import convert_to_utc\nfrom datetime import datetime\n\nconvert_to_utc(datetime.now())\n```\n\nUse instead:\n```python\nfrom airflow.sdk.timezone import convert_to_utc\nfrom datetime import datetime\n\nconvert_to_utc(datetime.now())\n```\n",
|
|
15
|
+
"ruff/ERA001": "## What it does\nChecks for commented-out Python code.\n\n## Why is this bad?\nCommented-out code is dead code, and is often included inadvertently.\nIt should be removed.\n\n## Known problems\nProne to false positives when checking comments that resemble Python code,\nbut are not actually Python code ([#4845]).\n\n## Example\n```python\n# print(\"Hello, world!\")\n```\n\n## Options\n- `lint.task-tags`\n\n[#4845]: https://github.com/astral-sh/ruff/issues/4845\n",
|
|
16
|
+
"ruff/FAST001": "## What it does\nChecks for FastAPI routes that use the optional `response_model` parameter\nwith the same type as the return type.\n\n## Why is this bad?\nFastAPI routes automatically infer the response model type from the return\ntype, so specifying it explicitly is redundant.\n\nThe `response_model` parameter is used to override the default response\nmodel type. For example, `response_model` can be used to specify that\na non-serializable response type should instead be serialized via an\nalternative type.\n\nFor more information, see the [FastAPI documentation](https://fastapi.tiangolo.com/tutorial/response-model/).\n\n## Example\n\n```python\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n\n\n@app.post(\"/items/\", response_model=Item)\nasync def create_item(item: Item) -> Item:\n return item\n```\n\nUse instead:\n\n```python\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n\nclass Item(BaseModel):\n name: str\n\n\n@app.post(\"/items/\")\nasync def create_item(item: Item) -> Item:\n return item\n```\n\n## Fix safety\nThis fix is always unsafe, as removing the `response_model` argument can change\nruntime behavior and API documentation generation. Additionally, comments inside\nthe decorator might be removed when the argument is deleted.\n",
|
|
17
|
+
"ruff/FAST002": "## What it does\nIdentifies FastAPI routes with deprecated uses of `Depends` or similar.\n\n## Why is this bad?\nThe [FastAPI documentation] recommends the use of [`typing.Annotated`][typing-annotated]\nfor defining route dependencies and parameters, rather than using `Depends`,\n`Query` or similar as a default value for a parameter. Using this approach\neverywhere helps ensure consistency and clarity in defining dependencies\nand parameters.\n\n`Annotated` was added to the `typing` module in Python 3.9; however,\nthe third-party [`typing_extensions`][typing-extensions] package\nprovides a backport that can be used on older versions of Python.\n\n## Example\n\n```python\nfrom fastapi import Depends, FastAPI\n\napp = FastAPI()\n\n\nasync def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):\n return {\"q\": q, \"skip\": skip, \"limit\": limit}\n\n\n@app.get(\"/items/\")\nasync def read_items(commons: dict = Depends(common_parameters)):\n return commons\n```\n\nUse instead:\n\n```python\nfrom typing import Annotated\n\nfrom fastapi import Depends, FastAPI\n\napp = FastAPI()\n\n\nasync def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):\n return {\"q\": q, \"skip\": skip, \"limit\": limit}\n\n\n@app.get(\"/items/\")\nasync def read_items(commons: Annotated[dict, Depends(common_parameters)]):\n return commons\n```\n\n## Fix safety\nThis fix is always unsafe, as adding/removing/changing a function parameter's\ndefault value can change runtime behavior. Additionally, comments inside the\ndeprecated uses might be removed.\n\n## Availability\n\nBecause this rule relies on the third-party `typing_extensions` module for Python versions\nbefore 3.9, if the target version is < 3.9 and `typing_extensions` imports have been\ndisabled by the [`lint.typing-extensions`] linter option the diagnostic will not be emitted\nand no fix will be offered.\n\n## Options\n\n- `lint.typing-extensions`\n\n[FastAPI documentation]: https://fastapi.tiangolo.com/tutorial/query-params-str-validations/?h=annotated#advantages-of-annotated\n[typing-annotated]: https://docs.python.org/3/library/typing.html#typing.Annotated\n[typing-extensions]: https://typing-extensions.readthedocs.io/en/stable/\n",
|
|
18
|
+
"ruff/FAST003": "## What it does\nIdentifies FastAPI routes that declare path parameters in the route path\nthat are not included in the function signature.\n\n## Why is this bad?\nPath parameters are used to extract values from the URL path.\n\nIf a path parameter is declared in the route path but not in the function\nsignature, it will not be accessible in the function body, which is likely\na mistake.\n\nIf a path parameter is declared in the route path, but as a positional-only\nargument in the function signature, it will also not be accessible in the\nfunction body, as FastAPI will not inject the parameter.\n\n## Known problems\nIf the path parameter is _not_ a valid Python identifier (e.g., `user-id`, as\nopposed to `user_id`), FastAPI will normalize it. However, this rule simply\nignores such path parameters, as FastAPI's normalization behavior is undocumented.\n\n## Example\n\n```python\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n\n@app.get(\"/things/{thing_id}\")\nasync def read_thing(query: str): ...\n```\n\nUse instead:\n\n```python\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n\n@app.get(\"/things/{thing_id}\")\nasync def read_thing(thing_id: int, query: str): ...\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as modifying a function signature can\nchange the behavior of the code.\n",
|
|
19
|
+
"ruff/YTT101": "## What it does\nChecks for uses of `sys.version[:3]`.\n\n## Why is this bad?\nIf the current major or minor version consists of multiple digits,\n`sys.version[:3]` will truncate the version number (e.g., `\"3.10\"` would\nbecome `\"3.1\"`). This is likely unintended, and can lead to subtle bugs if\nthe version string is used to test against a specific Python version.\n\nInstead, use `sys.version_info` to access the current major and minor\nversion numbers as a tuple, which can be compared to other tuples\nwithout issue.\n\n## Example\n```python\nimport sys\n\nsys.version[:3] # Evaluates to \"3.1\" on Python 3.10.\n```\n\nUse instead:\n```python\nimport sys\n\nsys.version_info[:2] # Evaluates to (3, 10) on Python 3.10.\n```\n\n## References\n- [Python documentation: `sys.version`](https://docs.python.org/3/library/sys.html#sys.version)\n- [Python documentation: `sys.version_info`](https://docs.python.org/3/library/sys.html#sys.version_info)\n",
|
|
20
|
+
"ruff/YTT102": "## What it does\nChecks for uses of `sys.version[2]`.\n\n## Why is this bad?\nIf the current major or minor version consists of multiple digits,\n`sys.version[2]` will select the first digit of the minor number only\n(e.g., `\"3.10\"` would evaluate to `\"1\"`). This is likely unintended, and\ncan lead to subtle bugs if the version is used to test against a minor\nversion number.\n\nInstead, use `sys.version_info.minor` to access the current minor version\nnumber.\n\n## Example\n```python\nimport sys\n\nsys.version[2] # Evaluates to \"1\" on Python 3.10.\n```\n\nUse instead:\n```python\nimport sys\n\nf\"{sys.version_info.minor}\" # Evaluates to \"10\" on Python 3.10.\n```\n\n## References\n- [Python documentation: `sys.version`](https://docs.python.org/3/library/sys.html#sys.version)\n- [Python documentation: `sys.version_info`](https://docs.python.org/3/library/sys.html#sys.version_info)\n",
|
|
21
|
+
"ruff/YTT103": "## What it does\nChecks for comparisons that test `sys.version` against string literals,\nsuch that the comparison will evaluate to `False` on Python 3.10 or later.\n\n## Why is this bad?\nComparing `sys.version` to a string is error-prone and may cause subtle\nbugs, as the comparison will be performed lexicographically, not\nsemantically. For example, `sys.version > \"3.9\"` will evaluate to `False`\nwhen using Python 3.10, as `\"3.10\"` is lexicographically \"less\" than\n`\"3.9\"`.\n\nInstead, use `sys.version_info` to access the current major and minor\nversion numbers as a tuple, which can be compared to other tuples\nwithout issue.\n\n## Example\n```python\nimport sys\n\nsys.version > \"3.9\" # `False` on Python 3.10.\n```\n\nUse instead:\n```python\nimport sys\n\nsys.version_info > (3, 9) # `True` on Python 3.10.\n```\n\n## References\n- [Python documentation: `sys.version`](https://docs.python.org/3/library/sys.html#sys.version)\n- [Python documentation: `sys.version_info`](https://docs.python.org/3/library/sys.html#sys.version_info)\n",
|
|
22
|
+
"ruff/YTT201": "## What it does\nChecks for equality comparisons against the major version returned by\n`sys.version_info` (e.g., `sys.version_info[0] == 3` or `sys.version_info[0] != 3`).\n\n## Why is this bad?\nUsing `sys.version_info[0] == 3` to verify that the major version is\nPython 3 or greater will fail if the major version number is ever\nincremented (e.g., to Python 4). This is likely unintended, as code\nthat uses this comparison is likely intended to be run on Python 2,\nbut would now run on Python 4 too. Similarly, using `sys.version_info[0] != 3`\nto check for Python 2 will also fail if the major version number is\nincremented.\n\nInstead, use `>=` to check if the major version number is 3 or greater,\nor `<` to check if the major version number is less than 3, to future-proof\nthe code.\n\n## Example\n```python\nimport sys\n\nif sys.version_info[0] == 3:\n ...\nelse:\n print(\"Python 2\") # This will be printed on Python 4.\n```\n\nUse instead:\n```python\nimport sys\n\nif sys.version_info >= (3,):\n ...\nelse:\n print(\"Python 2\") # This will not be printed on Python 4.\n```\n\n## References\n- [Python documentation: `sys.version`](https://docs.python.org/3/library/sys.html#sys.version)\n- [Python documentation: `sys.version_info`](https://docs.python.org/3/library/sys.html#sys.version_info)\n",
|
|
23
|
+
"ruff/YTT202": "## What it does\nChecks for uses of `six.PY3`.\n\n## Why is this bad?\n`six.PY3` will evaluate to `False` on Python 4 and greater. This is likely\nunintended, and may cause code intended to run on Python 2 to run on Python 4\ntoo.\n\nInstead, use `not six.PY2` to validate that the current Python major version is\n_not_ equal to 2, to future-proof the code.\n\n## Example\n```python\nimport six\n\nsix.PY3 # `False` on Python 4.\n```\n\nUse instead:\n```python\nimport six\n\nnot six.PY2 # `True` on Python 4.\n```\n\n## References\n- [PyPI: `six`](https://pypi.org/project/six/)\n- [Six documentation: `six.PY2`](https://six.readthedocs.io/#six.PY2)\n- [Six documentation: `six.PY3`](https://six.readthedocs.io/#six.PY3)\n",
|
|
24
|
+
"ruff/YTT203": "## What it does\nChecks for comparisons that test `sys.version_info[1]` against an integer.\n\n## Why is this bad?\nComparisons based on the current minor version number alone can cause\nsubtle bugs and would likely lead to unintended effects if the Python\nmajor version number were ever incremented (e.g., to Python 4).\n\nInstead, compare `sys.version_info` to a tuple, including the major and\nminor version numbers, to future-proof the code.\n\n## Example\n```python\nimport sys\n\nif sys.version_info[1] < 7:\n print(\"Python 3.6 or earlier.\") # This will be printed on Python 4.0.\n```\n\nUse instead:\n```python\nimport sys\n\nif sys.version_info < (3, 7):\n print(\"Python 3.6 or earlier.\")\n```\n\n## References\n- [Python documentation: `sys.version`](https://docs.python.org/3/library/sys.html#sys.version)\n- [Python documentation: `sys.version_info`](https://docs.python.org/3/library/sys.html#sys.version_info)\n",
|
|
25
|
+
"ruff/YTT204": "## What it does\nChecks for comparisons that test `sys.version_info.minor` against an integer.\n\n## Why is this bad?\nComparisons based on the current minor version number alone can cause\nsubtle bugs and would likely lead to unintended effects if the Python\nmajor version number were ever incremented (e.g., to Python 4).\n\nInstead, compare `sys.version_info` to a tuple, including the major and\nminor version numbers, to future-proof the code.\n\n## Example\n```python\nimport sys\n\nif sys.version_info.minor < 7:\n print(\"Python 3.6 or earlier.\") # This will be printed on Python 4.0.\n```\n\nUse instead:\n```python\nimport sys\n\nif sys.version_info < (3, 7):\n print(\"Python 3.6 or earlier.\")\n```\n\n## References\n- [Python documentation: `sys.version`](https://docs.python.org/3/library/sys.html#sys.version)\n- [Python documentation: `sys.version_info`](https://docs.python.org/3/library/sys.html#sys.version_info)\n",
|
|
26
|
+
"ruff/YTT301": "## What it does\nChecks for uses of `sys.version[0]`.\n\n## Why is this bad?\nIf the current major or minor version consists of multiple digits,\n`sys.version[0]` will select the first digit of the major version number\nonly (e.g., `\"10.2\"` would evaluate to `\"1\"`). This is likely unintended,\nand can lead to subtle bugs if the version string is used to test against a\nmajor version number.\n\nInstead, use `sys.version_info.major` to access the current major version\nnumber.\n\n## Example\n```python\nimport sys\n\nsys.version[0] # If using Python 10, this evaluates to \"1\".\n```\n\nUse instead:\n```python\nimport sys\n\nf\"{sys.version_info.major}\" # If using Python 10, this evaluates to \"10\".\n```\n\n## References\n- [Python documentation: `sys.version`](https://docs.python.org/3/library/sys.html#sys.version)\n- [Python documentation: `sys.version_info`](https://docs.python.org/3/library/sys.html#sys.version_info)\n",
|
|
27
|
+
"ruff/YTT302": "## What it does\nChecks for comparisons that test `sys.version` against string literals,\nsuch that the comparison would fail if the major version number were\never incremented to Python 10 or higher.\n\n## Why is this bad?\nComparing `sys.version` to a string is error-prone and may cause subtle\nbugs, as the comparison will be performed lexicographically, not\nsemantically.\n\nInstead, use `sys.version_info` to access the current major and minor\nversion numbers as a tuple, which can be compared to other tuples\nwithout issue.\n\n## Example\n```python\nimport sys\n\nsys.version >= \"3\" # `False` on Python 10.\n```\n\nUse instead:\n```python\nimport sys\n\nsys.version_info >= (3,) # `True` on Python 10.\n```\n\n## References\n- [Python documentation: `sys.version`](https://docs.python.org/3/library/sys.html#sys.version)\n- [Python documentation: `sys.version_info`](https://docs.python.org/3/library/sys.html#sys.version_info)\n",
|
|
28
|
+
"ruff/YTT303": "## What it does\nChecks for uses of `sys.version[:1]`.\n\n## Why is this bad?\nIf the major version number consists of more than one digit, this will\nselect the first digit of the major version number only (e.g., `\"10.0\"`\nwould evaluate to `\"1\"`). This is likely unintended, and can lead to subtle\nbugs in future versions of Python if the version string is used to test\nagainst a specific major version number.\n\nInstead, use `sys.version_info.major` to access the current major version\nnumber.\n\n## Example\n```python\nimport sys\n\nsys.version[:1] # If using Python 10, this evaluates to \"1\".\n```\n\nUse instead:\n```python\nimport sys\n\nf\"{sys.version_info.major}\" # If using Python 10, this evaluates to \"10\".\n```\n\n## References\n- [Python documentation: `sys.version`](https://docs.python.org/3/library/sys.html#sys.version)\n- [Python documentation: `sys.version_info`](https://docs.python.org/3/library/sys.html#sys.version_info)\n",
|
|
29
|
+
"ruff/ANN001": "## What it does\nChecks that function arguments have type annotations.\n\n## Why is this bad?\nType annotations are a good way to document the types of function arguments. They also\nhelp catch bugs, when used alongside a type checker, by ensuring that the types of\nany provided arguments match expectation.\n\n## Example\n\n```python\ndef foo(x): ...\n```\n\nUse instead:\n\n```python\ndef foo(x: int): ...\n```\n\n## Options\n- `lint.flake8-annotations.suppress-dummy-args`\n",
|
|
30
|
+
"ruff/ANN002": "## What it does\nChecks that function `*args` arguments have type annotations.\n\n## Why is this bad?\nType annotations are a good way to document the types of function arguments. They also\nhelp catch bugs, when used alongside a type checker, by ensuring that the types of\nany provided arguments match expectation.\n\n## Example\n\n```python\ndef foo(*args): ...\n```\n\nUse instead:\n\n```python\ndef foo(*args: int): ...\n```\n\n## Options\n- `lint.flake8-annotations.suppress-dummy-args`\n",
|
|
31
|
+
"ruff/ANN003": "## What it does\nChecks that function `**kwargs` arguments have type annotations.\n\n## Why is this bad?\nType annotations are a good way to document the types of function arguments. They also\nhelp catch bugs, when used alongside a type checker, by ensuring that the types of\nany provided arguments match expectation.\n\n## Example\n\n```python\ndef foo(**kwargs): ...\n```\n\nUse instead:\n\n```python\ndef foo(**kwargs: int): ...\n```\n\n## Options\n- `lint.flake8-annotations.suppress-dummy-args`\n",
|
|
32
|
+
"ruff/ANN101": "## Removed\nThis rule has been removed because type checkers can infer this type without annotation.\n\n## What it does\nChecks that instance method `self` arguments have type annotations.\n\n## Why is this bad?\nType annotations are a good way to document the types of function arguments. They also\nhelp catch bugs, when used alongside a type checker, by ensuring that the types of\nany provided arguments match expectation.\n\nNote that many type checkers will infer the type of `self` automatically, so this\nannotation is not strictly necessary.\n\n## Example\n\n```python\nclass Foo:\n def bar(self): ...\n```\n\nUse instead:\n\n```python\nclass Foo:\n def bar(self: \"Foo\"): ...\n```\n",
|
|
33
|
+
"ruff/ANN102": "## Removed\nThis rule has been removed because type checkers can infer this type without annotation.\n\n## What it does\nChecks that class method `cls` arguments have type annotations.\n\n## Why is this bad?\nType annotations are a good way to document the types of function arguments. They also\nhelp catch bugs, when used alongside a type checker, by ensuring that the types of\nany provided arguments match expectation.\n\nNote that many type checkers will infer the type of `cls` automatically, so this\nannotation is not strictly necessary.\n\n## Example\n\n```python\nclass Foo:\n @classmethod\n def bar(cls): ...\n```\n\nUse instead:\n\n```python\nclass Foo:\n @classmethod\n def bar(cls: Type[\"Foo\"]): ...\n```\n",
|
|
34
|
+
"ruff/ANN201": "## What it does\nChecks that public functions and methods have return type annotations.\n\n## Why is this bad?\nType annotations are a good way to document the return types of functions. They also\nhelp catch bugs, when used alongside a type checker, by ensuring that the types of\nany returned values, and the types expected by callers, match expectation.\n\n## Example\n```python\ndef add(a, b):\n return a + b\n```\n\nUse instead:\n```python\ndef add(a: int, b: int) -> int:\n return a + b\n```\n\n## Availability\n\nBecause this rule relies on the third-party `typing_extensions` module for some Python versions,\nits diagnostic will not be emitted, and no fix will be offered, if `typing_extensions` imports\nhave been disabled by the [`lint.typing-extensions`] linter option.\n\n## Options\n\n- `lint.typing-extensions`\n",
|
|
35
|
+
"ruff/ANN202": "## What it does\nChecks that private functions and methods have return type annotations.\n\n## Why is this bad?\nType annotations are a good way to document the return types of functions. They also\nhelp catch bugs, when used alongside a type checker, by ensuring that the types of\nany returned values, and the types expected by callers, match expectation.\n\n## Example\n```python\ndef _add(a, b):\n return a + b\n```\n\nUse instead:\n```python\ndef _add(a: int, b: int) -> int:\n return a + b\n```\n\n## Availability\n\nBecause this rule relies on the third-party `typing_extensions` module for some Python versions,\nits diagnostic will not be emitted, and no fix will be offered, if `typing_extensions` imports\nhave been disabled by the [`lint.typing-extensions`] linter option.\n\n## Options\n\n- `lint.typing-extensions`\n",
|
|
36
|
+
"ruff/ANN204": "## What it does\nChecks that \"special\" methods, like `__init__`, `__new__`, and `__call__`, have\nreturn type annotations.\n\n## Why is this bad?\nType annotations are a good way to document the return types of functions. They also\nhelp catch bugs, when used alongside a type checker, by ensuring that the types of\nany returned values, and the types expected by callers, match expectation.\n\nNote that type checkers often allow you to omit the return type annotation for\n`__init__` methods, as long as at least one argument has a type annotation. To\nopt in to this behavior, use the `mypy-init-return` setting in your `pyproject.toml`\nor `ruff.toml` file:\n\n```toml\n[tool.ruff.lint.flake8-annotations]\nmypy-init-return = true\n```\n\n## Example\n```python\nclass Foo:\n def __init__(self, x: int):\n self.x = x\n```\n\nUse instead:\n```python\nclass Foo:\n def __init__(self, x: int) -> None:\n self.x = x\n```\n\n## Options\n\n- `lint.flake8-annotations.mypy-init-return`\n",
|
|
37
|
+
"ruff/ANN205": "## What it does\nChecks that static methods have return type annotations.\n\n## Why is this bad?\nType annotations are a good way to document the return types of functions. They also\nhelp catch bugs, when used alongside a type checker, by ensuring that the types of\nany returned values, and the types expected by callers, match expectation.\n\n## Example\n```python\nclass Foo:\n @staticmethod\n def bar():\n return 1\n```\n\nUse instead:\n```python\nclass Foo:\n @staticmethod\n def bar() -> int:\n return 1\n```\n\n## Options\n\n- `lint.flake8-annotations.suppress-none-returning`\n",
|
|
38
|
+
"ruff/ANN206": "## What it does\nChecks that class methods have return type annotations.\n\n## Why is this bad?\nType annotations are a good way to document the return types of functions. They also\nhelp catch bugs, when used alongside a type checker, by ensuring that the types of\nany returned values, and the types expected by callers, match expectation.\n\n## Example\n```python\nclass Foo:\n @classmethod\n def bar(cls):\n return 1\n```\n\nUse instead:\n```python\nclass Foo:\n @classmethod\n def bar(cls) -> int:\n return 1\n```\n\n## Options\n\n- `lint.flake8-annotations.suppress-none-returning`\n",
|
|
39
|
+
"ruff/ANN401": "## What it does\nChecks that function arguments and return values are annotated with a more\nspecific type than `Any`.\n\n## Why is this bad?\n`Any` is a special type indicating an unconstrained type. When an\nexpression is annotated with type `Any`, type checkers will allow all\noperations on it.\n\nIt's better to be explicit about the type of an expression, and to use\n`Any` as an \"escape hatch\" only when it is really needed.\n\n## Example\n\n```python\nfrom typing import Any\n\n\ndef foo(x: Any) -> Any: ...\n```\n\nUse instead:\n\n```python\ndef foo(x: int) -> int: ...\n```\n\n## Known problems\n\nType aliases are unsupported and can lead to false positives.\nFor example, the following will trigger this rule inadvertently:\n\n```python\nfrom typing import Any\n\nMyAny = Any\n\n\ndef foo(x: MyAny): ...\n```\n\n## Options\n- `lint.flake8-annotations.allow-star-arg-any`\n\n## References\n- [Typing spec: `Any`](https://typing.python.org/en/latest/spec/special-types.html#any)\n- [Python documentation: `typing.Any`](https://docs.python.org/3/library/typing.html#typing.Any)\n- [Mypy documentation: The Any type](https://mypy.readthedocs.io/en/stable/kinds_of_types.html#the-any-type)\n",
|
|
40
|
+
"ruff/ASYNC100": "## What it does\nChecks for timeout context managers which do not contain a checkpoint.\n\nFor the purposes of this check, `yield` is considered a checkpoint,\nsince checkpoints may occur in the caller to which we yield.\n\n## Why is this bad?\nSome asynchronous context managers, such as `asyncio.timeout` and\n`trio.move_on_after`, have no effect unless they contain a checkpoint.\nThe use of such context managers without an `await`, `async with` or\n`async for` statement is likely a mistake.\n\n## Example\n```python\nimport asyncio\n\n\nasync def func():\n async with asyncio.timeout(2):\n do_something()\n```\n\nUse instead:\n```python\nimport asyncio\n\n\nasync def func():\n async with asyncio.timeout(2):\n do_something()\n await awaitable()\n```\n\n## References\n- [`asyncio` timeouts](https://docs.python.org/3/library/asyncio-task.html#timeouts)\n- [`anyio` timeouts](https://anyio.readthedocs.io/en/stable/cancellation.html)\n- [`trio` timeouts](https://trio.readthedocs.io/en/stable/reference-core.html#cancellation-and-timeouts)\n",
|
|
41
|
+
"ruff/ASYNC105": "## What it does\nChecks for calls to trio functions that are not immediately awaited.\n\n## Why is this bad?\nMany of the functions exposed by trio are asynchronous, and must be awaited\nto take effect. Calling a trio function without an `await` can lead to\n`RuntimeWarning` diagnostics and unexpected behaviour.\n\n## Example\n```python\nimport trio\n\n\nasync def double_sleep(x):\n trio.sleep(2 * x)\n```\n\nUse instead:\n```python\nimport trio\n\n\nasync def double_sleep(x):\n await trio.sleep(2 * x)\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as adding an `await` to a function\ncall changes its semantics and runtime behavior.\n",
|
|
42
|
+
"ruff/ASYNC109": "## What it does\nChecks for `async` function definitions with `timeout` parameters.\n\n## Why is this bad?\nRather than implementing asynchronous timeout behavior manually, prefer\nbuilt-in timeout functionality, such as `asyncio.timeout`, `trio.fail_after`,\nor `anyio.move_on_after`, among others.\n\nThis rule is highly opinionated to enforce a design pattern\ncalled [\"structured concurrency\"] that allows for\n`async` functions to be oblivious to timeouts,\ninstead letting callers to handle the logic with a context manager.\n\n## Details\n\nThis rule attempts to detect which async framework your code is using\nby analysing the imports in the file it's checking. If it sees an\n`anyio` import in your code, it will assume `anyio` is your framework\nof choice; if it sees a `trio` import, it will assume `trio`; if it\nsees neither, it will assume `asyncio`. `asyncio.timeout` was added\nin Python 3.11, so if `asyncio` is detected as the framework being used,\nthis rule will be ignored when your configured [`target-version`] is set\nto less than Python 3.11.\n\nFor functions that wrap `asyncio.timeout`, `trio.fail_after` or\n`anyio.move_on_after`, false positives from this rule can be avoided\nby using a different parameter name.\n\nThis rule exempts methods decorated with [`@typing.override`][override].\nRemoving a parameter from a subclass method may cause type checkers to\ncomplain about a violation of the Liskov Substitution Principle if it\nmeans that the method now incompatibly overrides a method defined on a\nsuperclass. Explicitly decorating an overriding method with `@override`\nsignals to Ruff that the method is intended to override a superclass\nmethod and that a type checker will enforce that it does so; Ruff\ntherefore knows that it should not enforce this rule on such methods.\n\n## Example\n\n```python\nasync def long_running_task(timeout): ...\n\n\nasync def main():\n await long_running_task(timeout=2)\n```\n\nUse instead:\n\n```python\nasync def long_running_task(): ...\n\n\nasync def main():\n async with asyncio.timeout(2):\n await long_running_task()\n```\n\n## References\n- [`asyncio` timeouts](https://docs.python.org/3/library/asyncio-task.html#timeouts)\n- [`anyio` timeouts](https://anyio.readthedocs.io/en/stable/cancellation.html)\n- [`trio` timeouts](https://trio.readthedocs.io/en/stable/reference-core.html#cancellation-and-timeouts)\n\n[\"structured concurrency\"]: https://vorpus.org/blog/some-thoughts-on-asynchronous-api-design-in-a-post-asyncawait-world/#timeouts-and-cancellation\n[override]: https://docs.python.org/3/library/typing.html#typing.override\n",
|
|
43
|
+
"ruff/ASYNC110": "## What it does\nChecks for the use of an async sleep function in a `while` loop.\n\n## Why is this bad?\nBusy-waiting for a condition in a loop forces a tradeoff between\nefficiency and latency: shorter sleep times improve responsiveness\nbut waste more CPU cycles, while longer sleep times reduce CPU usage\nbut delay reaction to state changes.\n\nWaiting on an `Event` object like `asyncio.Event`, `trio.Event`, or\n`anyio.Event` eliminates this tradeoff, allowing immediate response\nwith minimal wasted CPU time.\n\n## Example\n```python\nimport asyncio\n\nDONE = False\n\n\nasync def func():\n while not DONE:\n await asyncio.sleep(1)\n```\n\nUse instead:\n```python\nimport asyncio\n\nDONE = asyncio.Event()\n\n\nasync def func():\n await DONE.wait()\n```\n\n## References\n- [`asyncio` events](https://docs.python.org/3/library/asyncio-sync.html#asyncio.Event)\n- [`anyio` events](https://anyio.readthedocs.io/en/latest/api.html#anyio.Event)\n- [`trio` events](https://trio.readthedocs.io/en/latest/reference-core.html#trio.Event)\n",
|
|
44
|
+
"ruff/ASYNC115": "## What it does\nChecks for uses of `trio.sleep(0)` or `anyio.sleep(0)`.\n\n## Why is this bad?\n`trio.sleep(0)` is equivalent to calling `trio.lowlevel.checkpoint()`.\nHowever, the latter better conveys the intent of the code.\n\n## Example\n```python\nimport trio\n\n\nasync def func():\n await trio.sleep(0)\n```\n\nUse instead:\n```python\nimport trio.lowlevel\n\n\nasync def func():\n await trio.lowlevel.checkpoint()\n```\n## Fix safety\nThis rule's fix is marked as unsafe if there's comments in the\n`trio.sleep(0)` expression, as comments may be removed.\n\nFor example, the fix would be marked as unsafe in the following case:\n```python\nimport trio\n\n\nasync def func():\n await trio.sleep( # comment\n # comment\n 0\n )\n```\n",
|
|
45
|
+
"ruff/ASYNC116": "## What it does\nChecks for uses of `trio.sleep()` or `anyio.sleep()` with a delay greater than 24 hours.\n\n## Why is this bad?\nCalling `sleep()` with a delay greater than 24 hours is usually intended\nto sleep indefinitely. Instead of using a large delay,\n`trio.sleep_forever()` or `anyio.sleep_forever()` better conveys the intent.\n\n\n## Example\n```python\nimport trio\n\n\nasync def func():\n await trio.sleep(86401)\n```\n\nUse instead:\n```python\nimport trio\n\n\nasync def func():\n await trio.sleep_forever()\n```\n\n## Fix safety\n\nThis fix is marked as unsafe as it changes program behavior.\n",
|
|
46
|
+
"ruff/ASYNC119": "## What it does\nChecks for `yield` inside a context manager in an async generator.\n\n## Why is this bad?\nYielding inside a context manager in an async generator is unsafe because\nthe cleanup of the context manager may be delayed until the generator is\nclosed, at which point `await` is no longer allowed. This can lead to\nresource leaks or other bugs.\n\nFor more information, see [PEP 533](https://peps.python.org/pep-0533/).\n\nIf the function is intended to yield only once and act as a context\nmanager, use `@asynccontextmanager`. If it's a true async generator\nthat yields multiple values, consumers should use `contextlib.aclosing` to\nensure timely cleanup, or the generator should be refactored to avoid\nholding context managers open across yields.\n\nThe rule also suppresses diagnostics for functions decorated with\n`@pytest.fixture`, `@pytest_asyncio.fixture`, or `@trio.as_safe_channel`,\nas these handle async generator cleanup safely.\n\n## Example\n\nThe following function yields once inside a context manager, but without\n`@asynccontextmanager`, cleanup of the connection may be delayed:\n```python\nasync def open_connection():\n async with connect() as conn:\n yield conn\n```\n\nIf the function is intended to yield exactly once (i.e., it's a context\nmanager), add `@asynccontextmanager`:\n```python\nfrom contextlib import asynccontextmanager\n\n\n@asynccontextmanager\nasync def open_connection():\n async with connect() as conn:\n yield conn\n```\n\nFor async generators that yield multiple values, `@asynccontextmanager`\nis not appropriate. Instead, refactor to avoid holding context managers\nopen across yields, or ensure consumers use `contextlib.aclosing` for timely\ncleanup.\n\n## Known problems\nUsing `contextlib.aclosing` around all call sites of an async generator is a\nvalid way to guarantee timely cleanup, but this rule cannot verify that\nall callers use `aclosing`. As a result, it may flag generators that\nare always consumed safely.\n\n## References\n- [PEP 533 \u2013 Deterministic cleanup for iterators](https://peps.python.org/pep-0533/)\n- [`contextlib.aclosing`](https://docs.python.org/3/library/contextlib.html#contextlib.aclosing)\n- [trio.as_safe_channel](https://trio.readthedocs.io/en/latest/reference-core.html#trio.as_safe_channel)\n",
|
|
47
|
+
"ruff/ASYNC210": "## What it does\nChecks that async functions do not contain blocking HTTP calls.\n\n## Why is this bad?\nBlocking an async function via a blocking HTTP call will block the entire\nevent loop, preventing it from executing other tasks while waiting for the\nHTTP response, negating the benefits of asynchronous programming.\n\nInstead of making a blocking HTTP call, use an asynchronous HTTP client\nlibrary such as `aiohttp` or `httpx`.\n\n## Example\n```python\nimport urllib\n\n\nasync def fetch():\n urllib.request.urlopen(\"https://example.com/foo/bar\").read()\n```\n\nUse instead:\n```python\nimport aiohttp\n\n\nasync def fetch():\n async with aiohttp.ClientSession() as session:\n async with session.get(\"https://example.com/foo/bar\") as resp:\n ...\n```\n",
|
|
48
|
+
"ruff/ASYNC212": "## What it does\nChecks that async functions do not use blocking httpx clients.\n\n## Why is this bad?\nBlocking an async function via a blocking HTTP call will block the entire\nevent loop, preventing it from executing other tasks while waiting for the\nHTTP response, negating the benefits of asynchronous programming.\n\nInstead of using the blocking `httpx` client, use the asynchronous client.\n\n## Example\n```python\nimport httpx\n\n\nasync def fetch():\n client = httpx.Client()\n response = client.get(...)\n```\n\nUse instead:\n```python\nimport httpx\n\n\nasync def fetch():\n async with httpx.AsyncClient() as client:\n response = await client.get(...)\n```\n",
|
|
49
|
+
"ruff/ASYNC220": "## What it does\nChecks that async functions do not create subprocesses with blocking methods.\n\n## Why is this bad?\nBlocking an async function via a blocking call will block the entire\nevent loop, preventing it from executing other tasks while waiting for the\ncall to complete, negating the benefits of asynchronous programming.\n\nInstead of making a blocking call, use an equivalent asynchronous library\nor function, like [`trio.run_process()`](https://trio.readthedocs.io/en/stable/reference-io.html#trio.run_process)\nor [`anyio.run_process()`](https://anyio.readthedocs.io/en/latest/api.html#anyio.run_process).\n\n## Example\n```python\nimport os\n\n\nasync def foo():\n os.popen(cmd)\n```\n\nUse instead:\n```python\nimport asyncio\n\n\nasync def foo():\n asyncio.create_subprocess_shell(cmd)\n```\n",
|
|
50
|
+
"ruff/ASYNC221": "## What it does\nChecks that async functions do not run processes with blocking methods.\n\n## Why is this bad?\nBlocking an async function via a blocking call will block the entire\nevent loop, preventing it from executing other tasks while waiting for the\ncall to complete, negating the benefits of asynchronous programming.\n\nInstead of making a blocking call, use an equivalent asynchronous library\nor function, like [`trio.run_process()`](https://trio.readthedocs.io/en/stable/reference-io.html#trio.run_process)\nor [`anyio.run_process()`](https://anyio.readthedocs.io/en/latest/api.html#anyio.run_process).\n\n## Example\n```python\nimport subprocess\n\n\nasync def foo():\n subprocess.run(cmd)\n```\n\nUse instead:\n```python\nimport asyncio\n\n\nasync def foo():\n asyncio.create_subprocess_shell(cmd)\n```\n",
|
|
51
|
+
"ruff/ASYNC222": "## What it does\nChecks that async functions do not wait on processes with blocking methods.\n\n## Why is this bad?\nBlocking an async function via a blocking call will block the entire\nevent loop, preventing it from executing other tasks while waiting for the\ncall to complete, negating the benefits of asynchronous programming.\n\nInstead of making a blocking call, use an equivalent asynchronous library\nor function, like [`trio.to_thread.run_sync()`](https://trio.readthedocs.io/en/latest/reference-core.html#trio.to_thread.run_sync)\nor [`anyio.to_thread.run_sync()`](https://anyio.readthedocs.io/en/latest/api.html#anyio.to_thread.run_sync).\n\n## Example\n```python\nimport os\n\n\nasync def foo():\n os.waitpid(0)\n```\n\nUse instead:\n```python\nimport asyncio\nimport os\n\n\ndef wait_for_process():\n os.waitpid(0)\n\n\nasync def foo():\n await asyncio.loop.run_in_executor(None, wait_for_process)\n```\n",
|
|
52
|
+
"ruff/ASYNC230": "## What it does\nChecks that async functions do not open files with blocking methods like `open`.\n\n## Why is this bad?\nBlocking an async function via a blocking call will block the entire\nevent loop, preventing it from executing other tasks while waiting for the\ncall to complete, negating the benefits of asynchronous programming.\n\nInstead of making a blocking call, use an equivalent asynchronous library\nor function.\n\n## Example\n```python\nasync def foo():\n with open(\"bar.txt\") as f:\n contents = f.read()\n```\n\nUse instead:\n```python\nimport anyio\n\n\nasync def foo():\n async with await anyio.open_file(\"bar.txt\") as f:\n contents = await f.read()\n```\n",
|
|
53
|
+
"ruff/ASYNC240": "## What it does\nChecks that async functions do not call blocking `os.path` functions or\n`pathlib.Path` methods.\n\n## Why is this bad?\nCalling some `os.path` functions or `pathlib.Path` methods in an async function\nwill block the entire event loop, preventing it from executing other tasks while\nwaiting for the operation. This negates the benefits of asynchronous programming.\n\nInstead, run blocking path operations in a separate thread, or use an API that\nprovides asynchronous path operations, such as `aiofiles.os.path`, `anyio.Path`,\nor `trio.Path`.\n\n## Example\n```python\nimport os\n\n\nasync def func():\n path = \"my_file.txt\"\n file_exists = os.path.exists(path)\n```\n\nOn Python 3.9 and later, use instead:\n```python\nimport asyncio\nimport os\n\n\nasync def func():\n path = \"my_file.txt\"\n file_exists = await asyncio.to_thread(os.path.exists, path)\n```\n\nOn earlier Python versions, use `loop.run_in_executor()`.\n\nOr, use an asynchronous path API:\n```python\nimport trio\n\n\nasync def func():\n path = trio.Path(\"my_file.txt\")\n file_exists = await path.exists()\n```\n\nPurely computational path operations, such as `os.path.join()` and\n`pathlib.Path.with_suffix()`, are not flagged.\n\n## References\n- [Python documentation: `asyncio.to_thread`](https://docs.python.org/3/library/asyncio-task.html#asyncio.to_thread)\n- [Python documentation: `loop.run_in_executor`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor)\n- [aiofiles documentation: `aiofiles.os`](https://github.com/Tinche/aiofiles#usage)\n- [AnyIO documentation: `anyio.Path`](https://anyio.readthedocs.io/en/stable/api.html#anyio.Path)\n- [Trio documentation: `trio.Path`](https://trio.readthedocs.io/en/stable/reference-io.html#trio.Path)\n",
|
|
54
|
+
"ruff/ASYNC250": "## What it does\nChecks that async functions do not contain blocking usage of input from user.\n\n## Why is this bad?\nBlocking an async function via a blocking input call will block the entire\nevent loop, preventing it from executing other tasks while waiting for user\ninput, negating the benefits of asynchronous programming.\n\nInstead of making a blocking input call directly, wrap the input call in\nan executor to execute the blocking call on another thread.\n\n## Example\n```python\nasync def foo():\n username = input(\"Username:\")\n```\n\nUse instead:\n```python\nimport asyncio\n\n\nasync def foo():\n loop = asyncio.get_running_loop()\n username = await loop.run_in_executor(None, input, \"Username:\")\n```\n",
|
|
55
|
+
"ruff/ASYNC251": "## What it does\nChecks that async functions do not call `time.sleep`.\n\n## Why is this bad?\nBlocking an async function via a `time.sleep` call will block the entire\nevent loop, preventing it from executing other tasks while waiting for the\n`time.sleep`, negating the benefits of asynchronous programming.\n\nInstead of `time.sleep`, use `asyncio.sleep`.\n\n## Example\n```python\nimport time\n\n\nasync def fetch():\n time.sleep(1)\n```\n\nUse instead:\n```python\nimport asyncio\n\n\nasync def fetch():\n await asyncio.sleep(1)\n```\n",
|
|
56
|
+
"ruff/S101": "## What it does\nChecks for uses of the `assert` keyword.\n\n## Why is this bad?\nAssertions are removed when Python is run with optimization requested\n(i.e., when the `-O` flag is present), which is a common practice in\nproduction environments. As such, assertions should not be used for runtime\nvalidation of user input or to enforce interface constraints.\n\nConsider raising a meaningful error instead of using `assert`.\n\nThe rule exempts assertions within a `TYPE_CHECKING` block, assuming these are needed to satisfy\na type checker.\n\n## Example\n```python\nassert x > 0, \"Expected positive value.\"\n```\n\nUse instead:\n```python\nif not x > 0:\n raise ValueError(\"Expected positive value.\")\n\n# or even better:\nif x <= 0:\n raise ValueError(\"Expected positive value.\")\n```\n",
|
|
57
|
+
"ruff/S102": "## What it does\nChecks for uses of the builtin `exec` function.\n\n## Why is this bad?\nThe `exec()` function is insecure as it allows for arbitrary code\nexecution.\n\n## Example\n```python\nexec(\"print('Hello World')\")\n```\n\n## References\n- [Python documentation: `exec`](https://docs.python.org/3/library/functions.html#exec)\n- [Common Weakness Enumeration: CWE-78](https://cwe.mitre.org/data/definitions/78.html)\n",
|
|
58
|
+
"ruff/S103": "## What it does\nChecks for files with overly permissive permissions.\n\n## Why is this bad?\nOverly permissive file permissions may allow unintended access and\narbitrary code execution.\n\n## Example\n```python\nimport os\n\nos.chmod(\"/etc/secrets.txt\", 0o666) # rw-rw-rw-\n```\n\nUse instead:\n```python\nimport os\n\nos.chmod(\"/etc/secrets.txt\", 0o600) # rw-------\n```\n\n## Preview\nWhen [preview] is enabled, the set of bits treated as dangerous matches\nupstream Bandit (`0o33`): `S_IWOTH`, `S_IXOTH`, `S_IWGRP`, and `S_IXGRP`.\nOutside preview, only `S_IWOTH` and `S_IXGRP` are flagged.\n\n[preview]: https://docs.astral.sh/ruff/preview/\n\n## References\n- [Python documentation: `os.chmod`](https://docs.python.org/3/library/os.html#os.chmod)\n- [Python documentation: `stat`](https://docs.python.org/3/library/stat.html)\n- [Common Weakness Enumeration: CWE-732](https://cwe.mitre.org/data/definitions/732.html)\n",
|
|
59
|
+
"ruff/S104": "## What it does\nChecks for hardcoded bindings to all network interfaces (`0.0.0.0`).\n\n## Why is this bad?\nBinding to all network interfaces is insecure as it allows access from\nunintended interfaces, which may be poorly secured or unauthorized.\n\nInstead, bind to specific interfaces.\n\n## Example\n```python\nALLOWED_HOSTS = [\"0.0.0.0\"]\n```\n\nUse instead:\n```python\nALLOWED_HOSTS = [\"127.0.0.1\", \"localhost\"]\n```\n\n## References\n- [Common Weakness Enumeration: CWE-200](https://cwe.mitre.org/data/definitions/200.html)\n",
|
|
60
|
+
"ruff/S105": "## What it does\nChecks for potential uses of hardcoded passwords in strings.\n\n## Why is this bad?\nIncluding a hardcoded password in source code is a security risk, as an\nattacker could discover the password and use it to gain unauthorized\naccess.\n\nInstead, store passwords and other secrets in configuration files,\nenvironment variables, or other sources that are excluded from version\ncontrol.\n\n## Example\n```python\nSECRET_KEY = \"hunter2\"\n```\n\nUse instead:\n```python\nimport os\n\nSECRET_KEY = os.environ[\"SECRET_KEY\"]\n```\n\n## References\n- [Common Weakness Enumeration: CWE-259](https://cwe.mitre.org/data/definitions/259.html)\n",
|
|
61
|
+
"ruff/S106": "## What it does\nChecks for potential uses of hardcoded passwords in function calls.\n\n## Why is this bad?\nIncluding a hardcoded password in source code is a security risk, as an\nattacker could discover the password and use it to gain unauthorized\naccess.\n\nInstead, store passwords and other secrets in configuration files,\nenvironment variables, or other sources that are excluded from version\ncontrol.\n\n## Example\n```python\nconnect_to_server(password=\"hunter2\")\n```\n\nUse instead:\n```python\nimport os\n\nconnect_to_server(password=os.environ[\"PASSWORD\"])\n```\n\n## References\n- [Common Weakness Enumeration: CWE-259](https://cwe.mitre.org/data/definitions/259.html)\n",
|
|
62
|
+
"ruff/S107": "## What it does\nChecks for potential uses of hardcoded passwords in function argument\ndefaults.\n\n## Why is this bad?\nIncluding a hardcoded password in source code is a security risk, as an\nattacker could discover the password and use it to gain unauthorized\naccess.\n\nInstead, store passwords and other secrets in configuration files,\nenvironment variables, or other sources that are excluded from version\ncontrol.\n\n## Example\n\n```python\ndef connect_to_server(password=\"hunter2\"): ...\n```\n\nUse instead:\n\n```python\nimport os\n\n\ndef connect_to_server(password=os.environ[\"PASSWORD\"]): ...\n```\n\n## References\n- [Common Weakness Enumeration: CWE-259](https://cwe.mitre.org/data/definitions/259.html)\n",
|
|
63
|
+
"ruff/S108": "## What it does\nChecks for the use of hardcoded temporary file or directory paths.\n\n## Why is this bad?\nThe use of hardcoded paths for temporary files can be insecure. If an\nattacker discovers the location of a hardcoded path, they can replace the\ncontents of the file or directory with a malicious payload.\n\nOther programs may also read or write contents to these hardcoded paths,\ncausing unexpected behavior.\n\n## Example\n```python\nwith open(\"/tmp/foo.txt\", \"w\") as file:\n ...\n```\n\nUse instead:\n```python\nimport tempfile\n\nwith tempfile.NamedTemporaryFile() as file:\n ...\n```\n\n## Options\n- `lint.flake8-bandit.hardcoded-tmp-directory`\n- `lint.flake8-bandit.hardcoded-tmp-directory-extend`\n\n## References\n- [Common Weakness Enumeration: CWE-377](https://cwe.mitre.org/data/definitions/377.html)\n- [Common Weakness Enumeration: CWE-379](https://cwe.mitre.org/data/definitions/379.html)\n- [Python documentation: `tempfile`](https://docs.python.org/3/library/tempfile.html)\n",
|
|
64
|
+
"ruff/S110": "## What it does\nChecks for uses of the `try`-`except`-`pass` pattern.\n\n## Why is this bad?\nThe `try`-`except`-`pass` pattern suppresses all exceptions. Suppressing\nexceptions may hide errors that could otherwise reveal unexpected behavior,\nsecurity vulnerabilities, or malicious activity. Instead, consider logging\nthe exception.\n\n## Example\n```python\ntry:\n ...\nexcept Exception:\n pass\n```\n\nUse instead:\n```python\nimport logging\n\ntry:\n ...\nexcept Exception as exc:\n logging.exception(\"Exception occurred\")\n```\n\n## Options\n- `lint.flake8-bandit.check-typed-exception`\n\n## References\n- [Common Weakness Enumeration: CWE-703](https://cwe.mitre.org/data/definitions/703.html)\n- [Python documentation: `logging`](https://docs.python.org/3/library/logging.html)\n",
|
|
65
|
+
"ruff/S112": "## What it does\nChecks for uses of the `try`-`except`-`continue` pattern.\n\n## Why is this bad?\nThe `try`-`except`-`continue` pattern suppresses all exceptions.\nSuppressing exceptions may hide errors that could otherwise reveal\nunexpected behavior, security vulnerabilities, or malicious activity.\nInstead, consider logging the exception.\n\n## Example\n```python\nimport logging\n\nwhile predicate:\n try:\n ...\n except Exception:\n continue\n```\n\nUse instead:\n```python\nimport logging\n\nwhile predicate:\n try:\n ...\n except Exception as exc:\n logging.exception(\"Error occurred\")\n```\n\n## Options\n- `lint.flake8-bandit.check-typed-exception`\n\n## References\n- [Common Weakness Enumeration: CWE-703](https://cwe.mitre.org/data/definitions/703.html)\n- [Python documentation: `logging`](https://docs.python.org/3/library/logging.html)\n",
|
|
66
|
+
"ruff/S113": "## What it does\nChecks for uses of the Python `requests` or `httpx` module without timeouts.\n\n## Why is this bad?\nThe `timeout` parameter is used to set the maximum time to wait for a\nresponse from the server. By omitting the `timeout` parameter or\nexplicitly disabling it, the program may hang indefinitely while awaiting a\nresponse.\n\n`requests` has no timeout by default, so both omitting the `timeout` argument\nand setting it to `None` are flagged. `httpx` applies a default timeout, so only an explicit\n`timeout=None` is flagged.\n\n## Example\n```python\nimport requests\n\nrequests.get(\"https://www.example.com/\")\n```\n\nUse instead:\n```python\nimport requests\n\nrequests.get(\"https://www.example.com/\", timeout=10)\n```\n\n## References\n- [Requests documentation: Timeouts](https://requests.readthedocs.io/en/latest/user/advanced/#timeouts)\n- [httpx documentation: Timeouts](https://www.python-httpx.org/advanced/timeouts/)\n",
|
|
67
|
+
"ruff/S201": "## What it does\nChecks for uses of `debug=True` in Flask.\n\n## Why is this bad?\nEnabling debug mode shows an interactive debugger in the browser if an\nerror occurs, and allows running arbitrary Python code from the browser.\nThis could leak sensitive information, or allow an attacker to run\narbitrary code.\n\n## Example\n```python\nfrom flask import Flask\n\napp = Flask()\n\napp.run(debug=True)\n```\n\nUse instead:\n```python\nimport os\n\nfrom flask import Flask\n\napp = Flask()\n\napp.run(debug=os.environ[\"ENV\"] == \"dev\")\n```\n\n## References\n- [Flask documentation: Debug Mode](https://flask.palletsprojects.com/en/latest/quickstart/#debug-mode)\n",
|
|
68
|
+
"ruff/S202": "## What it does\nChecks for uses of `tarfile.extractall`.\n\n## Why is this bad?\n\nExtracting archives from untrusted sources without prior inspection is\na security risk, as maliciously crafted archives may contain files that\nwill be written outside of the target directory. For example, the archive\ncould include files with absolute paths (e.g., `/etc/passwd`), or relative\npaths with parent directory references (e.g., `../etc/passwd`).\n\nOn Python 3.12 and later, use `filter='data'` to prevent the most dangerous\nsecurity issues (see: [PEP 706]). On earlier versions, set the `members`\nargument to a trusted subset of the archive's members.\n\n## Example\n```python\nimport tarfile\nimport tempfile\n\ntar = tarfile.open(filename)\ntar.extractall(path=tempfile.mkdtemp())\ntar.close()\n```\n\n## References\n- [Common Weakness Enumeration: CWE-22](https://cwe.mitre.org/data/definitions/22.html)\n- [Python documentation: `TarFile.extractall`](https://docs.python.org/3/library/tarfile.html#tarfile.TarFile.extractall)\n- [Python documentation: Extraction filters](https://docs.python.org/3/library/tarfile.html#tarfile-extraction-filter)\n\n[PEP 706]: https://peps.python.org/pep-0706/#backporting-forward-compatibility\n",
|
|
69
|
+
"ruff/S301": "## What it does\nChecks for calls to `pickle` functions or modules that wrap them.\n\n## Why is this bad?\nDeserializing untrusted data with `pickle` and other deserialization\nmodules is insecure as it can allow for the creation of arbitrary objects,\nwhich can then be used to achieve arbitrary code execution and otherwise\nunexpected behavior.\n\nAvoid deserializing untrusted data with `pickle` and other deserialization\nmodules. Instead, consider safer formats, such as JSON.\n\nIf you must deserialize untrusted data with `pickle`, consider signing the\ndata with a secret key and verifying the signature before deserializing the\npayload, This will prevent an attacker from injecting arbitrary objects\ninto the serialized data.\n\nIn [preview], this rule will also flag references to `pickle` functions.\n\n## Example\n```python\nimport pickle\n\nwith open(\"foo.pickle\", \"rb\") as file:\n foo = pickle.load(file)\n```\n\nUse instead:\n```python\nimport json\n\nwith open(\"foo.json\", \"rb\") as file:\n foo = json.load(file)\n```\n\n## References\n- [Python documentation: `pickle` \u2014 Python object serialization](https://docs.python.org/3/library/pickle.html)\n- [Common Weakness Enumeration: CWE-502](https://cwe.mitre.org/data/definitions/502.html)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
70
|
+
"ruff/S302": "## What it does\nChecks for calls to `marshal` functions.\n\n## Why is this bad?\nDeserializing untrusted data with `marshal` is insecure, as it can allow for\nthe creation of arbitrary objects, which can then be used to achieve\narbitrary code execution and otherwise unexpected behavior.\n\nAvoid deserializing untrusted data with `marshal`. Instead, consider safer\nformats, such as JSON.\n\nIf you must deserialize untrusted data with `marshal`, consider signing the\ndata with a secret key and verifying the signature before deserializing the\npayload. This will prevent an attacker from injecting arbitrary objects\ninto the serialized data.\n\nIn [preview], this rule will also flag references to `marshal` functions.\n\n## Example\n```python\nimport marshal\n\nwith open(\"foo.marshal\", \"rb\") as file:\n foo = marshal.load(file)\n```\n\nUse instead:\n```python\nimport json\n\nwith open(\"foo.json\", \"rb\") as file:\n foo = json.load(file)\n```\n\n## References\n- [Python documentation: `marshal` \u2014 Internal Python object serialization](https://docs.python.org/3/library/marshal.html)\n- [Common Weakness Enumeration: CWE-502](https://cwe.mitre.org/data/definitions/502.html)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
71
|
+
"ruff/S303": "## What it does\nChecks for uses of weak or broken cryptographic hash functions.\n\n## Why is this bad?\nWeak or broken cryptographic hash functions may be susceptible to\ncollision attacks (where two different inputs produce the same hash) or\npre-image attacks (where an attacker can find an input that produces a\ngiven hash). This can lead to security vulnerabilities in applications\nthat rely on these hash functions.\n\nAvoid using weak or broken cryptographic hash functions in security\ncontexts. Instead, use a known secure hash function such as SHA-256.\n\nIn [preview], this rule will also flag references to insecure hash functions.\n\n## Example\n```python\nfrom cryptography.hazmat.primitives import hashes\n\ndigest = hashes.Hash(hashes.MD5())\ndigest.update(b\"Hello, world!\")\ndigest.finalize()\n```\n\nUse instead:\n```python\nfrom cryptography.hazmat.primitives import hashes\n\ndigest = hashes.Hash(hashes.SHA256())\ndigest.update(b\"Hello, world!\")\ndigest.finalize()\n```\n\n## References\n- [Python documentation: `hashlib` \u2014 Secure hashes and message digests](https://docs.python.org/3/library/hashlib.html)\n- [Common Weakness Enumeration: CWE-327](https://cwe.mitre.org/data/definitions/327.html)\n- [Common Weakness Enumeration: CWE-328](https://cwe.mitre.org/data/definitions/328.html)\n- [Common Weakness Enumeration: CWE-916](https://cwe.mitre.org/data/definitions/916.html)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
72
|
+
"ruff/S304": "## What it does\nChecks for uses of weak or broken cryptographic ciphers.\n\n## Why is this bad?\nWeak or broken cryptographic ciphers may be susceptible to attacks that\nallow an attacker to decrypt ciphertext without knowing the key or\notherwise compromise the security of the cipher, such as forgeries.\n\nUse strong, modern cryptographic ciphers instead of weak or broken ones.\n\nIn [preview], this rule will also flag references to insecure ciphers.\n\n## Example\n```python\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms\n\nalgorithm = algorithms.ARC4(key)\ncipher = Cipher(algorithm, mode=None)\nencryptor = cipher.encryptor()\n```\n\nUse instead:\n```python\nfrom cryptography.fernet import Fernet\n\nfernet = Fernet(key)\n```\n\n## References\n- [Common Weakness Enumeration: CWE-327](https://cwe.mitre.org/data/definitions/327.html)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
73
|
+
"ruff/S305": "## What it does\nChecks for uses of weak or broken cryptographic cipher modes.\n\n## Why is this bad?\nWeak or broken cryptographic ciphers may be susceptible to attacks that\nallow an attacker to decrypt ciphertext without knowing the key or\notherwise compromise the security of the cipher, such as forgeries.\n\nUse strong, modern cryptographic ciphers instead of weak or broken ones.\n\nIn [preview], this rule will also flag references to insecure cipher modes.\n\n## Example\n```python\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\n\nalgorithm = algorithms.ARC4(key)\ncipher = Cipher(algorithm, mode=modes.ECB(iv))\nencryptor = cipher.encryptor()\n```\n\nUse instead:\n```python\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\n\nalgorithm = algorithms.ARC4(key)\ncipher = Cipher(algorithm, mode=modes.CTR(iv))\nencryptor = cipher.encryptor()\n```\n\n## References\n- [Common Weakness Enumeration: CWE-327](https://cwe.mitre.org/data/definitions/327.html)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
74
|
+
"ruff/S306": "## What it does\nChecks for uses of `tempfile.mktemp`.\n\n## Why is this bad?\n`tempfile.mktemp` returns a pathname of a file that does not exist at the\ntime the call is made; then, the caller is responsible for creating the\nfile and subsequently using it. This is insecure because another process\ncould create a file with the same name between the time the function\nreturns and the time the caller creates the file.\n\n`tempfile.mktemp` is deprecated in favor of `tempfile.mkstemp` which\ncreates the file when it is called. Consider using `tempfile.mkstemp`\ninstead, either directly or via a context manager such as\n`tempfile.TemporaryFile`.\n\nIn [preview], this rule will also flag references to `tempfile.mktemp`.\n\n## Example\n```python\nimport tempfile\n\ntmp_file = tempfile.mktemp()\nwith open(tmp_file, \"w\") as file:\n file.write(\"Hello, world!\")\n```\n\nUse instead:\n```python\nimport tempfile\n\nwith tempfile.TemporaryFile() as file:\n file.write(\"Hello, world!\")\n```\n\n## References\n- [Python documentation:`mktemp`](https://docs.python.org/3/library/tempfile.html#tempfile.mktemp)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
75
|
+
"ruff/S307": "## What it does\nChecks for uses of the builtin `eval()` function.\n\n## Why is this bad?\nThe `eval()` function is insecure as it enables arbitrary code execution.\n\nIf you need to evaluate an expression from a string, consider using\n`ast.literal_eval()` instead, which will raise an exception if the\nexpression is not a valid Python literal.\n\nIn [preview], this rule will also flag references to `eval`.\n\n## Example\n```python\nx = eval(input(\"Enter a number: \"))\n```\n\nUse instead:\n```python\nfrom ast import literal_eval\n\nx = literal_eval(input(\"Enter a number: \"))\n```\n\n## References\n- [Python documentation: `eval`](https://docs.python.org/3/library/functions.html#eval)\n- [Python documentation: `literal_eval`](https://docs.python.org/3/library/ast.html#ast.literal_eval)\n- [_Eval really is dangerous_ by Ned Batchelder](https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
76
|
+
"ruff/S308": "## What it does\nChecks for uses of calls to `django.utils.safestring.mark_safe`.\n\n## Why is this bad?\nCross-site scripting (XSS) vulnerabilities allow attackers to execute\narbitrary JavaScript. To guard against XSS attacks, Django templates\nassumes that data is unsafe and automatically escapes malicious strings\nbefore rending them.\n\n`django.utils.safestring.mark_safe` marks a string as safe for use in HTML\ntemplates, bypassing XSS protection. Its usage can be dangerous if the\ncontents of the string are dynamically generated, because it may allow\ncross-site scripting attacks if the string is not properly escaped.\n\nFor dynamically generated strings, consider utilizing\n`django.utils.html.format_html`.\n\nIn [preview], this rule will also flag references to `django.utils.safestring.mark_safe`.\n\n## Example\n```python\nfrom django.utils.safestring import mark_safe\n\n\ndef render_username(username):\n return mark_safe(f\"<i>{username}</i>\") # Dangerous if username is user-provided.\n```\n\nUse instead:\n```python\nfrom django.utils.html import format_html\n\n\ndef render_username(username):\n return format_html(\"<i>{}</i>\", username) # username is escaped.\n```\n\n## References\n- [Django documentation: `mark_safe`](https://docs.djangoproject.com/en/dev/ref/utils/#django.utils.safestring.mark_safe)\n- [Django documentation: Cross Site Scripting (XSS) protection](https://docs.djangoproject.com/en/dev/topics/security/#cross-site-scripting-xss-protection)\n- [Common Weakness Enumeration: CWE-80](https://cwe.mitre.org/data/definitions/80.html)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
77
|
+
"ruff/S310": "## What it does\nChecks for instances where URL open functions are used with unexpected schemes.\n\n## Why is this bad?\nSome URL open functions allow the use of `file:` or custom schemes (for use\ninstead of `http:` or `https:`). An attacker may be able to use these\nschemes to access or modify unauthorized resources, and cause unexpected\nbehavior.\n\nTo mitigate this risk, audit all uses of URL open functions and ensure that\nonly permitted schemes are used (e.g., allowing `http:` and `https:`, and\ndisallowing `file:` and `ftp:`).\n\nIn [preview], this rule will also flag references to URL open functions.\n\n## Example\n```python\nfrom urllib.request import urlopen\n\nurl = input(\"Enter a URL: \")\n\nwith urlopen(url) as response:\n ...\n```\n\nUse instead:\n```python\nfrom urllib.request import urlopen\n\nurl = input(\"Enter a URL: \")\n\nif not url.startswith((\"http:\", \"https:\")):\n raise ValueError(\"URL must start with 'http:' or 'https:'\")\n\nwith urlopen(url) as response:\n ...\n```\n\n## References\n- [Python documentation: `urlopen`](https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
78
|
+
"ruff/S311": "## What it does\nChecks for uses of cryptographically weak pseudo-random number generators.\n\n## Why is this bad?\nCryptographically weak pseudo-random number generators are insecure, as they\nare easily predictable. This can allow an attacker to guess the generated\nnumbers and compromise the security of the system.\n\nInstead, use a cryptographically secure pseudo-random number generator\n(such as using the [`secrets` module](https://docs.python.org/3/library/secrets.html))\nwhen generating random numbers for security purposes.\n\nIn [preview], this rule will also flag references to these generators.\n\n## Example\n```python\nimport random\n\nrandom.randrange(10)\n```\n\nUse instead:\n```python\nimport secrets\n\nsecrets.randbelow(10)\n```\n\n## References\n- [Python documentation: `random` \u2014 Generate pseudo-random numbers](https://docs.python.org/3/library/random.html)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
79
|
+
"ruff/S312": "## What it does\nChecks for the use of Telnet-related functions.\n\n## Why is this bad?\nTelnet is considered insecure because it does not encrypt data sent over\nthe connection and is vulnerable to numerous attacks.\n\nInstead, consider using a more secure protocol such as SSH.\n\nIn [preview], this rule will also flag references to Telnet-related functions.\n\n## References\n- [Python documentation: `telnetlib` \u2014 Telnet client](https://docs.python.org/3/library/telnetlib.html)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
80
|
+
"ruff/S313": "## What it does\nChecks for uses of insecure XML parsers.\n\n## Why is this bad?\nMany XML parsers are vulnerable to XML attacks (such as entity expansion),\nwhich cause excessive memory and CPU usage by exploiting recursion. An\nattacker could use such methods to access unauthorized resources.\n\nConsider using the `defusedxml` package when parsing untrusted XML data,\nto protect against XML attacks.\n\nIn [preview], this rule will also flag references to insecure XML parsers.\n\n## Example\n```python\nfrom xml.etree.cElementTree import parse\n\ntree = parse(\"untrusted.xml\") # Vulnerable to XML attacks.\n```\n\nUse instead:\n```python\nfrom defusedxml.cElementTree import parse\n\ntree = parse(\"untrusted.xml\")\n```\n\n## References\n- [Python documentation: `xml` \u2014 XML processing modules](https://docs.python.org/3/library/xml.html)\n- [PyPI: `defusedxml`](https://pypi.org/project/defusedxml/)\n- [Common Weakness Enumeration: CWE-400](https://cwe.mitre.org/data/definitions/400.html)\n- [Common Weakness Enumeration: CWE-776](https://cwe.mitre.org/data/definitions/776.html)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
81
|
+
"ruff/S314": "## What it does\nChecks for uses of insecure XML parsers.\n\n## Why is this bad?\nMany XML parsers are vulnerable to XML attacks (such as entity expansion),\nwhich cause excessive memory and CPU usage by exploiting recursion. An\nattacker could use such methods to access unauthorized resources.\n\nConsider using the `defusedxml` package when parsing untrusted XML data,\nto protect against XML attacks.\n\nIn [preview], this rule will also flag references to insecure XML parsers.\n\n## Example\n```python\nfrom xml.etree.ElementTree import parse\n\ntree = parse(\"untrusted.xml\") # Vulnerable to XML attacks.\n```\n\nUse instead:\n```python\nfrom defusedxml.ElementTree import parse\n\ntree = parse(\"untrusted.xml\")\n```\n\n## References\n- [Python documentation: `xml` \u2014 XML processing modules](https://docs.python.org/3/library/xml.html)\n- [PyPI: `defusedxml`](https://pypi.org/project/defusedxml/)\n- [Common Weakness Enumeration: CWE-400](https://cwe.mitre.org/data/definitions/400.html)\n- [Common Weakness Enumeration: CWE-776](https://cwe.mitre.org/data/definitions/776.html)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
82
|
+
"ruff/S315": "## What it does\nChecks for uses of insecure XML parsers.\n\n## Why is this bad?\nMany XML parsers are vulnerable to XML attacks (such as entity expansion),\nwhich cause excessive memory and CPU usage by exploiting recursion. An\nattacker could use such methods to access unauthorized resources.\n\nConsider using the `defusedxml` package when parsing untrusted XML data,\nto protect against XML attacks.\n\nIn [preview], this rule will also flag references to insecure XML parsers.\n\n## Example\n```python\nfrom xml.sax.expatreader import create_parser\n\nparser = create_parser()\n```\n\nUse instead:\n```python\nfrom defusedxml.sax import create_parser\n\nparser = create_parser()\n```\n\n## References\n- [Python documentation: `xml` \u2014 XML processing modules](https://docs.python.org/3/library/xml.html)\n- [PyPI: `defusedxml`](https://pypi.org/project/defusedxml/)\n- [Common Weakness Enumeration: CWE-400](https://cwe.mitre.org/data/definitions/400.html)\n- [Common Weakness Enumeration: CWE-776](https://cwe.mitre.org/data/definitions/776.html)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
83
|
+
"ruff/S316": "## What it does\nChecks for uses of insecure XML parsers.\n\n## Why is this bad?\nMany XML parsers are vulnerable to XML attacks (such as entity expansion),\nwhich cause excessive memory and CPU usage by exploiting recursion. An\nattacker could use such methods to access unauthorized resources.\n\nConsider using the `defusedxml` package when parsing untrusted XML data,\nto protect against XML attacks.\n\nIn [preview], this rule will also flag references to insecure XML parsers.\n\n## Example\n```python\nfrom xml.dom.expatbuilder import parse\n\nparse(\"untrusted.xml\")\n```\n\nUse instead:\n```python\nfrom defusedxml.expatbuilder import parse\n\ntree = parse(\"untrusted.xml\")\n```\n\n## References\n- [Python documentation: `xml` \u2014 XML processing modules](https://docs.python.org/3/library/xml.html)\n- [PyPI: `defusedxml`](https://pypi.org/project/defusedxml/)\n- [Common Weakness Enumeration: CWE-400](https://cwe.mitre.org/data/definitions/400.html)\n- [Common Weakness Enumeration: CWE-776](https://cwe.mitre.org/data/definitions/776.html)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
84
|
+
"ruff/S317": "## What it does\nChecks for uses of insecure XML parsers.\n\n## Why is this bad?\nMany XML parsers are vulnerable to XML attacks (such as entity expansion),\nwhich cause excessive memory and CPU usage by exploiting recursion. An\nattacker could use such methods to access unauthorized resources.\n\nConsider using the `defusedxml` package when parsing untrusted XML data,\nto protect against XML attacks.\n\nIn [preview], this rule will also flag references to insecure XML parsers.\n\n## Example\n```python\nfrom xml.sax import make_parser\n\nmake_parser()\n```\n\nUse instead:\n```python\nfrom defusedxml.sax import make_parser\n\nmake_parser()\n```\n\n## References\n- [Python documentation: `xml` \u2014 XML processing modules](https://docs.python.org/3/library/xml.html)\n- [PyPI: `defusedxml`](https://pypi.org/project/defusedxml/)\n- [Common Weakness Enumeration: CWE-400](https://cwe.mitre.org/data/definitions/400.html)\n- [Common Weakness Enumeration: CWE-776](https://cwe.mitre.org/data/definitions/776.html)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
85
|
+
"ruff/S318": "## What it does\nChecks for uses of insecure XML parsers.\n\n## Why is this bad?\nMany XML parsers are vulnerable to XML attacks (such as entity expansion),\nwhich cause excessive memory and CPU usage by exploiting recursion. An\nattacker could use such methods to access unauthorized resources.\n\nConsider using the `defusedxml` package when parsing untrusted XML data,\nto protect against XML attacks.\n\nIn [preview], this rule will also flag references to insecure XML parsers.\n\n## Example\n```python\nfrom xml.dom.minidom import parse\n\ncontent = parse(\"untrusted.xml\")\n```\n\nUse instead:\n```python\nfrom defusedxml.minidom import parse\n\ncontent = parse(\"untrusted.xml\")\n```\n\n## References\n- [Python documentation: `xml` \u2014 XML processing modules](https://docs.python.org/3/library/xml.html)\n- [PyPI: `defusedxml`](https://pypi.org/project/defusedxml/)\n- [Common Weakness Enumeration: CWE-400](https://cwe.mitre.org/data/definitions/400.html)\n- [Common Weakness Enumeration: CWE-776](https://cwe.mitre.org/data/definitions/776.html)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
86
|
+
"ruff/S319": "## What it does\nChecks for uses of insecure XML parsers.\n\n## Why is this bad?\nMany XML parsers are vulnerable to XML attacks (such as entity expansion),\nwhich cause excessive memory and CPU usage by exploiting recursion. An\nattacker could use such methods to access unauthorized resources.\n\nConsider using the `defusedxml` package when parsing untrusted XML data,\nto protect against XML attacks.\n\nIn [preview], this rule will also flag references to insecure XML parsers.\n\n## Example\n```python\nfrom xml.dom.pulldom import parse\n\ncontent = parse(\"untrusted.xml\")\n```\n\nUse instead:\n```python\nfrom defusedxml.pulldom import parse\n\ncontent = parse(\"untrusted.xml\")\n```\n\n## References\n- [Python documentation: `xml` \u2014 XML processing modules](https://docs.python.org/3/library/xml.html)\n- [PyPI: `defusedxml`](https://pypi.org/project/defusedxml/)\n- [Common Weakness Enumeration: CWE-400](https://cwe.mitre.org/data/definitions/400.html)\n- [Common Weakness Enumeration: CWE-776](https://cwe.mitre.org/data/definitions/776.html)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
87
|
+
"ruff/S320": "## Removed\n\nThis rule was removed as the `lxml` library has been modified to address\nknown vulnerabilities and unsafe defaults. As such, the `defusedxml`\nlibrary is no longer necessary, `defusedxml` has [deprecated] its `lxml`\nmodule.\n\n## What it does\nChecks for uses of insecure XML parsers.\n\n## Why is this bad?\nMany XML parsers are vulnerable to XML attacks (such as entity expansion),\nwhich cause excessive memory and CPU usage by exploiting recursion. An\nattacker could use such methods to access unauthorized resources.\n\nIn [preview], this rule will also flag references to insecure XML parsers.\n\n## Example\n```python\nfrom lxml import etree\n\ncontent = etree.parse(\"untrusted.xml\")\n```\n\n## References\n- [PyPI: `lxml`](https://pypi.org/project/lxml/)\n- [Common Weakness Enumeration: CWE-400](https://cwe.mitre.org/data/definitions/400.html)\n- [Common Weakness Enumeration: CWE-776](https://cwe.mitre.org/data/definitions/776.html)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n[deprecated]: https://pypi.org/project/defusedxml/0.8.0rc2/#defusedxml-lxml\n",
|
|
88
|
+
"ruff/S321": "## What it does\nChecks for the use of FTP-related functions.\n\n## Why is this bad?\nFTP is considered insecure as it does not encrypt data sent over the\nconnection and is thus vulnerable to numerous attacks.\n\nInstead, consider using FTPS (which secures FTP using SSL/TLS) or SFTP.\n\nIn [preview], this rule will also flag references to FTP-related functions.\n\n## References\n- [Python documentation: `ftplib` \u2014 FTP protocol client](https://docs.python.org/3/library/ftplib.html)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
89
|
+
"ruff/S323": "## What it does\nChecks for uses of `ssl._create_unverified_context`.\n\n## Why is this bad?\n[PEP 476] enabled certificate and hostname validation by default in Python\nstandard library HTTP clients. Previously, Python did not validate\ncertificates by default, which could allow an attacker to perform a \"man in\nthe middle\" attack by intercepting and modifying traffic between client and\nserver.\n\nTo support legacy environments, `ssl._create_unverified_context` reverts to\nthe previous behavior that does perform verification. Otherwise, use\n`ssl.create_default_context` to create a secure context.\n\nIn [preview], this rule will also flag references to `ssl._create_unverified_context`.\n\n## Example\n```python\nimport ssl\n\ncontext = ssl._create_unverified_context()\n```\n\nUse instead:\n```python\nimport ssl\n\ncontext = ssl.create_default_context()\n```\n\n## References\n- [PEP 476 \u2013 Enabling certificate verification by default for stdlib http clients: Opting out](https://peps.python.org/pep-0476/#opting-out)\n- [Python documentation: `ssl` \u2014 TLS/SSL wrapper for socket objects](https://docs.python.org/3/library/ssl.html)\n\n[PEP 476]: https://peps.python.org/pep-0476/\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
90
|
+
"ruff/S324": "## What it does\nChecks for uses of weak or broken cryptographic hash functions in\n`hashlib` and `crypt` libraries.\n\n## Why is this bad?\nWeak or broken cryptographic hash functions may be susceptible to\ncollision attacks (where two different inputs produce the same hash) or\npre-image attacks (where an attacker can find an input that produces a\ngiven hash). This can lead to security vulnerabilities in applications\nthat rely on these hash functions.\n\nAvoid using weak or broken cryptographic hash functions in security\ncontexts. Instead, use a known secure hash function such as SHA256.\n\nNote: This rule targets the following weak algorithm names in `hashlib`:\n`md4`, `md5`, `sha`, and `sha1`. It also flags uses of `crypt.crypt` and\n`crypt.mksalt` when configured with `METHOD_CRYPT`, `METHOD_MD5`, or\n`METHOD_BLOWFISH`.\n\nIt does not attempt to lint OpenSSL- or platform-specific aliases and OIDs\n(for example: `\"sha-1\"`, `\"ssl3-sha1\"`, `\"ssl3-md5\"`, or\n`\"1.3.14.3.2.26\"`), nor variations with trailing spaces, as the set of\naccepted aliases depends on the underlying OpenSSL version and varies across\nplatforms and Python builds.\n\n## Example\n```python\nimport hashlib\n\n\ndef certificate_is_valid(certificate: bytes, known_hash: str) -> bool:\n hash = hashlib.md5(certificate).hexdigest()\n return hash == known_hash\n```\n\nUse instead:\n```python\nimport hashlib\n\n\ndef certificate_is_valid(certificate: bytes, known_hash: str) -> bool:\n hash = hashlib.sha256(certificate).hexdigest()\n return hash == known_hash\n```\n\nor add `usedforsecurity=False` if the hashing algorithm is not used in a security context, e.g.\nas a non-cryptographic one-way compression function:\n```python\nimport hashlib\n\n\ndef certificate_is_valid(certificate: bytes, known_hash: str) -> bool:\n hash = hashlib.md5(certificate, usedforsecurity=False).hexdigest()\n return hash == known_hash\n```\n\n\n## References\n- [Python documentation: `hashlib` \u2014 Secure hashes and message digests](https://docs.python.org/3/library/hashlib.html)\n- [Python documentation: `crypt` \u2014 Function to check Unix passwords](https://docs.python.org/3/library/crypt.html)\n- [Python documentation: `FIPS` - FIPS compliant hashlib implementation](https://docs.python.org/3/library/hashlib.html#hashlib.algorithms_guaranteed)\n- [Common Weakness Enumeration: CWE-327](https://cwe.mitre.org/data/definitions/327.html)\n- [Common Weakness Enumeration: CWE-328](https://cwe.mitre.org/data/definitions/328.html)\n- [Common Weakness Enumeration: CWE-916](https://cwe.mitre.org/data/definitions/916.html)\n",
|
|
91
|
+
"ruff/S401": "## What it does\nChecks for imports of the `telnetlib` module.\n\n## Why is this bad?\nTelnet is considered insecure. It is deprecated since version 3.11, and\nwas removed in version 3.13. Instead, use SSH or another encrypted\nprotocol.\n\n## Example\n```python\nimport telnetlib\n```\n\n## References\n- [Python documentation: `telnetlib` - Telnet client](https://docs.python.org/3.12/library/telnetlib.html#module-telnetlib)\n- [PEP 594: `telnetlib`](https://peps.python.org/pep-0594/#telnetlib)\n",
|
|
92
|
+
"ruff/S402": "## What it does\nChecks for imports of the `ftplib` module.\n\n## Why is this bad?\nFTP is considered insecure. Instead, use SSH, SFTP, SCP, or another\nencrypted protocol.\n\n## Example\n```python\nimport ftplib\n```\n\n## References\n- [Python documentation: `ftplib` - FTP protocol client](https://docs.python.org/3/library/ftplib.html)\n",
|
|
93
|
+
"ruff/S403": "## What it does\nChecks for imports of the `pickle`, `cPickle`, `dill`, and `shelve` modules.\n\n## Why is this bad?\nIt is possible to construct malicious pickle data which will execute\narbitrary code during unpickling. Consider possible security implications\nassociated with these modules.\n\n## Example\n```python\nimport pickle\n```\n\n## References\n- [Python documentation: `pickle` \u2014 Python object serialization](https://docs.python.org/3/library/pickle.html)\n",
|
|
94
|
+
"ruff/S404": "## What it does\nChecks for imports of the `subprocess` module.\n\n## Why is this bad?\nIt is possible to inject malicious commands into subprocess calls. Consider\npossible security implications associated with this module.\n\n## Example\n```python\nimport subprocess\n```\n",
|
|
95
|
+
"ruff/S405": "## What it does\nChecks for imports of the `xml.etree.cElementTree` and `xml.etree.ElementTree` modules\n\n## Why is this bad?\nUsing various methods from these modules to parse untrusted XML data is\nknown to be vulnerable to XML attacks. Replace vulnerable imports with the\nequivalent `defusedxml` package, or make sure `defusedxml.defuse_stdlib()` is\ncalled before parsing XML data.\n\n## Example\n```python\nimport xml.etree.cElementTree\n```\n",
|
|
96
|
+
"ruff/S406": "## What it does\nChecks for imports of the `xml.sax` module.\n\n## Why is this bad?\nUsing various methods from these modules to parse untrusted XML data is\nknown to be vulnerable to XML attacks. Replace vulnerable imports with the\nequivalent `defusedxml` package, or make sure `defusedxml.defuse_stdlib()` is\ncalled before parsing XML data.\n\n## Example\n```python\nimport xml.sax\n```\n",
|
|
97
|
+
"ruff/S407": "## What it does\nChecks for imports of the `xml.dom.expatbuilder` module.\n\n## Why is this bad?\nUsing various methods from these modules to parse untrusted XML data is\nknown to be vulnerable to XML attacks. Replace vulnerable imports with the\nequivalent `defusedxml` package, or make sure `defusedxml.defuse_stdlib()` is\ncalled before parsing XML data.\n\n## Example\n```python\nimport xml.dom.expatbuilder\n```\n",
|
|
98
|
+
"ruff/S408": "## What it does\nChecks for imports of the `xml.dom.minidom` module.\n\n## Why is this bad?\nUsing various methods from these modules to parse untrusted XML data is\nknown to be vulnerable to XML attacks. Replace vulnerable imports with the\nequivalent `defusedxml` package, or make sure `defusedxml.defuse_stdlib()` is\ncalled before parsing XML data.\n\n## Example\n```python\nimport xml.dom.minidom\n```\n",
|
|
99
|
+
"ruff/S409": "## What it does\nChecks for imports of the `xml.dom.pulldom` module.\n\n## Why is this bad?\nUsing various methods from these modules to parse untrusted XML data is\nknown to be vulnerable to XML attacks. Replace vulnerable imports with the\nequivalent `defusedxml` package, or make sure `defusedxml.defuse_stdlib()` is\ncalled before parsing XML data.\n\n## Example\n```python\nimport xml.dom.pulldom\n```\n",
|
|
100
|
+
"ruff/S410": "## Removed\nThis rule was removed as the `lxml` library has been modified to address\nknown vulnerabilities and unsafe defaults. As such, the `defusedxml`\nlibrary is no longer necessary, `defusedxml` has [deprecated] its `lxml`\nmodule.\n\n## What it does\nChecks for imports of the `lxml` module.\n\n## Why is this bad?\nUsing various methods from the `lxml` module to parse untrusted XML data is\nknown to be vulnerable to XML attacks. Replace vulnerable imports with the\nequivalent `defusedxml` package.\n\n## Example\n```python\nimport lxml\n```\n\n[deprecated]: https://github.com/tiran/defusedxml/blob/c7445887f5e1bcea470a16f61369d29870cfcfe1/README.md#defusedxmllxml\n",
|
|
101
|
+
"ruff/S411": "## What it does\nChecks for imports of the `xmlrpc` module.\n\n## Why is this bad?\nXMLRPC is a particularly dangerous XML module, as it is also concerned with\ncommunicating data over a network. Use the `defused.xmlrpc.monkey_patch()`\nfunction to monkey-patch the `xmlrpclib` module and mitigate remote XML\nattacks.\n\n## Example\n```python\nimport xmlrpc\n```\n",
|
|
102
|
+
"ruff/S412": "## What it does\nChecks for imports of `wsgiref.handlers.CGIHandler` and\n`twisted.web.twcgi.CGIScript`.\n\n## Why is this bad?\nhttpoxy is a set of vulnerabilities that affect application code running in\nCGI or CGI-like environments. The use of CGI for web applications should be\navoided to prevent this class of attack.\n\n## Example\n```python\nfrom wsgiref.handlers import CGIHandler\n```\n\n## References\n- [httpoxy website](https://httpoxy.org/)\n",
|
|
103
|
+
"ruff/S413": "## What it does\nChecks for imports of several unsafe cryptography modules.\n\n## Why is this bad?\nThe `pycrypto` library is known to have a publicly disclosed buffer\noverflow vulnerability. It is no longer actively maintained and has been\ndeprecated in favor of the `pyca/cryptography` library.\n\n## Example\n```python\nimport Crypto.Random\n```\n\n## References\n- [Buffer Overflow Issue](https://github.com/pycrypto/pycrypto/issues/176)\n",
|
|
104
|
+
"ruff/S415": "## What it does\nChecks for imports of the `pyghmi` module.\n\n## Why is this bad?\n`pyghmi` is an IPMI-related module, but IPMI is considered insecure.\nInstead, use an encrypted protocol.\n\n## Example\n```python\nimport pyghmi\n```\n\n## References\n- [Buffer Overflow Issue](https://github.com/pycrypto/pycrypto/issues/176)\n",
|
|
105
|
+
"ruff/S501": "## What it does\nChecks for HTTPS requests that disable SSL certificate checks.\n\n## Why is this bad?\nIf SSL certificates are not verified, an attacker could perform a \"man in\nthe middle\" attack by intercepting and modifying traffic between the client\nand server.\n\n## Example\n```python\nimport requests\n\nrequests.get(\"https://www.example.com\", verify=False)\n```\n\nUse instead:\n```python\nimport requests\n\nrequests.get(\"https://www.example.com\") # By default, `verify=True`.\n```\n\n## References\n- [Common Weakness Enumeration: CWE-295](https://cwe.mitre.org/data/definitions/295.html)\n",
|
|
106
|
+
"ruff/S502": "## What it does\nChecks for function calls with parameters that indicate the use of insecure\nSSL and TLS protocol versions.\n\n## Why is this bad?\nSeveral highly publicized exploitable flaws have been discovered in all\nversions of SSL and early versions of TLS. The following versions are\nconsidered insecure, and should be avoided:\n- SSL v2\n- SSL v3\n- TLS v1\n- TLS v1.1\n\nThis method supports detection on the Python's built-in `ssl` module and\nthe `pyOpenSSL` module.\n\n## Example\n```python\nimport ssl\n\nssl.wrap_socket(ssl_version=ssl.PROTOCOL_TLSv1)\n```\n\nUse instead:\n```python\nimport ssl\n\nssl.wrap_socket(ssl_version=ssl.PROTOCOL_TLSv1_2)\n```\n",
|
|
107
|
+
"ruff/S503": "## What it does\nChecks for function definitions with default arguments set to insecure SSL\nand TLS protocol versions.\n\n## Why is this bad?\nSeveral highly publicized exploitable flaws have been discovered in all\nversions of SSL and early versions of TLS. The following versions are\nconsidered insecure, and should be avoided:\n- SSL v2\n- SSL v3\n- TLS v1\n- TLS v1.1\n\n## Example\n\n```python\nimport ssl\n\n\ndef func(version=ssl.PROTOCOL_TLSv1): ...\n```\n\nUse instead:\n\n```python\nimport ssl\n\n\ndef func(version=ssl.PROTOCOL_TLSv1_2): ...\n```\n",
|
|
108
|
+
"ruff/S504": "## What it does\nChecks for calls to `ssl.wrap_socket()` without an `ssl_version`.\n\n## Why is this bad?\nThis method is known to provide a default value that maximizes\ncompatibility, but permits use of insecure protocols.\n\n## Example\n```python\nimport ssl\n\nssl.wrap_socket()\n```\n\nUse instead:\n```python\nimport ssl\n\nssl.wrap_socket(ssl_version=ssl.PROTOCOL_TLSv1_2)\n```\n",
|
|
109
|
+
"ruff/S505": "## What it does\nChecks for uses of cryptographic keys with vulnerable key sizes.\n\n## Why is this bad?\nSmall keys are easily breakable. For DSA and RSA, keys should be at least\n2048 bits long. For EC, keys should be at least 224 bits long.\n\n## Example\n```python\nfrom cryptography.hazmat.primitives.asymmetric import dsa, ec\n\ndsa.generate_private_key(key_size=512)\nec.generate_private_key(curve=ec.SECT163K1())\n```\n\nUse instead:\n```python\nfrom cryptography.hazmat.primitives.asymmetric import dsa, ec\n\ndsa.generate_private_key(key_size=4096)\nec.generate_private_key(curve=ec.SECP384R1())\n```\n\n## References\n- [CSRC: Transitioning the Use of Cryptographic Algorithms and Key Lengths](https://csrc.nist.gov/pubs/sp/800/131/a/r2/final)\n",
|
|
110
|
+
"ruff/S506": "## What it does\nChecks for uses of the `yaml.load` function.\n\n## Why is this bad?\nRunning the `yaml.load` function over untrusted YAML files is insecure, as\n`yaml.load` allows for the creation of arbitrary Python objects, which can\nthen be used to execute arbitrary code.\n\nInstead, consider using `yaml.safe_load`, which allows for the creation of\nsimple Python objects like integers and lists, but prohibits the creation of\nmore complex objects like functions and classes.\n\n## Example\n```python\nimport yaml\n\nyaml.load(untrusted_yaml)\n```\n\nUse instead:\n```python\nimport yaml\n\nyaml.safe_load(untrusted_yaml)\n```\n\n## References\n- [PyYAML documentation: Loading YAML](https://pyyaml.org/wiki/PyYAMLDocumentation)\n- [Common Weakness Enumeration: CWE-20](https://cwe.mitre.org/data/definitions/20.html)\n",
|
|
111
|
+
"ruff/S507": "## What it does\nChecks for uses of policies disabling SSH verification in Paramiko.\n\n## Why is this bad?\nBy default, Paramiko checks the identity of the remote host when establishing\nan SSH connection. Disabling the verification might lead to the client\nconnecting to a malicious host, without the client knowing.\n\n## Example\n```python\nfrom paramiko import client\n\nssh_client = client.SSHClient()\nssh_client.set_missing_host_key_policy(client.AutoAddPolicy)\n```\n\nUse instead:\n```python\nfrom paramiko import client\n\nssh_client = client.SSHClient()\nssh_client.set_missing_host_key_policy(client.RejectPolicy)\n```\n\n## References\n- [Paramiko documentation: set_missing_host_key_policy](https://docs.paramiko.org/en/latest/api/client.html#paramiko.client.SSHClient.set_missing_host_key_policy)\n",
|
|
112
|
+
"ruff/S508": "## What it does\nChecks for uses of SNMPv1 or SNMPv2.\n\n## Why is this bad?\nThe SNMPv1 and SNMPv2 protocols are considered insecure as they do\nnot support encryption. Instead, prefer SNMPv3, which supports\nencryption.\n\n## Example\n```python\nfrom pysnmp.hlapi import CommunityData\n\nCommunityData(\"public\", mpModel=0)\n```\n\nUse instead:\n```python\nfrom pysnmp.hlapi import CommunityData\n\nCommunityData(\"public\", mpModel=2)\n```\n\n## References\n- [Cybersecurity and Infrastructure Security Agency (CISA): Alert TA17-156A](https://www.cisa.gov/news-events/alerts/2017/06/05/reducing-risk-snmp-abuse)\n- [Common Weakness Enumeration: CWE-319](https://cwe.mitre.org/data/definitions/319.html)\n",
|
|
113
|
+
"ruff/S509": "## What it does\nChecks for uses of the SNMPv3 protocol without encryption.\n\n## Why is this bad?\nUnencrypted SNMPv3 communication can be intercepted and read by\nunauthorized parties. Instead, enable encryption when using SNMPv3.\n\n## Example\n```python\nfrom pysnmp.hlapi import UsmUserData\n\nUsmUserData(\"user\")\n```\n\nUse instead:\n```python\nfrom pysnmp.hlapi import UsmUserData\n\nUsmUserData(\"user\", \"authkey\", \"privkey\")\n```\n\n## References\n- [Common Weakness Enumeration: CWE-319](https://cwe.mitre.org/data/definitions/319.html)\n",
|
|
114
|
+
"ruff/S601": "## What it does\nChecks for `paramiko` calls.\n\n## Why is this bad?\n`paramiko` calls allow users to execute arbitrary shell commands on a\nremote machine. If the inputs to these calls are not properly sanitized,\nthey can be vulnerable to shell injection attacks.\n\n## Example\n```python\nimport paramiko\n\nclient = paramiko.SSHClient()\nclient.exec_command(\"echo $HOME\")\n```\n\n## References\n- [Common Weakness Enumeration: CWE-78](https://cwe.mitre.org/data/definitions/78.html)\n- [Paramiko documentation: `SSHClient.exec_command()`](https://docs.paramiko.org/en/stable/api/client.html#paramiko.client.SSHClient.exec_command)\n",
|
|
115
|
+
"ruff/S602": "## What it does\nCheck for method calls that initiate a subprocess with a shell.\n\n## Why is this bad?\nStarting a subprocess with a shell can allow attackers to execute arbitrary\nshell commands. Consider starting the process without a shell call and\nsanitize the input to mitigate the risk of shell injection.\n\n## Example\n```python\nimport subprocess\n\nsubprocess.run(\"ls -l\", shell=True)\n```\n\nUse instead:\n```python\nimport subprocess\n\nsubprocess.run([\"ls\", \"-l\"])\n```\n\n## References\n- [Python documentation: `subprocess` \u2014 Subprocess management](https://docs.python.org/3/library/subprocess.html)\n- [Common Weakness Enumeration: CWE-78](https://cwe.mitre.org/data/definitions/78.html)\n",
|
|
116
|
+
"ruff/S603": "## What it does\nCheck for method calls that initiate a subprocess without a shell.\n\n## Why is this bad?\nStarting a subprocess without a shell can prevent attackers from executing\narbitrary shell commands; however, it is still error-prone. Consider\nvalidating the input.\n\n## Known problems\nProne to false positives as it is difficult to determine whether the\npassed arguments have been validated ([#4045]).\n\n## Example\n```python\nimport subprocess\n\ncmd = input(\"Enter a command: \").split()\nsubprocess.run(cmd)\n```\n\n## References\n- [Python documentation: `subprocess` \u2014 Subprocess management](https://docs.python.org/3/library/subprocess.html)\n\n[#4045]: https://github.com/astral-sh/ruff/issues/4045\n",
|
|
117
|
+
"ruff/S604": "## What it does\nChecks for method calls that set the `shell` parameter to `true` or another\ntruthy value when invoking a subprocess.\n\n## Why is this bad?\nSetting the `shell` parameter to `true` or another truthy value when\ninvoking a subprocess can introduce security vulnerabilities, as it allows\nshell metacharacters and whitespace to be passed to child processes,\npotentially leading to shell injection attacks.\n\nIt is recommended to avoid using `shell=True` unless absolutely necessary\nand, when used, to ensure that all inputs are properly sanitized and quoted\nto prevent such vulnerabilities.\n\n## Known problems\nProne to false positives as it is triggered on any function call with a\n`shell=True` parameter.\n\n## Example\n```python\nimport my_custom_subprocess\n\nuser_input = input(\"Enter a command: \")\nmy_custom_subprocess.run(user_input, shell=True)\n```\n\n## References\n- [Python documentation: Security Considerations](https://docs.python.org/3/library/subprocess.html#security-considerations)\n",
|
|
118
|
+
"ruff/S605": "## What it does\nChecks for calls that start a process with a shell, providing guidance on\nwhether the usage is safe or not.\n\n## Why is this bad?\nStarting a process with a shell can introduce security risks, such as\ncode injection vulnerabilities. It's important to be aware of whether the\nusage of the shell is safe or not.\n\nThis rule triggers on functions like `os.system`, `popen`, etc., which\nstart processes with a shell. It evaluates whether the provided command\nis a literal string or an expression. If the command is a literal string,\nit's considered safe. If the command is an expression, it's considered\n(potentially) unsafe.\n\n## Example\n```python\nimport os\n\n# Safe usage (literal string)\ncommand = \"ls -l\"\nos.system(command)\n\n# Potentially unsafe usage (expression)\ncmd = get_user_input()\nos.system(cmd)\n```\n\n## Note\nThe `subprocess` module provides more powerful facilities for spawning new\nprocesses and retrieving their results, and using that module is preferable\nto using `os.system` or similar functions. Consider replacing such usages\nwith `subprocess.call` or related functions.\n\n## References\n- [Python documentation: `subprocess`](https://docs.python.org/3/library/subprocess.html)\n",
|
|
119
|
+
"ruff/S606": "## What it does\nChecks for functions that start a process without a shell.\n\n## Why is this bad?\nInvoking any kind of external executable via a function call can pose\nsecurity risks if arbitrary variables are passed to the executable, or if\nthe input is otherwise unsanitised or unvalidated.\n\nThis rule specifically flags functions in the `os` module that spawn\nsubprocesses *without* the use of a shell. Note that these typically pose a\nmuch smaller security risk than subprocesses that are started *with* a\nshell, which are flagged by [`start-process-with-a-shell`][S605] (`S605`).\nThis gives you the option of enabling one rule while disabling the other\nif you decide that the security risk from these functions is acceptable\nfor your use case.\n\n## Example\n```python\nimport os\n\n\ndef insecure_function(arbitrary_user_input: str):\n os.spawnlp(os.P_NOWAIT, \"/bin/mycmd\", \"mycmd\", arbitrary_user_input)\n```\n\n[S605]: https://docs.astral.sh/ruff/rules/start-process-with-a-shell\n",
|
|
120
|
+
"ruff/S607": "## What it does\nChecks for the starting of a process with a partial executable path.\n\n## Why is this bad?\nStarting a process with a partial executable path can allow attackers to\nexecute an arbitrary executable by adjusting the `PATH` environment variable.\nConsider using a full path to the executable instead.\n\n## Example\n```python\nimport subprocess\n\nsubprocess.Popen([\"ruff\", \"check\", \"file.py\"])\n```\n\nUse instead:\n```python\nimport subprocess\n\nsubprocess.Popen([\"/usr/bin/ruff\", \"check\", \"file.py\"])\n```\n\n## References\n- [Python documentation: `subprocess.Popen()`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen)\n- [Common Weakness Enumeration: CWE-426](https://cwe.mitre.org/data/definitions/426.html)\n",
|
|
121
|
+
"ruff/S608": "## What it does\nChecks for strings that resemble SQL statements involved in some form\nstring building operation.\n\n## Why is this bad?\nSQL injection is a common attack vector for web applications. Directly\ninterpolating user input into SQL statements should always be avoided.\nInstead, favor parameterized queries, in which the SQL statement is\nprovided separately from its parameters, as supported by `psycopg3`\nand other database drivers and ORMs.\n\n## Example\n```python\nquery = \"DELETE FROM foo WHERE id = '%s'\" % identifier\n```\n\n## References\n- [B608: Test for SQL injection](https://bandit.readthedocs.io/en/latest/plugins/b608_hardcoded_sql_expressions.html)\n- [psycopg3: Server-side binding](https://www.psycopg.org/psycopg3/docs/basic/from_pg2.html#server-side-binding)\n",
|
|
122
|
+
"ruff/S609": "## What it does\nChecks for possible wildcard injections in calls to `subprocess.Popen()`.\n\n## Why is this bad?\nWildcard injections can lead to unexpected behavior if unintended files are\nmatched by the wildcard. Consider using a more specific path instead.\n\n## Example\n```python\nimport subprocess\n\nsubprocess.Popen([\"chmod\", \"777\", \"*.py\"], shell=True)\n```\n\nUse instead:\n```python\nimport subprocess\n\nsubprocess.Popen([\"chmod\", \"777\", \"main.py\"], shell=True)\n```\n\n## References\n- [Common Weakness Enumeration: CWE-78](https://cwe.mitre.org/data/definitions/78.html)\n",
|
|
123
|
+
"ruff/S610": "## What it does\nChecks for uses of Django's `extra` function where one or more arguments\npassed are not literal expressions.\n\n## Why is this bad?\nDjango's `extra` function can be used to execute arbitrary SQL queries,\nwhich can in turn lead to SQL injection vulnerabilities.\n\n## Example\n```python\nfrom django.contrib.auth.models import User\n\n# String interpolation creates a security loophole that could be used\n# for SQL injection:\nUser.objects.all().extra(select={\"test\": \"%secure\" % \"nos\"})\n```\n\nUse instead:\n```python\nfrom django.contrib.auth.models import User\n\n# SQL injection is impossible if all arguments are literal expressions:\nUser.objects.all().extra(select={\"test\": \"secure\"})\n```\n\n## References\n- [Django documentation: SQL injection protection](https://docs.djangoproject.com/en/dev/topics/security/#sql-injection-protection)\n- [Common Weakness Enumeration: CWE-89](https://cwe.mitre.org/data/definitions/89.html)\n",
|
|
124
|
+
"ruff/S611": "## What it does\nChecks for uses of Django's `RawSQL` function.\n\n## Why is this bad?\nDjango's `RawSQL` function can be used to execute arbitrary SQL queries,\nwhich can in turn lead to SQL injection vulnerabilities.\n\n## Example\n```python\nfrom django.db.models.expressions import RawSQL\nfrom django.contrib.auth.models import User\n\nUser.objects.annotate(val=RawSQL(\"%s\" % input_param, []))\n```\n\n## References\n- [Django documentation: SQL injection protection](https://docs.djangoproject.com/en/dev/topics/security/#sql-injection-protection)\n- [Common Weakness Enumeration: CWE-89](https://cwe.mitre.org/data/definitions/89.html)\n",
|
|
125
|
+
"ruff/S612": "## What it does\nChecks for insecure `logging.config.listen` calls.\n\n## Why is this bad?\n`logging.config.listen` starts a server that listens for logging\nconfiguration requests. This is insecure, as parts of the configuration are\npassed to the built-in `eval` function, which can be used to execute\narbitrary code.\n\n## Example\n```python\nimport logging\n\nlogging.config.listen(9999)\n```\n\n## References\n- [Python documentation: `logging.config.listen()`](https://docs.python.org/3/library/logging.config.html#logging.config.listen)\n",
|
|
126
|
+
"ruff/S701": "## What it does\nChecks for `jinja2` templates that use `autoescape=False`.\n\n## Why is this bad?\n`jinja2` templates that use `autoescape=False` are vulnerable to cross-site\nscripting (XSS) attacks that allow attackers to execute arbitrary\nJavaScript.\n\nBy default, `jinja2` sets `autoescape` to `False`, so it is important to\nset `autoescape=True` or use the `select_autoescape` function to mitigate\nXSS vulnerabilities.\n\n## Example\n```python\nimport jinja2\n\njinja2.Environment(loader=jinja2.FileSystemLoader(\".\"))\n```\n\nUse instead:\n```python\nimport jinja2\n\njinja2.Environment(loader=jinja2.FileSystemLoader(\".\"), autoescape=True)\n```\n\n## References\n- [Jinja documentation: API](https://jinja.palletsprojects.com/en/latest/api/#autoescaping)\n- [Common Weakness Enumeration: CWE-94](https://cwe.mitre.org/data/definitions/94.html)\n",
|
|
127
|
+
"ruff/S702": "## What it does\nChecks for uses of the `mako` templates.\n\n## Why is this bad?\nMako templates allow HTML and JavaScript rendering by default, and are\ninherently open to XSS attacks. Ensure variables in all templates are\nproperly escaped via the `h` (HTML) or `x` (XML) filters, depending on\ncontext. For example, to HTML escape the variable `data`, use `${ data |h }`.\n\n## Example\n```python\nfrom mako.template import Template\n\nTemplate(\"${ data }\") # Unescaped: vulnerable to XSS.\n```\n\nUse instead:\n```python\nfrom mako.template import Template\n\nTemplate(\"${ data |h }\") # HTML-escaped with the `h` filter.\n```\n\n## References\n- [Mako documentation](https://www.makotemplates.org/)\n- [OpenStack security: Cross site scripting XSS](https://security.openstack.org/guidelines/dg_cross-site-scripting-xss.html)\n- [Common Weakness Enumeration: CWE-80](https://cwe.mitre.org/data/definitions/80.html)\n",
|
|
128
|
+
"ruff/S704": "## What it does\nChecks for non-literal strings being passed to [`markupsafe.Markup`][markupsafe-markup].\n\n## Why is this bad?\n[`markupsafe.Markup`][markupsafe-markup] does not perform any escaping, so passing dynamic\ncontent, like f-strings, variables or interpolated strings will potentially\nlead to XSS vulnerabilities.\n\nInstead you should interpolate the `Markup` object.\n\nUsing [`lint.flake8-bandit.extend-markup-names`] additional objects can be\ntreated like `Markup`.\n\nThis rule was originally inspired by [flake8-markupsafe] but doesn't carve\nout any exceptions for i18n related calls by default.\n\nYou can use [`lint.flake8-bandit.allowed-markup-calls`] to specify exceptions.\n\n## Example\nGiven:\n```python\nfrom markupsafe import Markup\n\ncontent = \"<script>alert('Hello, world!')</script>\"\nhtml = Markup(f\"<b>{content}</b>\") # XSS\n```\n\nUse instead:\n```python\nfrom markupsafe import Markup\n\ncontent = \"<script>alert('Hello, world!')</script>\"\nhtml = Markup(\"<b>{}</b>\").format(content) # Safe\n```\n\nGiven:\n```python\nfrom markupsafe import Markup\n\nlines = [\n Markup(\"<b>heading</b>\"),\n \"<script>alert('XSS attempt')</script>\",\n]\nhtml = Markup(\"<br>\".join(lines)) # XSS\n```\n\nUse instead:\n```python\nfrom markupsafe import Markup\n\nlines = [\n Markup(\"<b>heading</b>\"),\n \"<script>alert('XSS attempt')</script>\",\n]\nhtml = Markup(\"<br>\").join(lines) # Safe\n```\n## Options\n- `lint.flake8-bandit.extend-markup-names`\n- `lint.flake8-bandit.allowed-markup-calls`\n\n## References\n- [MarkupSafe on PyPI](https://pypi.org/project/MarkupSafe/)\n- [`markupsafe.Markup` API documentation](https://markupsafe.palletsprojects.com/en/stable/escaping/#markupsafe.Markup)\n\n[markupsafe-markup]: https://markupsafe.palletsprojects.com/en/stable/escaping/#markupsafe.Markup\n[flake8-markupsafe]: https://github.com/vmagamedov/flake8-markupsafe\n",
|
|
129
|
+
"ruff/BLE001": "## What it does\nChecks for `except` clauses that catch all exceptions. This includes\n`except BaseException` and `except Exception`.\n\n\n## Why is this bad?\nOverly broad `except` clauses can lead to unexpected behavior, such as\ncatching `KeyboardInterrupt` or `SystemExit` exceptions that prevent the\nuser from exiting the program.\n\nInstead of catching all exceptions, catch only those that are expected to\nbe raised in the `try` block.\n\n## Example\n```python\ntry:\n foo()\nexcept BaseException:\n ...\n```\n\nUse instead:\n```python\ntry:\n foo()\nexcept FileNotFoundError:\n ...\n```\n\nExceptions that are re-raised will _not_ be flagged, as they're expected to\nbe caught elsewhere:\n```python\ntry:\n foo()\nexcept BaseException:\n raise\n```\n\nExceptions that are logged with `exc_info` enabled will\n_not_ be flagged, as this is a common pattern for propagating exception\ntraces:\n```python\ntry:\n foo()\nexcept BaseException:\n logging.exception(\"Something went wrong\")\n```\n\n## Options\n\n- `lint.logger-objects`\n\n## References\n- [Python documentation: The `try` statement](https://docs.python.org/3/reference/compound_stmts.html#the-try-statement)\n- [Python documentation: Exception hierarchy](https://docs.python.org/3/library/exceptions.html#exception-hierarchy)\n- [PEP 8: Programming Recommendations on bare `except`](https://peps.python.org/pep-0008/#programming-recommendations)\n",
|
|
130
|
+
"ruff/FBT001": "## What it does\nChecks for the use of boolean positional arguments in function definitions,\nas determined by the presence of a type hint containing `bool` as an\nevident subtype - e.g. `bool`, `bool | int`, `typing.Optional[bool]`, etc.\n\n## Why is this bad?\nCalling a function with boolean positional arguments is confusing as the\nmeaning of the boolean value is not clear to the caller and to future\nreaders of the code.\n\nThe use of a boolean will also limit the function to only two possible\nbehaviors, which makes the function difficult to extend in the future.\n\nInstead, consider refactoring into separate implementations for the\n`True` and `False` cases, using an `Enum`, or making the argument a\nkeyword-only argument, to force callers to be explicit when providing\nthe argument.\n\nDunder methods that define operators are exempt from this rule, as are\nsetters and [`@override`][override] definitions.\n\n## Example\n\n```python\nfrom math import ceil, floor\n\n\ndef round_number(number: float, up: bool) -> int:\n return ceil(number) if up else floor(number)\n\n\nround_number(1.5, True) # What does `True` mean?\nround_number(1.5, False) # What does `False` mean?\n```\n\nInstead, refactor into separate implementations:\n\n```python\nfrom math import ceil, floor\n\n\ndef round_up(number: float) -> int:\n return ceil(number)\n\n\ndef round_down(number: float) -> int:\n return floor(number)\n\n\nround_up(1.5)\nround_down(1.5)\n```\n\nOr, refactor to use an `Enum`:\n\n```python\nfrom enum import Enum\n\n\nclass RoundingMethod(Enum):\n UP = 1\n DOWN = 2\n\n\ndef round_number(value: float, method: RoundingMethod) -> float: ...\n```\n\nOr, make the argument a keyword-only argument:\n\n```python\nfrom math import ceil, floor\n\n\ndef round_number(number: float, *, up: bool) -> int:\n return ceil(number) if up else floor(number)\n\n\nround_number(1.5, up=True)\nround_number(1.5, up=False)\n```\n\n## References\n- [Python documentation: Calls](https://docs.python.org/3/reference/expressions.html#calls)\n- [_How to Avoid \u201cThe Boolean Trap\u201d_ by Adam Johnson](https://adamj.eu/tech/2021/07/10/python-type-hints-how-to-avoid-the-boolean-trap/)\n\n[override]: https://docs.python.org/3/library/typing.html#typing.override\n",
|
|
131
|
+
"ruff/FBT002": "## What it does\nChecks for the use of boolean positional arguments in function definitions,\nas determined by the presence of a boolean default value.\n\n## Why is this bad?\nCalling a function with boolean positional arguments is confusing as the\nmeaning of the boolean value is not clear to the caller and to future\nreaders of the code.\n\nThe use of a boolean will also limit the function to only two possible\nbehaviors, which makes the function difficult to extend in the future.\n\nInstead, consider refactoring into separate implementations for the\n`True` and `False` cases, using an `Enum`, or making the argument a\nkeyword-only argument, to force callers to be explicit when providing\nthe argument.\n\nThis rule exempts methods decorated with [`@typing.override`][override],\nsince changing the signature of a subclass method that overrides a\nsuperclass method may cause type checkers to complain about a violation of\nthe Liskov Substitution Principle.\n\n## Example\n```python\nfrom math import ceil, floor\n\n\ndef round_number(number, up=True):\n return ceil(number) if up else floor(number)\n\n\nround_number(1.5, True) # What does `True` mean?\nround_number(1.5, False) # What does `False` mean?\n```\n\nInstead, refactor into separate implementations:\n```python\nfrom math import ceil, floor\n\n\ndef round_up(number):\n return ceil(number)\n\n\ndef round_down(number):\n return floor(number)\n\n\nround_up(1.5)\nround_down(1.5)\n```\n\nOr, refactor to use an `Enum`:\n```python\nfrom enum import Enum\n\n\nclass RoundingMethod(Enum):\n UP = 1\n DOWN = 2\n\n\ndef round_number(value, method):\n return ceil(number) if method is RoundingMethod.UP else floor(number)\n\n\nround_number(1.5, RoundingMethod.UP)\nround_number(1.5, RoundingMethod.DOWN)\n```\n\nOr, make the argument a keyword-only argument:\n```python\nfrom math import ceil, floor\n\n\ndef round_number(number, *, up=True):\n return ceil(number) if up else floor(number)\n\n\nround_number(1.5, up=True)\nround_number(1.5, up=False)\n```\n\n## References\n- [Python documentation: Calls](https://docs.python.org/3/reference/expressions.html#calls)\n- [_How to Avoid \u201cThe Boolean Trap\u201d_ by Adam Johnson](https://adamj.eu/tech/2021/07/10/python-type-hints-how-to-avoid-the-boolean-trap/)\n\n[override]: https://docs.python.org/3/library/typing.html#typing.override\n",
|
|
132
|
+
"ruff/FBT003": "## What it does\nChecks for boolean positional arguments in function calls.\n\nSome functions are whitelisted by default. To extend the list of allowed calls\nconfigure the [`lint.flake8-boolean-trap.extend-allowed-calls`] option.\n\n## Why is this bad?\nCalling a function with boolean positional arguments is confusing as the\nmeaning of the boolean value is not clear to the caller, and to future\nreaders of the code.\n\n## Example\n\n```python\ndef func(flag: bool) -> None: ...\n\n\nfunc(True)\n```\n\nUse instead:\n\n```python\ndef func(flag: bool) -> None: ...\n\n\nfunc(flag=True)\n```\n\n## Options\n- `lint.flake8-boolean-trap.extend-allowed-calls`\n\n## References\n- [Python documentation: Calls](https://docs.python.org/3/reference/expressions.html#calls)\n- [_How to Avoid \u201cThe Boolean Trap\u201d_ by Adam Johnson](https://adamj.eu/tech/2021/07/10/python-type-hints-how-to-avoid-the-boolean-trap/)\n",
|
|
133
|
+
"ruff/B002": "## What it does\nChecks for the attempted use of the unary prefix increment (`++`) or\ndecrement operator (`--`).\n\n## Why is this bad?\nPython does not support the unary prefix increment or decrement operator.\nWriting `++n` is equivalent to `+(+(n))` and writing `--n` is equivalent to\n`-(-(n))`. In both cases, it is equivalent to `n`.\n\n## Example\n```python\n++x\n--y\n```\n\nUse instead:\n```python\nx += 1\ny -= 1\n```\n\n## References\n- [Python documentation: Unary arithmetic and bitwise operations](https://docs.python.org/3/reference/expressions.html#unary-arithmetic-and-bitwise-operations)\n- [Python documentation: Augmented assignment statements](https://docs.python.org/3/reference/simple_stmts.html#augmented-assignment-statements)\n",
|
|
134
|
+
"ruff/B003": "## What it does\nChecks for assignments to `os.environ`.\n\n## Why is this bad?\nIn Python, `os.environ` is a mapping that represents the environment of the\ncurrent process.\n\nHowever, reassigning to `os.environ` does not clear the environment. Instead,\nit merely updates the `os.environ` for the current process. This can lead to\nunexpected behavior, especially when running the program in a subprocess.\n\nInstead, use `os.environ.clear()` to clear the environment, or use the\n`env` argument of `subprocess.Popen` to pass a custom environment to\na subprocess.\n\n## Example\n```python\nimport os\n\nos.environ = {\"foo\": \"bar\"}\n```\n\nUse instead:\n```python\nimport os\n\nos.environ.clear()\nos.environ[\"foo\"] = \"bar\"\n```\n\n## References\n- [Python documentation: `os.environ`](https://docs.python.org/3/library/os.html#os.environ)\n- [Python documentation: `subprocess.Popen`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen)\n",
|
|
135
|
+
"ruff/B004": "## What it does\nChecks for uses of `hasattr` to test if an object is callable (e.g.,\n`hasattr(obj, \"__call__\")`).\n\n## Why is this bad?\nUsing `hasattr` is an unreliable mechanism for testing if an object is\ncallable. If `obj` implements a custom `__getattr__`, or if its `__call__`\nis itself not callable, you may get misleading results.\n\nInstead, use `callable(obj)` to test if `obj` is callable.\n\n## Example\n```python\nhasattr(obj, \"__call__\")\n```\n\nUse instead:\n```python\ncallable(obj)\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe because the replacement may not be semantically\nequivalent to the original expression, potentially changing the behavior of the code.\n\nFor example, an imported module may have a `__call__` attribute but is not considered\na callable object:\n```python\nimport operator\n\nassert hasattr(operator, \"__call__\")\nassert callable(operator) is False\n```\nAdditionally, `__call__` may be defined only as an instance method:\n```python\nclass A:\n def __init__(self):\n self.__call__ = None\n\n\nassert hasattr(A(), \"__call__\")\nassert callable(A()) is False\n```\n\nAdditionally, if there are comments in the `hasattr` call expression, they may be removed:\n```python\nhasattr(\n # comment 1\n obj, # comment 2\n # comment 3\n \"__call__\", # comment 4\n # comment 5\n)\n```\n\n## References\n- [Python documentation: `callable`](https://docs.python.org/3/library/functions.html#callable)\n- [Python documentation: `hasattr`](https://docs.python.org/3/library/functions.html#hasattr)\n- [Python documentation: `__getattr__`](https://docs.python.org/3/reference/datamodel.html#object.__getattr__)\n- [Python documentation: `__call__`](https://docs.python.org/3/reference/datamodel.html#object.__call__)\n",
|
|
136
|
+
"ruff/B005": "## What it does\nChecks for uses of multi-character strings in `.strip()`, `.lstrip()`, and\n`.rstrip()` calls.\n\n## Why is this bad?\nAll characters in the call to `.strip()`, `.lstrip()`, or `.rstrip()` are\nremoved from the leading and trailing ends of the string. If the string\ncontains multiple characters, the reader may be misled into thinking that\na prefix or suffix is being removed, rather than a set of characters.\n\nIn Python 3.9 and later, you can use `str.removeprefix` and\n`str.removesuffix` to remove an exact prefix or suffix from a string,\nrespectively, which should be preferred when possible.\n\n## Known problems\nAs a heuristic, this rule only flags multi-character strings that contain\nduplicate characters. This allows usages like `.strip(\"xyz\")`, which\nremoves all occurrences of the characters `x`, `y`, and `z` from the\nleading and trailing ends of the string, but not `.strip(\"foo\")`.\n\nThe use of unique, multi-character strings may be intentional and\nconsistent with the intent of `.strip()`, `.lstrip()`, or `.rstrip()`,\nwhile the use of duplicate-character strings is very likely to be a\nmistake.\n\n## Example\n```python\n\"text.txt\".strip(\".txt\") # \"e\"\n```\n\nUse instead:\n```python\n\"text.txt\".removesuffix(\".txt\") # \"text\"\n```\n\n## Preview\nIn [preview], the diagnostic message reflects the actual method name\n(`.strip()`, `.lstrip()`, or `.rstrip()`), and the diagnostic range covers\nthe method call rather than the entire expression.\n\n## References\n- [Python documentation: `str.strip`](https://docs.python.org/3/library/stdtypes.html#str.strip)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
137
|
+
"ruff/B006": "## What it does\nChecks for uses of mutable objects as function argument defaults.\n\n## Why is this bad?\nFunction defaults are evaluated once, when the function is defined.\n\nThe same mutable object is then shared across all calls to the function.\nIf the object is modified, those modifications will persist across calls,\nwhich can lead to unexpected behavior.\n\nInstead, prefer to use immutable data structures, or take `None` as a\ndefault, and initialize a new mutable object inside the function body\nfor each call.\n\nArguments with immutable type annotations will be ignored by this rule.\nTypes outside of the standard library can be marked as immutable with the\n[`lint.flake8-bugbear.extend-immutable-calls`] configuration option.\n\n## Known problems\nMutable argument defaults can be used intentionally to cache computation\nresults. Replacing the default with `None` or an immutable data structure\ndoes not work for such usages. Instead, prefer the `@functools.lru_cache`\ndecorator from the standard library.\n\n## Example\n```python\ndef add_to_list(item, some_list=[]):\n some_list.append(item)\n return some_list\n\n\nl1 = add_to_list(0) # [0]\nl2 = add_to_list(1) # [0, 1]\n```\n\nUse instead:\n```python\ndef add_to_list(item, some_list=None):\n if some_list is None:\n some_list = []\n some_list.append(item)\n return some_list\n\n\nl1 = add_to_list(0) # [0]\nl2 = add_to_list(1) # [1]\n```\n\n## Options\n- `lint.flake8-bugbear.extend-immutable-calls`\n\n## Fix safety\n\nThis fix is marked as unsafe because it replaces the mutable default with `None`\nand initializes it in the function body, which may not be what the user intended,\nas described above.\n\n## References\n- [Python documentation: Default Argument Values](https://docs.python.org/3/tutorial/controlflow.html#default-argument-values)\n",
|
|
138
|
+
"ruff/B007": "## What it does\nChecks for unused variables in loops (e.g., `for` and `while` statements).\n\n## Why is this bad?\nDefining a variable in a loop statement that is never used can confuse\nreaders.\n\nIf the variable is intended to be unused (e.g., to facilitate\ndestructuring of a tuple or other object), prefix it with an underscore\nto indicate the intent. Otherwise, remove the variable entirely.\n\n## Example\n```python\nfor i, j in foo:\n bar(i)\n```\n\nUse instead:\n```python\nfor i, _j in foo:\n bar(i)\n```\n\n## Options\n\n- `lint.dummy-variable-rgx`\n\n## References\n- [PEP 8: Naming Conventions](https://peps.python.org/pep-0008/#naming-conventions)\n",
|
|
139
|
+
"ruff/B008": "## What it does\nChecks for function calls in default function arguments.\n\n## Why is this bad?\nAny function call that's used in a default argument will only be performed\nonce, at definition time. The returned value will then be reused by all\ncalls to the function, which can lead to unexpected behaviour.\n\nParameters with immutable type annotations will be ignored by this rule.\nThose whose default arguments are `NewType` calls where the original type\nis immutable are also ignored.\n\nCalls and types outside of the standard library can be marked as an exception\nto this rule with the [`lint.flake8-bugbear.extend-immutable-calls`] configuration option.\n\n## Example\n\n```python\ndef create_list() -> list[int]:\n return [1, 2, 3]\n\n\ndef mutable_default(arg: list[int] = create_list()) -> list[int]:\n arg.append(4)\n return arg\n```\n\nUse instead:\n\n```python\ndef better(arg: list[int] | None = None) -> list[int]:\n if arg is None:\n arg = create_list()\n\n arg.append(4)\n return arg\n```\n\nIf the use of a singleton is intentional, assign the result call to a\nmodule-level variable, and use that variable in the default argument:\n\n```python\nERROR = ValueError(\"Hosts weren't successfully added\")\n\n\ndef add_host(error: Exception = ERROR) -> None: ...\n```\n\n## Options\n- `lint.flake8-bugbear.extend-immutable-calls`\n",
|
|
140
|
+
"ruff/B009": "## What it does\nChecks for uses of `getattr` that take a constant attribute value as an\nargument (e.g., `getattr(obj, \"foo\")`).\n\n## Why is this bad?\n`getattr` is used to access attributes dynamically. If the attribute is\ndefined as a constant, it is no safer than a typical property access. When\npossible, prefer property access over `getattr` calls, as the former is\nmore concise and idiomatic.\n\n\n## Example\n```python\ngetattr(obj, \"foo\")\n```\n\nUse instead:\n```python\nobj.foo\n```\n\n## Fix safety\nThe fix is marked as unsafe for attribute names that are not in NFKC (Normalization Form KC)\nnormalization. Python normalizes identifiers using NFKC when using attribute access syntax\n(e.g., `obj.attr`), but does not normalize string arguments passed to `getattr`. Rewriting\n`getattr(obj, \"\u017f\")` to `obj.\u017f` would be interpreted as `obj.s` at runtime, changing behavior.\n\nAdditionally, the fix is marked as unsafe if the expression contains comments,\nas the replacement may remove comments attached to the original `getattr` call.\n\nFor example, the long s character `\"\u017f\"` normalizes to `\"s\"` under NFKC, so:\n```python\n# This accesses an attribute with the exact name \"\u017f\" (if it exists)\nvalue = getattr(obj, \"\u017f\")\n\n# But this would normalize to \"s\" and access a different attribute\nobj.\u017f # This is interpreted as obj.s, not obj.\u017f\n```\n\n## References\n- [Python documentation: `getattr`](https://docs.python.org/3/library/functions.html#getattr)\n",
|
|
141
|
+
"ruff/B010": "## What it does\nChecks for uses of `setattr` that take a constant attribute value as an\nargument (e.g., `setattr(obj, \"foo\", 42)`).\n\n## Why is this bad?\n`setattr` is used to set attributes dynamically. If the attribute is\ndefined as a constant, it is no safer than a typical property access. When\npossible, prefer property access over `setattr` calls, as the former is\nmore concise and idiomatic.\n\n## Example\n```python\nsetattr(obj, \"foo\", 42)\n```\n\nUse instead:\n```python\nobj.foo = 42\n```\n\n## Fix safety\nThe fix is marked as unsafe for attribute names that are not in NFKC (Normalization Form KC)\nnormalization. Python normalizes identifiers using NFKC when using attribute access syntax\n(e.g., `obj.attr = value`), but does not normalize string arguments passed to `setattr`.\nRewriting `setattr(obj, \"\u017f\", 1)` to `obj.\u017f = 1` would be interpreted as `obj.s = 1` at\nruntime, changing behavior.\n\nAdditionally, the fix is marked as unsafe if the expression contains comments,\nas the replacement may remove comments attached to the original `setattr` call.\n\nFor example, the long s character `\"\u017f\"` normalizes to `\"s\"` under NFKC, so:\n```python\n# This creates an attribute with the exact name \"\u017f\"\nsetattr(obj, \"\u017f\", 1)\ngetattr(obj, \"\u017f\") # Returns 1\n\n# But this would normalize to \"s\" and set a different attribute\nobj.\u017f = 1 # This is interpreted as obj.s = 1, not obj.\u017f = 1\n```\n\n## Known issues\nIn some cases, a type checker may be able to analyze an assignment more\nthoroughly than a `setattr` call. Applying the fix in such cases may result\nin new type checking diagnostics, even if the runtime behavior of the code\nis unchanged.\n\n## References\n- [Python documentation: `setattr`](https://docs.python.org/3/library/functions.html#setattr)\n",
|
|
142
|
+
"ruff/B011": "## What it does\nChecks for uses of `assert False`.\n\n## Why is this bad?\nPython removes `assert` statements when running in optimized mode\n(`python -O`), making `assert False` an unreliable means of\nraising an `AssertionError`.\n\nInstead, raise an `AssertionError` directly.\n\n## Example\n```python\nassert False\n```\n\nUse instead:\n```python\nraise AssertionError\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as changing an `assert` to a\n`raise` will change the behavior of your program when running in\noptimized mode (`python -O`).\n\n## References\n- [Python documentation: `assert`](https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement)\n",
|
|
143
|
+
"ruff/B012": "## What it does\nChecks for `break`, `continue`, and `return` statements in `finally`\nblocks.\n\n## Why is this bad?\nThe use of `break`, `continue`, and `return` statements in `finally` blocks\ncan cause exceptions to be silenced.\n\n`finally` blocks execute regardless of whether an exception is raised. If a\n`break`, `continue`, or `return` statement is reached in a `finally` block,\nany exception raised in the `try` or `except` blocks will be silenced.\n\n## Example\n```python\ndef speed(distance, time):\n try:\n return distance / time\n except ZeroDivisionError:\n raise ValueError(\"Time cannot be zero\")\n finally:\n return 299792458 # `ValueError` is silenced\n```\n\nUse instead:\n```python\ndef speed(distance, time):\n try:\n return distance / time\n except ZeroDivisionError:\n raise ValueError(\"Time cannot be zero\")\n```\n\n## References\n- [Python documentation: The `try` statement](https://docs.python.org/3/reference/compound_stmts.html#the-try-statement)\n",
|
|
144
|
+
"ruff/B013": "## What it does\nChecks for single-element tuples in exception handlers (e.g.,\n`except (ValueError,):`).\n\nNote: Single-element tuples consisting of a starred expression\nare allowed.\n\n## Why is this bad?\nA tuple with a single element can be more concisely and idiomatically\nexpressed as a single value.\n\n## Example\n```python\ntry:\n ...\nexcept (ValueError,):\n ...\n```\n\nUse instead:\n```python\ntry:\n ...\nexcept ValueError:\n ...\n```\n\n## Fix safety\nThis rule's fix is marked as safe, unless the exception handler contains comments.\n\n## References\n- [Python documentation: `except` clause](https://docs.python.org/3/reference/compound_stmts.html#except-clause)\n",
|
|
145
|
+
"ruff/B014": "## What it does\nChecks for exception handlers that catch duplicate exceptions.\n\n## Why is this bad?\nIncluding the same exception multiple times in the same handler is redundant,\nas the first exception will catch the exception, making the second exception\nunreachable. The same applies to exception hierarchies, as a handler for a\nparent exception (like `Exception`) will also catch child exceptions (like\n`ValueError`).\n\n## Example\n```python\ntry:\n ...\nexcept (Exception, ValueError): # `Exception` includes `ValueError`.\n ...\n```\n\nUse instead:\n```python\ntry:\n ...\nexcept Exception:\n ...\n```\n\n## References\n- [Python documentation: `except` clause](https://docs.python.org/3/reference/compound_stmts.html#except-clause)\n- [Python documentation: Exception hierarchy](https://docs.python.org/3/library/exceptions.html#exception-hierarchy)\n",
|
|
146
|
+
"ruff/B015": "## What it does\nChecks for useless comparisons.\n\n## Why is this bad?\nUseless comparisons have no effect on the program, and are often included\nby mistake. If the comparison is intended to enforce an invariant, prepend\nthe comparison with an `assert`. Otherwise, remove it entirely.\n\n## Example\n```python\nfoo == bar\n```\n\nUse instead:\n```python\nassert foo == bar, \"`foo` and `bar` should be equal.\"\n```\n\n## Notebook behavior\nFor Jupyter Notebooks, this rule is not applied to the last top-level expression in a cell.\nThis is because it's common to have a notebook cell that ends with an expression,\nwhich will result in the `repr` of the evaluated expression being printed as the cell's output.\n\n## References\n- [Python documentation: `assert` statement](https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement)\n",
|
|
147
|
+
"ruff/B016": "## What it does\nChecks for `raise` statements that raise a literal value.\n\n## Why is this bad?\n`raise` must be followed by an exception instance or an exception class,\nand exceptions must be instances of `BaseException` or a subclass thereof.\nRaising a literal will raise a `TypeError` at runtime.\n\n## Example\n```python\nraise \"foo\"\n```\n\nUse instead:\n```python\nraise Exception(\"foo\")\n```\n\n## References\n- [Python documentation: `raise` statement](https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement)\n",
|
|
148
|
+
"ruff/B017": "## What it does\nChecks for `assertRaises` and `pytest.raises` context managers that catch\n`Exception` or `BaseException`.\n\n## Why is this bad?\nThese forms catch every `Exception`, which can lead to tests passing even\nif, e.g., the code under consideration raises a `SyntaxError` or\n`IndentationError`.\n\nEither assert for a more specific exception (builtin or custom), or use\n`assertRaisesRegex` or `pytest.raises(..., match=<REGEX>)` respectively.\n\n## Example\n```python\nself.assertRaises(Exception, foo)\n```\n\nUse instead:\n```python\nself.assertRaises(SomeSpecificException, foo)\n```\n",
|
|
149
|
+
"ruff/B018": "## What it does\nChecks for useless expressions.\n\n## Why is this bad?\nUseless expressions have no effect on the program, and are often included\nby mistake. Assign a useless expression to a variable, or remove it\nentirely.\n\n## Example\n```python\n1 + 1\n```\n\nUse instead:\n```python\nfoo = 1 + 1\n```\n\n## Notebook behavior\nFor Jupyter Notebooks, this rule is not applied to the last top-level expression in a cell.\nThis is because it's common to have a notebook cell that ends with an expression,\nwhich will result in the `repr` of the evaluated expression being printed as the cell's output.\n\n## Known problems\nThis rule ignores expression types that are commonly used for their side\neffects, such as function calls.\n\nHowever, if a seemingly useless expression (like an attribute access) is\nneeded to trigger a side effect, consider assigning it to an anonymous\nvariable, to indicate that the return value is intentionally ignored.\n\nFor example, given:\n```python\nwith errors.ExceptionRaisedContext():\n obj.attribute\n```\n\nUse instead:\n```python\nwith errors.ExceptionRaisedContext():\n _ = obj.attribute\n```\n",
|
|
150
|
+
"ruff/B019": "## What it does\nChecks for uses of the `functools.lru_cache` and `functools.cache`\ndecorators on methods.\n\n## Why is this bad?\nUsing the `functools.lru_cache` and `functools.cache` decorators on methods\ncan lead to memory leaks, as the global cache will retain a reference to\nthe instance, preventing it from being garbage collected.\n\nInstead, refactor the method to depend only on its arguments and not on the\ninstance of the class, or use the `@lru_cache` decorator on a function\noutside of the class.\n\nThis rule ignores instance methods on enumeration classes, as enum members\nare singletons.\n\n## Example\n```python\nfrom functools import lru_cache\n\n\ndef square(x: int) -> int:\n return x * x\n\n\nclass Number:\n value: int\n\n @lru_cache\n def squared(self):\n return square(self.value)\n```\n\nUse instead:\n```python\nfrom functools import lru_cache\n\n\n@lru_cache\ndef square(x: int) -> int:\n return x * x\n\n\nclass Number:\n value: int\n\n def squared(self):\n return square(self.value)\n```\n\n## Options\n\nThis rule only applies to regular methods, not static or class methods. You can customize how\nRuff categorizes methods with the following options:\n\n- `lint.pep8-naming.classmethod-decorators`\n- `lint.pep8-naming.staticmethod-decorators`\n\n## References\n- [Python documentation: `functools.lru_cache`](https://docs.python.org/3/library/functools.html#functools.lru_cache)\n- [Python documentation: `functools.cache`](https://docs.python.org/3/library/functools.html#functools.cache)\n- [don't lru_cache methods!](https://www.youtube.com/watch?v=sVjtp6tGo0g)\n",
|
|
151
|
+
"ruff/B020": "## What it does\nChecks for loop control variables that override the loop iterable.\n\n## Why is this bad?\nLoop control variables should not override the loop iterable, as this can\nlead to confusing behavior.\n\nInstead, use a distinct variable name for any loop control variables.\n\n## Example\n```python\nitems = [1, 2, 3]\n\nfor items in items:\n print(items)\n```\n\nUse instead:\n```python\nitems = [1, 2, 3]\n\nfor item in items:\n print(item)\n```\n\n## References\n- [Python documentation: The `for` statement](https://docs.python.org/3/reference/compound_stmts.html#the-for-statement)\n",
|
|
152
|
+
"ruff/B021": "## What it does\nChecks for docstrings that are written via f-strings.\n\n## Why is this bad?\nPython will interpret the f-string as a joined string, rather than as a\ndocstring. As such, the \"docstring\" will not be accessible via the\n`__doc__` attribute, nor will it be picked up by any automated\ndocumentation tooling.\n\n## Example\n```python\ndef foo():\n f\"\"\"Not a docstring.\"\"\"\n```\n\nUse instead:\n```python\ndef foo():\n \"\"\"A docstring.\"\"\"\n```\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [Python documentation: Formatted string literals](https://docs.python.org/3/reference/lexical_analysis.html#f-strings)\n",
|
|
153
|
+
"ruff/B022": "## What it does\nChecks for `contextlib.suppress` without arguments.\n\n## Why is this bad?\n`contextlib.suppress` is a context manager that suppresses exceptions. It takes,\nas arguments, the exceptions to suppress within the enclosed block. If no\nexceptions are specified, then the context manager won't suppress any\nexceptions, and is thus redundant.\n\nConsider adding exceptions to the `contextlib.suppress` call, or removing the\ncontext manager entirely.\n\n## Example\n```python\nimport contextlib\n\nwith contextlib.suppress():\n foo()\n```\n\nUse instead:\n```python\nimport contextlib\n\nwith contextlib.suppress(Exception):\n foo()\n```\n\n## References\n- [Python documentation: `contextlib.suppress`](https://docs.python.org/3/library/contextlib.html#contextlib.suppress)\n",
|
|
154
|
+
"ruff/B023": "## What it does\nChecks for function definitions that use a loop variable.\n\n## Why is this bad?\nThe loop variable is not bound in the function definition, so it will always\nhave the value it had in the last iteration when the function is called.\n\nInstead, consider using a default argument to bind the loop variable at\nfunction definition time. Or, use `functools.partial`.\n\n## Example\n```python\nadders = [lambda x: x + i for i in range(3)]\nvalues = [adder(1) for adder in adders] # [3, 3, 3]\n```\n\nUse instead:\n```python\nadders = [lambda x, i=i: x + i for i in range(3)]\nvalues = [adder(1) for adder in adders] # [1, 2, 3]\n```\n\nOr:\n```python\nfrom functools import partial\n\nadders = [partial(lambda x, i: x + i, i=i) for i in range(3)]\nvalues = [adder(1) for adder in adders] # [1, 2, 3]\n```\n\n## References\n- [The Hitchhiker's Guide to Python: Late Binding Closures](https://docs.python-guide.org/writing/gotchas/#late-binding-closures)\n- [Python documentation: `functools.partial`](https://docs.python.org/3/library/functools.html#functools.partial)\n",
|
|
155
|
+
"ruff/B024": "## What it does\nChecks for abstract classes without abstract methods or properties.\nAnnotated but unassigned class variables are regarded as abstract.\n\n## Why is this bad?\nAbstract base classes are used to define interfaces. If an abstract base\nclass has no abstract methods or properties, you may have forgotten\nto add an abstract method or property to the class,\nor omitted an `@abstractmethod` decorator.\n\nIf the class is _not_ meant to be used as an interface, consider removing\nthe `ABC` base class from the class definition.\n\n## Example\n```python\nfrom abc import ABC\nfrom typing import ClassVar\n\n\nclass Foo(ABC):\n class_var: ClassVar[str] = \"assigned\"\n\n def method(self):\n bar()\n```\n\nUse instead:\n```python\nfrom abc import ABC, abstractmethod\nfrom typing import ClassVar\n\n\nclass Foo(ABC):\n class_var: ClassVar[str] # unassigned\n\n @abstractmethod\n def method(self):\n bar()\n```\n\n## References\n- [Python documentation: `abc`](https://docs.python.org/3/library/abc.html)\n- [Python documentation: `typing.ClassVar`](https://docs.python.org/3/library/typing.html#typing.ClassVar)\n",
|
|
156
|
+
"ruff/B025": "## What it does\nChecks for `try-except` blocks with duplicate exception handlers.\n\n## Why is this bad?\nDuplicate exception handlers are redundant, as the first handler will catch\nthe exception, making the second handler unreachable.\n\n## Example\n```python\ntry:\n ...\nexcept ValueError:\n ...\nexcept ValueError:\n ...\n```\n\nUse instead:\n```python\ntry:\n ...\nexcept ValueError:\n ...\n```\n\n## Fix safety\nThis rule's fix is marked as safe, unless the exception handler contains comments.\n\n## References\n- [Python documentation: `except` clause](https://docs.python.org/3/reference/compound_stmts.html#except-clause)\n",
|
|
157
|
+
"ruff/B026": "## What it does\nChecks for function calls that use star-argument unpacking after providing a\nkeyword argument\n\n## Why is this bad?\nIn Python, you can use star-argument unpacking to pass a list or tuple of\narguments to a function.\n\nProviding a star-argument after a keyword argument can lead to confusing\nbehavior, and is only supported for backwards compatibility.\n\n## Example\n```python\ndef foo(x, y, z):\n return x, y, z\n\n\nfoo(1, 2, 3) # (1, 2, 3)\nfoo(1, *[2, 3]) # (1, 2, 3)\n# foo(x=1, *[2, 3]) # TypeError\n# foo(y=2, *[1, 3]) # TypeError\nfoo(z=3, *[1, 2]) # (1, 2, 3) # No error, but confusing!\n```\n\nUse instead:\n```python\ndef foo(x, y, z):\n return x, y, z\n\n\nfoo(1, 2, 3) # (1, 2, 3)\nfoo(x=1, y=2, z=3) # (1, 2, 3)\nfoo(*[1, 2, 3]) # (1, 2, 3)\nfoo(*[1, 2], 3) # (1, 2, 3)\n```\n\n## References\n- [Python documentation: Calls](https://docs.python.org/3/reference/expressions.html#calls)\n- [Disallow iterable argument unpacking after a keyword argument?](https://github.com/python/cpython/issues/82741)\n",
|
|
158
|
+
"ruff/B027": "## What it does\nChecks for empty methods in abstract base classes without an abstract\ndecorator.\n\n## Why is this bad?\nEmpty methods in abstract base classes without an abstract decorator may be\nbe indicative of a mistake. If the method is meant to be abstract, add an\n`@abstractmethod` decorator to the method.\n\n## Example\n\n```python\nfrom abc import ABC\n\n\nclass Foo(ABC):\n def method(self): ...\n```\n\nUse instead:\n\n```python\nfrom abc import ABC, abstractmethod\n\n\nclass Foo(ABC):\n @abstractmethod\n def method(self): ...\n```\n\n## References\n- [Python documentation: `abc`](https://docs.python.org/3/library/abc.html)\n",
|
|
159
|
+
"ruff/B028": "## What it does\nChecks for `warnings.warn` calls without an explicit `stacklevel` keyword\nargument.\n\n## Why is this bad?\nThe `warnings.warn` method uses a `stacklevel` of 1 by default, which\nwill output a stack frame of the line on which the \"warn\" method\nis called. Setting it to a higher number will output a stack frame\nfrom higher up the stack.\n\nIt's recommended to use a `stacklevel` of 2 or higher, to give the caller\nmore context about the warning.\n\nIn Python 3.12 and higher, one may also use `skip_file_prefixes` to specify\nwhich file prefixes are ignored when counting the stack level. This implicitly overrides the `stacklevel` to be\nat least 2, according to the [Python documentation].\n## Example\n```python\nimport warnings\n\nwarnings.warn(\"This is a warning\")\n```\n\nUse instead:\n```python\nimport warnings\n\nwarnings.warn(\"This is a warning\", stacklevel=2)\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe because it changes\nthe behavior of the code. Moreover, the fix will assign\na stacklevel of 2, while the user may wish to assign a\nhigher stacklevel to address the diagnostic.\n\n## References\n- [Python documentation: `warnings.warn`][Python documentation]\n\n[Python documentation]: https://docs.python.org/3/library/warnings.html#warnings.warn\n",
|
|
160
|
+
"ruff/B029": "## What it does\nChecks for exception handlers that catch an empty tuple.\n\n## Why is this bad?\nAn exception handler that catches an empty tuple will not catch anything,\nand is indicative of a mistake. Instead, add exceptions to the `except`\nclause.\n\n## Example\n```python\ntry:\n 1 / 0\nexcept ():\n ...\n```\n\nUse instead:\n```python\ntry:\n 1 / 0\nexcept ZeroDivisionError:\n ...\n```\n\n## References\n- [Python documentation: `except` clause](https://docs.python.org/3/reference/compound_stmts.html#except-clause)\n",
|
|
161
|
+
"ruff/B030": "## What it does\nChecks for exception handlers that catch non-exception classes.\n\n## Why is this bad?\nCatching classes that do not inherit from `BaseException` will raise a\n`TypeError`.\n\n## Example\n```python\ntry:\n 1 / 0\nexcept 1:\n ...\n```\n\nUse instead:\n```python\ntry:\n 1 / 0\nexcept ZeroDivisionError:\n ...\n```\n\n## References\n- [Python documentation: `except` clause](https://docs.python.org/3/reference/compound_stmts.html#except-clause)\n- [Python documentation: Built-in Exceptions](https://docs.python.org/3/library/exceptions.html#built-in-exceptions)\n",
|
|
162
|
+
"ruff/B031": "## What it does\nChecks for multiple usage of the generator returned from\n`itertools.groupby()`.\n\n## Why is this bad?\nUsing the generator more than once will do nothing on the second usage.\nIf that data is needed later, it should be stored as a list.\n\n## Example:\n```python\nimport itertools\n\nfor name, group in itertools.groupby(data):\n for _ in range(5):\n do_something_with_the_group(group)\n```\n\nUse instead:\n```python\nimport itertools\n\nfor name, group in itertools.groupby(data):\n values = list(group)\n for _ in range(5):\n do_something_with_the_group(values)\n```\n",
|
|
163
|
+
"ruff/B032": "## What it does\nChecks for the unintentional use of type annotations.\n\n## Why is this bad?\nThe use of a colon (`:`) in lieu of an assignment (`=`) can be syntactically valid, but\nis almost certainly a mistake when used in a subscript or attribute assignment.\n\n## Example\n```python\na[\"b\"]: 1\n```\n\nUse instead:\n```python\na[\"b\"] = 1\n```\n",
|
|
164
|
+
"ruff/B033": "## What it does\nChecks for set literals that contain duplicate items.\n\n## Why is this bad?\nIn Python, sets are unordered collections of unique elements. Including a\nduplicate item in a set literal is redundant, as the duplicate item will be\nreplaced with a single item at runtime.\n\n## Example\n```python\n{1, 2, 3, 1}\n```\n\nUse instead:\n```python\n{1, 2, 3}\n```\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the\noriginal expression, potentially losing important context or documentation.\n\nFor example:\n```python\n{\n 1,\n 2,\n # Comment\n 1,\n}\n```\n",
|
|
165
|
+
"ruff/B034": "## What it does\nChecks for calls to `re.sub`, `re.subn`, and `re.split` that pass `count`,\n`maxsplit`, or `flags` as positional arguments.\n\n## Why is this bad?\nPassing `count`, `maxsplit`, or `flags` as positional arguments to\n`re.sub`, `re.subn`, or `re.split` can lead to confusion, as most methods in\nthe `re` module accept `flags` as the third positional argument, while\n`re.sub`, `re.subn`, and `re.split` have different signatures.\n\nInstead, pass `count`, `maxsplit`, and `flags` as keyword arguments.\n\n## Example\n```python\nimport re\n\nre.split(\"pattern\", \"replacement\", 1)\n```\n\nUse instead:\n```python\nimport re\n\nre.split(\"pattern\", \"replacement\", maxsplit=1)\n```\n\n## References\n- [Python documentation: `re.sub`](https://docs.python.org/3/library/re.html#re.sub)\n- [Python documentation: `re.subn`](https://docs.python.org/3/library/re.html#re.subn)\n- [Python documentation: `re.split`](https://docs.python.org/3/library/re.html#re.split)\n",
|
|
166
|
+
"ruff/B035": "## What it does\nChecks for dictionary comprehensions that use a static key, like a string\nliteral or a variable defined outside the comprehension.\n\n## Why is this bad?\nUsing a static key (like a string literal) in a dictionary comprehension\nis usually a mistake, as it will result in a dictionary with only one key,\ndespite the comprehension iterating over multiple values.\n\n## Example\n```python\ndata = [\"some\", \"Data\"]\n{\"key\": value.upper() for value in data}\n```\n\nUse instead:\n```python\ndata = [\"some\", \"Data\"]\n{value: value.upper() for value in data}\n```\n",
|
|
167
|
+
"ruff/B039": "## What it does\nChecks for uses of mutable objects as `ContextVar` defaults.\n\n## Why is this bad?\n\nThe `ContextVar` default is evaluated once, when the `ContextVar` is defined.\n\nThe same mutable object is then shared across all `.get()` method calls to\nthe `ContextVar`. If the object is modified, those modifications will persist\nacross calls, which can lead to unexpected behavior.\n\nInstead, prefer to use immutable data structures. Alternatively, take\n`None` as a default, and initialize a new mutable object inside for each\ncall using the `.set()` method.\n\nTypes outside the standard library can be marked as immutable with the\n[`lint.flake8-bugbear.extend-immutable-calls`] configuration option.\n\n## Example\n```python\nfrom contextvars import ContextVar\n\n\ncv: ContextVar[list] = ContextVar(\"cv\", default=[])\n```\n\nUse instead:\n```python\nfrom contextvars import ContextVar\n\n\ncv: ContextVar[list | None] = ContextVar(\"cv\", default=None)\n\n...\n\nif cv.get() is None:\n cv.set([])\n```\n\n## Options\n- `lint.flake8-bugbear.extend-immutable-calls`\n\n## References\n- [Python documentation: `contextvars` \u2014 Context Variables](https://docs.python.org/3/library/contextvars.html)\n",
|
|
168
|
+
"ruff/B043": "## What it does\nChecks for uses of `delattr` that take a constant attribute value as an\nargument (e.g., `delattr(obj, \"foo\")`).\n\n## Why is this bad?\n`delattr` is used to delete attributes dynamically. If the attribute is\ndefined as a constant, it is no safer than a typical property deletion.\nWhen possible, prefer `del` statements over `delattr` calls, as the\nformer is more concise and idiomatic.\n\n## Example\n```python\ndelattr(obj, \"foo\")\n```\n\nUse instead:\n```python\ndel obj.foo\n```\n\n## Fix safety\nThe fix is marked as unsafe for attribute names that are not in NFKC\n(Normalization Form KC) normalization. Python normalizes identifiers using\nNFKC when using attribute access syntax (e.g., `del obj.attr`), but does\nnot normalize string arguments passed to `delattr`. Rewriting\n`delattr(obj, \"\u017f\")` to `del obj.\u017f` would be interpreted as `del obj.s`\nat runtime, changing behavior.\n\nAdditionally, the fix is marked as unsafe if the expression contains\ncomments, as the replacement may remove comments attached to the original\n`delattr` call.\n\n## References\n- [Python documentation: `delattr`](https://docs.python.org/3/library/functions.html#delattr)\n",
|
|
169
|
+
"ruff/B901": "## What it does\nChecks for `return {value}` statements in functions that also contain `yield`\nor `yield from` statements.\n\n## Why is this bad?\nUsing `return {value}` in a generator function was syntactically invalid in\nPython 2. In Python 3 `return {value}` _can_ be used in a generator; however,\nthe combination of `yield` and `return` can lead to confusing behavior, as\nthe `return` statement will cause the generator to raise `StopIteration`\nwith the value provided, rather than returning the value to the caller.\n\nFor example, given:\n```python\nfrom collections.abc import Iterable\nfrom pathlib import Path\n\n\ndef get_file_paths(file_types: Iterable[str] | None = None) -> Iterable[Path]:\n dir_path = Path(\".\")\n if file_types is None:\n return dir_path.glob(\"*\")\n\n for file_type in file_types:\n yield from dir_path.glob(f\"*.{file_type}\")\n```\n\nReaders might assume that `get_file_paths()` would return an iterable of\n`Path` objects in the directory; in reality, though, `list(get_file_paths())`\nevaluates to `[]`, since the `return` statement causes the generator to raise\n`StopIteration` with the value `dir_path.glob(\"*\")`:\n\n```shell\n>>> list(get_file_paths(file_types=[\"cfg\", \"toml\"]))\n[PosixPath('setup.cfg'), PosixPath('pyproject.toml')]\n>>> list(get_file_paths())\n[]\n```\n\nFor intentional uses of `return` in a generator, consider suppressing this\ndiagnostic.\n\n## Example\n```python\nfrom collections.abc import Iterable\nfrom pathlib import Path\n\n\ndef get_file_paths(file_types: Iterable[str] | None = None) -> Iterable[Path]:\n dir_path = Path(\".\")\n if file_types is None:\n return dir_path.glob(\"*\")\n\n for file_type in file_types:\n yield from dir_path.glob(f\"*.{file_type}\")\n```\n\nUse instead:\n\n```python\nfrom collections.abc import Iterable\nfrom pathlib import Path\n\n\ndef get_file_paths(file_types: Iterable[str] | None = None) -> Iterable[Path]:\n dir_path = Path(\".\")\n if file_types is None:\n yield from dir_path.glob(\"*\")\n else:\n for file_type in file_types:\n yield from dir_path.glob(f\"*.{file_type}\")\n```\n",
|
|
170
|
+
"ruff/B903": "## What it does\nChecks for classes that only have a public `__init__` method,\nwithout base classes and decorators.\n\n## Why is this bad?\nClasses with just an `__init__` are possibly better off\nbeing a dataclass or a namedtuple, which have less boilerplate.\n\n## Example\n```python\nclass Point:\n def __init__(self, x: float, y: float):\n self.x = x\n self.y = y\n```\n\nUse instead:\n```python\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Point:\n x: float\n y: float\n```\n",
|
|
171
|
+
"ruff/B904": "## What it does\nChecks for `raise` statements in exception handlers that lack a `from`\nclause.\n\n## Why is this bad?\nIn Python, `raise` can be used with or without an exception from which the\ncurrent exception is derived. This is known as exception chaining. When\nprinting the stack trace, chained exceptions are displayed in such a way\nso as make it easier to trace the exception back to its root cause.\n\nWhen raising a new exception from within an `except` clause, it's recommended to\ninclude a `from` clause to explicitly set the exception's cause. Without it,\nPython will implicitly chain from the current exception (setting `__context__`),\nbut the `__cause__` attribute won't be set, which may make debugging slightly\nmore difficult.\n\n## Example\n```python\ntry:\n ...\nexcept FileNotFoundError:\n if ...:\n raise RuntimeError(\"...\")\n else:\n raise UserWarning(\"...\")\n```\n\nUse instead:\n```python\ntry:\n ...\nexcept FileNotFoundError as exc:\n if ...:\n raise RuntimeError(\"...\") from None\n else:\n raise UserWarning(\"...\") from exc\n```\n\n## References\n- [Python documentation: `raise` statement](https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement)\n",
|
|
172
|
+
"ruff/B905": "## What it does\nChecks for `zip` calls without an explicit `strict` parameter when called with two or more iterables, or any starred argument.\n\n## Why is this bad?\nBy default, if the iterables passed to `zip` are of different lengths, the\nresulting iterator will be silently truncated to the length of the shortest\niterable. This can lead to subtle bugs.\n\nPass `strict=True` to raise a `ValueError` if the iterables are of\nnon-uniform length. Alternatively, if the iterables are deliberately of\ndifferent lengths, pass `strict=False` to make the intention explicit.\n\n## Example\n```python\nzip(a, b)\n```\n\nUse instead:\n```python\nzip(a, b, strict=True)\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe. While adding `strict=False` preserves\nthe runtime behavior, it can obscure situations where the iterables are of\nunequal length. Ruff prefers to alert users so they can choose the intended\nbehavior themselves.\n\n## References\n- [Python documentation: `zip`](https://docs.python.org/3/library/functions.html#zip)\n",
|
|
173
|
+
"ruff/B909": "## What it does\nChecks for mutations to an iterable during a loop iteration.\n\n## Why is this bad?\nWhen iterating over an iterable, mutating the iterable can lead to unexpected\nbehavior, like skipping elements or infinite loops.\n\n## Example\n```python\nitems = [1, 2, 3]\n\nfor item in items:\n print(item)\n\n # Create an infinite loop by appending to the list.\n items.append(item)\n```\n\n## References\n- [Python documentation: Mutable Sequence Types](https://docs.python.org/3/library/stdtypes.html#typesseq-mutable)\n",
|
|
174
|
+
"ruff/B911": "## What it does\nChecks for `itertools.batched` calls without an explicit `strict` parameter.\n\n## Why is this bad?\nBy default, if the length of the iterable is not divisible by\nthe second argument to `itertools.batched`, the last batch\nwill be shorter than the rest.\n\nIn Python 3.13, a `strict` parameter was added which allows controlling if the batches must be of uniform length.\nPass `strict=True` to raise a `ValueError` if the batches are of non-uniform length.\nOtherwise, pass `strict=False` to make the intention explicit.\n\n## Example\n```python\nimport itertools\n\nitertools.batched(iterable, n)\n```\n\nUse instead if the batches must be of uniform length:\n```python\nimport itertools\n\nitertools.batched(iterable, n, strict=True)\n```\n\nOr if the batches can be of non-uniform length:\n```python\nimport itertools\n\nitertools.batched(iterable, n, strict=False)\n```\n\n## Known deviations\nUnlike the upstream `B911`, this rule will not report infinite iterators\n(e.g., `itertools.cycle(...)`).\n\n## Options\n- `target-version`\n\n## References\n- [Python documentation: `batched`](https://docs.python.org/3/library/itertools.html#batched)\n",
|
|
175
|
+
"ruff/B912": "## What it does\nChecks for `map` calls without an explicit `strict` parameter when called with two or more\niterables, or any starred argument.\n\nThis rule applies to Python 3.14 and later, where `map` accepts a `strict` keyword\nargument. For details, see: [What\u2019s New in Python 3.14].\n\n## Why is this bad?\nBy default, if the iterables passed to `map` are of different lengths, the\nresulting iterator will be silently truncated to the length of the shortest\niterable. This can lead to subtle bugs.\n\nPass `strict=True` to raise a `ValueError` if the iterables are of\nnon-uniform length. Alternatively, if the iterables are deliberately of\ndifferent lengths, pass `strict=False` to make the intention explicit.\n\n## Example\n```python\nmap(f, a, b)\n```\n\nUse instead:\n```python\nmap(f, a, b, strict=True)\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe. While adding `strict=False` preserves\nthe runtime behavior, it can obscure situations where the iterables are of\nunequal length. Ruff prefers to alert users so they can choose the intended\nbehavior themselves.\n\n## References\n- [Python documentation: `map`](https://docs.python.org/3/library/functions.html#map)\n- [What\u2019s New in Python 3.14]\n\n[What's New in Python 3.14]: https://docs.python.org/dev/whatsnew/3.14.html\n",
|
|
176
|
+
"ruff/A001": "## What it does\nChecks for variable (and function) assignments that use the same names\nas builtins.\n\n## Why is this bad?\nReusing a builtin name for the name of a variable increases the\ndifficulty of reading and maintaining the code, and can cause\nnon-obvious errors, as readers may mistake the variable for the\nbuiltin and vice versa.\n\nBuiltins can be marked as exceptions to this rule via the\n[`lint.flake8-builtins.ignorelist`] configuration option.\n\n## Example\n```python\ndef find_max(list_of_lists):\n max = 0\n for flat_list in list_of_lists:\n for value in flat_list:\n max = max(max, value) # TypeError: 'int' object is not callable\n return max\n```\n\nUse instead:\n```python\ndef find_max(list_of_lists):\n result = 0\n for flat_list in list_of_lists:\n for value in flat_list:\n result = max(result, value)\n return result\n```\n\n## Options\n- `lint.flake8-builtins.ignorelist`\n\n## References\n- [_Why is it a bad idea to name a variable `id` in Python?_](https://stackoverflow.com/questions/77552/id-is-a-bad-variable-name-in-python)\n",
|
|
177
|
+
"ruff/A002": "## What it does\nChecks for function arguments that use the same names as builtins.\n\n## Why is this bad?\nReusing a builtin name for the name of an argument increases the\ndifficulty of reading and maintaining the code, and can cause\nnon-obvious errors, as readers may mistake the argument for the\nbuiltin and vice versa.\n\nFunction definitions decorated with [`@override`][override] or\n[`@overload`][overload] are exempt from this rule by default.\nBuiltins can be marked as exceptions to this rule via the\n[`lint.flake8-builtins.ignorelist`] configuration option.\n\n## Example\n```python\ndef remove_duplicates(list, list2):\n result = set()\n for value in list:\n result.add(value)\n for value in list2:\n result.add(value)\n return list(result) # TypeError: 'list' object is not callable\n```\n\nUse instead:\n```python\ndef remove_duplicates(list1, list2):\n result = set()\n for value in list1:\n result.add(value)\n for value in list2:\n result.add(value)\n return list(result)\n```\n\n## Options\n- `lint.flake8-builtins.ignorelist`\n\n## References\n- [_Is it bad practice to use a built-in function name as an attribute or method identifier?_](https://stackoverflow.com/questions/9109333/is-it-bad-practice-to-use-a-built-in-function-name-as-an-attribute-or-method-ide)\n- [_Why is it a bad idea to name a variable `id` in Python?_](https://stackoverflow.com/questions/77552/id-is-a-bad-variable-name-in-python)\n\n[override]: https://docs.python.org/3/library/typing.html#typing.override\n[overload]: https://docs.python.org/3/library/typing.html#typing.overload\n",
|
|
178
|
+
"ruff/A003": "## What it does\nChecks for class attributes and methods that use the same names as\nPython builtins.\n\n## Why is this bad?\nReusing a builtin name for the name of an attribute increases the\ndifficulty of reading and maintaining the code, and can cause\nnon-obvious errors, as readers may mistake the attribute for the\nbuiltin and vice versa.\n\nSince methods and class attributes typically cannot be referenced directly\nfrom outside the class scope, this rule only applies to those methods\nand attributes that both shadow a builtin _and_ are referenced from within\nthe class scope, as in the following example, where the `list[int]` return\ntype annotation resolves to the `list` method, rather than the builtin:\n\n```python\nclass Class:\n @staticmethod\n def list() -> None:\n pass\n\n @staticmethod\n def repeat(value: int, times: int) -> list[int]:\n return [value] * times\n```\n\nBuiltins can be marked as exceptions to this rule via the\n[`lint.flake8-builtins.ignorelist`] configuration option, or\nconverted to the appropriate dunder method. Methods decorated with\n`@typing.override` or `@typing_extensions.override` are also\nignored.\n\n## Example\n```python\nclass Class:\n @staticmethod\n def list() -> None:\n pass\n\n @staticmethod\n def repeat(value: int, times: int) -> list[int]:\n return [value] * times\n```\n\n## Options\n- `lint.flake8-builtins.ignorelist`\n",
|
|
179
|
+
"ruff/A004": "## What it does\nChecks for imports that use the same names as builtins.\n\n## Why is this bad?\nReusing a builtin for the name of an import increases the difficulty\nof reading and maintaining the code, and can cause non-obvious errors,\nas readers may mistake the variable for the builtin and vice versa.\n\nBuiltins can be marked as exceptions to this rule via the\n[`lint.flake8-builtins.ignorelist`] configuration option.\n\n## Example\n```python\nfrom rich import print\n\nprint(\"Some message\")\n```\n\nUse instead:\n```python\nfrom rich import print as rich_print\n\nrich_print(\"Some message\")\n```\n\nor:\n```python\nimport rich\n\nrich.print(\"Some message\")\n```\n\n## Options\n- `lint.flake8-builtins.ignorelist`\n- `target-version`\n",
|
|
180
|
+
"ruff/A005": "## What it does\nChecks for modules that use the same names as Python standard-library\nmodules.\n\n## Why is this bad?\nReusing a standard-library module name for the name of a module increases\nthe difficulty of reading and maintaining the code, and can cause\nnon-obvious errors. Readers may mistake the first-party module for the\nstandard-library module and vice versa.\n\nStandard-library modules can be marked as exceptions to this rule via the\n[`lint.flake8-builtins.allowed-modules`] configuration option.\n\nBy default, the module path relative to the project root or [`src`] directories is considered,\nso a top-level `logging.py` or `logging/__init__.py` will clash with the builtin `logging`\nmodule, but `utils/logging.py`, for example, will not. With the\n[`lint.flake8-builtins.strict-checking`] option set to `true`, only the last component\nof the module name is considered, so `logging.py`, `utils/logging.py`, and\n`utils/logging/__init__.py` will all trigger the rule.\n\nThis rule is not applied to stub files, as the name of a stub module is out\nof the control of the author of the stub file. Instead, a stub should aim to\nfaithfully emulate the runtime module it is stubbing.\n\nAs of Python 3.13, errors from modules that use the same name as\nstandard-library modules now display a custom message.\n\n## Example\n\n```console\n$ touch random.py\n$ python3 -c 'from random import choice'\nTraceback (most recent call last):\n File \"<string>\", line 1, in <module>\n from random import choice\nImportError: cannot import name 'choice' from 'random' (consider renaming '/random.py' since it has the same name as the standard library module named 'random' and prevents importing that standard library module)\n```\n\n## Options\n- `lint.flake8-builtins.allowed-modules`\n- `lint.flake8-builtins.strict-checking`\n",
|
|
181
|
+
"ruff/A006": "## What it does\nChecks for lambda arguments that use the same names as Python builtins.\n\n## Why is this bad?\nReusing a builtin name for the name of a lambda argument increases the\ndifficulty of reading and maintaining the code and can cause\nnon-obvious errors. Readers may mistake the variable for the\nbuiltin, and vice versa.\n\nBuiltins can be marked as exceptions to this rule via the\n[`lint.flake8-builtins.ignorelist`] configuration option.\n\n## Options\n- `lint.flake8-builtins.ignorelist`\n",
|
|
182
|
+
"ruff/COM812": "## What it does\nChecks for the absence of trailing commas.\n\n## Why is this bad?\nThe presence of a trailing comma can reduce diff size when parameters or\nelements are added or removed from function calls, function definitions,\nliterals, etc.\n\n## Example\n```python\nfoo = {\n \"bar\": 1,\n \"baz\": 2\n}\n```\n\nUse instead:\n```python\nfoo = {\n \"bar\": 1,\n \"baz\": 2,\n}\n```\n\n## Formatter compatibility\nWe recommend against using this rule alongside the [formatter]. The\nformatter enforces consistent use of trailing commas, making the rule redundant.\n\n[formatter]:https://docs.astral.sh/ruff/formatter/\n",
|
|
183
|
+
"ruff/COM818": "## What it does\nChecks for the presence of trailing commas on bare (i.e., unparenthesized)\ntuples.\n\n## Why is this bad?\nThe presence of a misplaced comma will cause Python to interpret the value\nas a tuple, which can lead to unexpected behaviour.\n\n## Example\n```python\nimport json\n\n\nfoo = json.dumps({\"bar\": 1}),\n```\n\nUse instead:\n```python\nimport json\n\n\nfoo = json.dumps({\"bar\": 1})\n```\n\nIn the event that a tuple is intended, then use instead:\n```python\nimport json\n\n\nfoo = (json.dumps({\"bar\": 1}),)\n```\n",
|
|
184
|
+
"ruff/COM819": "## What it does\nChecks for the presence of prohibited trailing commas.\n\n## Why is this bad?\nTrailing commas are not essential in some cases and can therefore be viewed\nas unnecessary.\n\n## Example\n```python\nfoo = (1, 2, 3,)\n```\n\nUse instead:\n```python\nfoo = (1, 2, 3)\n```\n\n## Formatter compatibility\nWe recommend against using this rule alongside the [formatter]. With the\ndefault `format.skip-magic-trailing-comma = false`, trailing commas can be\nintentional: the formatter treats them as a signal to preserve multiline\nformatting. When set to `true`, the formatter removes those trailing commas\nwhere possible, making this rule redundant.\n\n[formatter]:https://docs.astral.sh/ruff/formatter/\n",
|
|
185
|
+
"ruff/C400": "## What it does\nChecks for unnecessary generators that can be rewritten as list\ncomprehensions (or with `list()` directly).\n\n## Why is this bad?\nIt is unnecessary to use `list()` around a generator expression, since\nthere are equivalent comprehensions for these types. Using a\ncomprehension is clearer and more idiomatic.\n\nFurther, if the comprehension can be removed entirely, as in the case of\n`list(x for x in foo)`, it's better to use `list(foo)` directly, since it's\neven more direct.\n\n## Example\n```python\nlist(f(x) for x in foo)\nlist(x for x in foo)\nlist((x for x in foo))\n```\n\nUse instead:\n```python\n[f(x) for x in foo]\nlist(foo)\nlist(foo)\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as it may occasionally drop comments\nwhen rewriting the call. In most cases, though, comments will be preserved.\n",
|
|
186
|
+
"ruff/C401": "## What it does\nChecks for unnecessary generators that can be rewritten as set\ncomprehensions (or with `set()` directly).\n\n## Why is this bad?\nIt is unnecessary to use `set` around a generator expression, since\nthere are equivalent comprehensions for these types. Using a\ncomprehension is clearer and more idiomatic.\n\nFurther, if the comprehension can be removed entirely, as in the case of\n`set(x for x in foo)`, it's better to use `set(foo)` directly, since it's\neven more direct.\n\n## Example\n```python\nset(f(x) for x in foo)\nset(x for x in foo)\nset((x for x in foo))\n```\n\nUse instead:\n```python\n{f(x) for x in foo}\nset(foo)\nset(foo)\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as it may occasionally drop comments\nwhen rewriting the call. In most cases, though, comments will be preserved.\n",
|
|
187
|
+
"ruff/C402": "## What it does\nChecks for unnecessary generators that can be rewritten as dict\ncomprehensions.\n\n## Why is this bad?\nIt is unnecessary to use `dict()` around a generator expression, since\nthere are equivalent comprehensions for these types. Using a\ncomprehension is clearer and more idiomatic.\n\n## Example\n```python\ndict((x, f(x)) for x in foo)\n```\n\nUse instead:\n```python\n{x: f(x) for x in foo}\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as it may occasionally drop comments\nwhen rewriting the call. In most cases, though, comments will be preserved.\n",
|
|
188
|
+
"ruff/C403": "## What it does\nChecks for unnecessary list comprehensions.\n\n## Why is this bad?\nIt's unnecessary to use a list comprehension inside a call to `set()`,\nsince there is an equivalent comprehension for this type.\n\n## Example\n```python\nset([f(x) for x in foo])\n```\n\nUse instead:\n```python\n{f(x) for x in foo}\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as it may occasionally drop comments\nwhen rewriting the call. In most cases, though, comments will be preserved.\n",
|
|
189
|
+
"ruff/C404": "## What it does\nChecks for unnecessary list comprehensions.\n\n## Why is this bad?\nIt's unnecessary to use a list comprehension inside a call to `dict()`,\nsince there is an equivalent comprehension for this type.\n\n## Example\n```python\ndict([(x, f(x)) for x in foo])\n```\n\nUse instead:\n```python\n{x: f(x) for x in foo}\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as it may occasionally drop comments\nwhen rewriting the call. In most cases, though, comments will be preserved.\n",
|
|
190
|
+
"ruff/C405": "## What it does\nChecks for `set()` calls that take unnecessary list or tuple literals\nas arguments.\n\n## Why is this bad?\nIt's unnecessary to use a list or tuple literal within a call to `set()`.\nInstead, the expression can be rewritten as a set literal.\n\n## Example\n```python\nset([1, 2])\nset((1, 2))\nset([])\n```\n\nUse instead:\n```python\n{1, 2}\n{1, 2}\nset()\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as it may occasionally drop comments\nwhen rewriting the call. In most cases, though, comments will be preserved.\n",
|
|
191
|
+
"ruff/C406": "## What it does\nChecks for unnecessary list or tuple literals.\n\n## Why is this bad?\nIt's unnecessary to use a list or tuple literal within a call to `dict()`.\nIt can be rewritten as a dict literal (`{}`).\n\n## Example\n```python\ndict([(1, 2), (3, 4)])\ndict(((1, 2), (3, 4)))\ndict([])\n```\n\nUse instead:\n```python\n{1: 2, 3: 4}\n{1: 2, 3: 4}\n{}\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as it may occasionally drop comments\nwhen rewriting the call. In most cases, though, comments will be preserved.\n",
|
|
192
|
+
"ruff/C408": "## What it does\nChecks for unnecessary `dict()`, `list()` or `tuple()` calls that can be\nrewritten as empty literals.\n\n## Why is this bad?\nIt's unnecessary to call, e.g., `dict()` as opposed to using an empty\nliteral (`{}`). The former is slower because the name `dict` must be\nlooked up in the global scope in case it has been rebound.\n\n## Example\n```python\ndict()\ndict(a=1, b=2)\nlist()\ntuple()\n```\n\nUse instead:\n```python\n{}\n{\"a\": 1, \"b\": 2}\n[]\n()\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as it may occasionally drop comments\nwhen rewriting the call. In most cases, though, comments will be preserved.\n\n## Options\n- `lint.flake8-comprehensions.allow-dict-calls-with-keyword-arguments`\n",
|
|
193
|
+
"ruff/C409": "## What it does\nChecks for `tuple` calls that take unnecessary list or tuple literals as\narguments.\n\n## Why is this bad?\nIt's unnecessary to use a list or tuple literal within a `tuple()` call,\nsince there is a literal syntax for these types.\n\nIf a list literal was passed, then it should be rewritten as a `tuple`\nliteral. Otherwise, if a tuple literal was passed, then the outer call\nto `tuple()` should be removed.\n\n## Example\n```python\ntuple([1, 2])\ntuple((1, 2))\n```\n\nUse instead:\n```python\n(1, 2)\n(1, 2)\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as it may occasionally drop comments\nwhen rewriting the call. In most cases, though, comments will be preserved.\n",
|
|
194
|
+
"ruff/C410": "## What it does\nChecks for `list()` calls that take unnecessary list or tuple literals as\narguments.\n\n## Why is this bad?\nIt's unnecessary to use a list or tuple literal within a `list()` call,\nsince there is a literal syntax for these types.\n\nIf a list literal is passed in, then the outer call to `list()` should be\nremoved. Otherwise, if a tuple literal is passed in, then it should be\nrewritten as a list literal.\n\n## Example\n```python\nlist([1, 2])\nlist((1, 2))\n```\n\nUse instead:\n```python\n[1, 2]\n[1, 2]\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as it may occasionally drop comments\nwhen rewriting the call. In most cases, though, comments will be preserved.\n",
|
|
195
|
+
"ruff/C411": "## What it does\nChecks for unnecessary `list()` calls around list comprehensions.\n\n## Why is this bad?\nIt is redundant to use a `list()` call around a list comprehension.\n\n## Example\n```python\nlist([f(x) for x in foo])\n```\n\nUse instead\n```python\n[f(x) for x in foo]\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as it may occasionally drop comments\nwhen rewriting the call. In most cases, though, comments will be preserved.\n",
|
|
196
|
+
"ruff/C413": "## What it does\nChecks for unnecessary `list()` or `reversed()` calls around `sorted()`\ncalls.\n\n## Why is this bad?\nIt is unnecessary to use `list()` around `sorted()`, as the latter already\nreturns a list.\n\nIt is also unnecessary to use `reversed()` around `sorted()`, as the latter\nhas a `reverse` argument that can be used in lieu of an additional\n`reversed()` call.\n\nIn both cases, it's clearer and more efficient to avoid the redundant call.\n\n## Example\n```python\nreversed(sorted(iterable))\n```\n\nUse instead:\n```python\nsorted(iterable, reverse=True)\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe for `reversed()` cases, as `reversed()`\nand `reverse=True` will yield different results in the event of custom sort\nkeys or equality functions. Specifically, `reversed()` will reverse the order\nof the collection, while `sorted()` with `reverse=True` will perform a stable\nreverse sort, which will preserve the order of elements that compare as\nequal.\n\nThe fix is marked as safe for `list()` cases, as removing `list()` around\n`sorted()` does not change the behavior.\n",
|
|
197
|
+
"ruff/C414": "## What it does\nChecks for unnecessary `list()`, `reversed()`, `set()`, `sorted()`, and\n`tuple()` call within `list()`, `set()`, `sorted()`, and `tuple()` calls.\n\n## Why is this bad?\nIt's unnecessary to double-cast or double-process iterables by wrapping\nthe listed functions within an additional `list()`, `set()`, `sorted()`, or\n`tuple()` call. Doing so is redundant and can be confusing for readers.\n\n## Example\n```python\nlist(tuple(iterable))\n```\n\nUse instead:\n```python\nlist(iterable)\n```\n\nThis rule applies to a variety of functions, including `list()`, `reversed()`,\n`set()`, `sorted()`, and `tuple()`. For example:\n\n- Instead of `list(list(iterable))`, use `list(iterable)`.\n- Instead of `list(tuple(iterable))`, use `list(iterable)`.\n- Instead of `tuple(list(iterable))`, use `tuple(iterable)`.\n- Instead of `tuple(tuple(iterable))`, use `tuple(iterable)`.\n- Instead of `set(set(iterable))`, use `set(iterable)`.\n- Instead of `set(list(iterable))`, use `set(iterable)`.\n- Instead of `set(tuple(iterable))`, use `set(iterable)`.\n- Instead of `set(sorted(iterable))`, use `set(iterable)`.\n- Instead of `set(reversed(iterable))`, use `set(iterable)`.\n- Instead of `sorted(list(iterable))`, use `sorted(iterable)`.\n- Instead of `sorted(tuple(iterable))`, use `sorted(iterable)`.\n- Instead of `sorted(sorted(iterable))`, use `sorted(iterable)`.\n- Instead of `sorted(reversed(iterable))`, use `sorted(iterable)`.\n\n## Fix safety\nThis rule's fix is marked as unsafe, as it may occasionally drop comments\nwhen rewriting the call. In most cases, though, comments will be preserved.\n",
|
|
198
|
+
"ruff/C415": "## What it does\nChecks for unnecessary subscript reversal of iterable.\n\n## Why is this bad?\nIt's unnecessary to reverse the order of an iterable when passing it\ninto `reversed()`, `set()` or `sorted()` functions as they will change\nthe order of the elements again.\n\n## Example\n```python\nsorted(iterable[::-1])\nset(iterable[::-1])\nreversed(iterable[::-1])\n```\n\nUse instead:\n```python\nsorted(iterable)\nset(iterable)\niterable\n```\n",
|
|
199
|
+
"ruff/C416": "## What it does\nChecks for unnecessary dict, list, and set comprehension.\n\n## Why is this bad?\nIt's unnecessary to use a dict/list/set comprehension to build a data structure if the\nelements are unchanged. Wrap the iterable with `dict()`, `list()`, or `set()` instead.\n\n## Example\n```python\n{a: b for a, b in iterable}\n[x for x in iterable]\n{x for x in iterable}\n```\n\nUse instead:\n```python\ndict(iterable)\nlist(iterable)\nset(iterable)\n```\n\n## Known problems\n\nThis rule may produce false positives for dictionary comprehensions that iterate over a mapping.\nThe dict constructor behaves differently depending on if it receives a sequence (e.g., a\nlist) or a mapping (e.g., a dict). When a comprehension iterates over the keys of a mapping,\nreplacing it with a `dict()` constructor call will give a different result.\n\nFor example:\n\n```pycon\n>>> d1 = {(1, 2): 3, (4, 5): 6}\n>>> {x: y for x, y in d1} # Iterates over the keys of a mapping\n{1: 2, 4: 5}\n>>> dict(d1) # Ruff's incorrect suggested fix\n{(1, 2): 3, (4, 5): 6}\n>>> dict(d1.keys()) # Correct fix\n{1: 2, 4: 5}\n```\n\nWhen the comprehension iterates over a sequence, Ruff's suggested fix is correct. However, Ruff\ncannot consistently infer if the iterable type is a sequence or a mapping and cannot suggest\nthe correct fix for mappings.\n\nAdditionally, rewriting comprehensions inside an object's `__len__` method may cause a\n`RecursionError`, as collection constructors can call back into `__len__`.\n\n## Fix safety\nThis rule's fix is always marked as unsafe because of the known problems described above and\nbecause comments may be dropped when rewriting the comprehension.\n",
|
|
200
|
+
"ruff/C417": "## What it does\nChecks for unnecessary `map()` calls with lambda functions.\n\n## Why is this bad?\nUsing `map(func, iterable)` when `func` is a lambda is slower than\nusing a generator expression or a comprehension, as the latter approach\navoids the function call overhead, in addition to being more readable.\n\nThis rule also applies to `map()` calls within `list()`, `set()`, and\n`dict()` calls. For example:\n\n- Instead of `list(map(lambda num: num * 2, nums))`, use\n `[num * 2 for num in nums]`.\n- Instead of `set(map(lambda num: num % 2 == 0, nums))`, use\n `{num % 2 == 0 for num in nums}`.\n- Instead of `dict(map(lambda v: (v, v ** 2), values))`, use\n `{v: v ** 2 for v in values}`.\n\n## Example\n```python\nmap(lambda x: x + 1, iterable)\n```\n\nUse instead:\n```python\n(x + 1 for x in iterable)\n```\n\n## Known problems\nA `map` object and a generator expression are not interchangeable when the\nmapped expression raises. Once an exception propagates out of a generator,\nthe generator is closed, so every later `next()` call raises\n`StopIteration`. A `map` object is not closed, so iteration can resume after\nthe error:\n\n```python\nvalues = [\"0\", \"x\", \"2\"]\n\nm = map(lambda v: int(v), values)\nnext(m) # 0\nnext(m) # raises ValueError\nnext(m) # 2\n\ng = (int(v) for v in values)\nnext(g) # 0\nnext(g) # raises ValueError\nnext(g) # raises StopIteration\n```\n\nRuff cannot tell whether a caller relies on this difference, so the\ndiagnostic is still reported in such cases.\n\n## Fix safety\nThis rule's fix is marked as unsafe because it can change how errors propagate\nout of the resulting iterator, as described above. It may also drop comments\nwhen rewriting the call.\n",
|
|
201
|
+
"ruff/C418": "## What it does\nChecks for `dict()` calls that take unnecessary dict literals or dict\ncomprehensions as arguments.\n\n## Why is this bad?\nIt's unnecessary to wrap a dict literal or comprehension within a `dict()`\ncall, since the literal or comprehension syntax already returns a\ndictionary.\n\n## Example\n```python\ndict({})\ndict({\"a\": 1})\n```\n\nUse instead:\n```python\n{}\n{\"a\": 1}\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as it may occasionally drop comments\nwhen rewriting the call. In most cases, though, comments will be preserved.\n",
|
|
202
|
+
"ruff/C419": "## What it does\nChecks for unnecessary list or set comprehensions passed to builtin functions that take an iterable.\n\nSet comprehensions are only a violation in the case where the builtin function does not care about\nduplication of elements in the passed iterable.\n\n## Why is this bad?\nMany builtin functions (this rule currently covers `any` and `all` in stable, along with `min`,\n`max`, and `sum` in [preview]) accept any iterable, including a generator. Constructing a\ntemporary list via list comprehension is unnecessary and wastes memory for large iterables.\n\n`any` and `all` can also short-circuit iteration, saving a lot of time. The unnecessary\ncomprehension forces a full iteration of the input iterable, giving up the benefits of\nshort-circuiting. For example, compare the performance of `all` with a list comprehension\nagainst that of a generator in a case where an early short-circuit is possible (almost 40x\nfaster):\n\n```console\nIn [1]: %timeit all([i for i in range(1000)])\n8.14 \u00b5s \u00b1 25.4 ns per loop (mean \u00b1 std. dev. of 7 runs, 100,000 loops each)\n\nIn [2]: %timeit all(i for i in range(1000))\n212 ns \u00b1 0.892 ns per loop (mean \u00b1 std. dev. of 7 runs, 1,000,000 loops each)\n```\n\nThis performance improvement is due to short-circuiting. If the entire iterable has to be\ntraversed, the comprehension version may even be a bit faster: list allocation overhead is not\nnecessarily greater than generator overhead.\n\nApplying this rule simplifies the code and will usually save memory, but in the absence of\nshort-circuiting it may not improve performance. (It may even slightly regress performance,\nthough the difference will usually be small.)\n\n## Example\n```python\nany([x.id for x in bar])\nall([x.id for x in bar])\nsum([x.val for x in bar])\nmin([x.val for x in bar])\nmax([x.val for x in bar])\n```\n\nUse instead:\n```python\nany(x.id for x in bar)\nall(x.id for x in bar)\nsum(x.val for x in bar)\nmin(x.val for x in bar)\nmax(x.val for x in bar)\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as it can change the behavior of the code if the iteration\nhas side effects (due to laziness and short-circuiting). The fix may also drop comments when\nrewriting some comprehensions.\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
203
|
+
"ruff/C420": "## What it does\nChecks for unnecessary dict comprehension when creating a dictionary from\nan iterable.\n\n## Why is this bad?\nIt's unnecessary to use a dict comprehension to build a dictionary from\nan iterable when the value is static.\n\nPrefer `dict.fromkeys(iterable)` over `{value: None for value in iterable}`,\nas `dict.fromkeys` is more readable and efficient.\n\n## Example\n```python\n{a: None for a in iterable}\n{a: 1 for a in iterable}\n```\n\nUse instead:\n```python\ndict.fromkeys(iterable)\ndict.fromkeys(iterable, 1)\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe if there's comments inside the dict comprehension,\nas comments may be removed.\n\nFor example, the fix would be marked as unsafe in the following case:\n```python\n{ # comment 1\n a: # comment 2\n None # comment 3\n for a in iterable # comment 4\n}\n```\n\n## References\n- [Python documentation: `dict.fromkeys`](https://docs.python.org/3/library/stdtypes.html#dict.fromkeys)\n",
|
|
204
|
+
"ruff/CPY001": "## What it does\nChecks for the absence of copyright notices within Python files.\n\nNote that this check only searches within the first 4096 bytes of the file.\n\n## Why is this bad?\nIn some codebases, it's common to have a license header at the top of every\nfile. This rule ensures that the license header is present.\n\n## Options\n- `lint.flake8-copyright.author`\n- `lint.flake8-copyright.min-file-size`\n- `lint.flake8-copyright.notice-rgx`\n",
|
|
205
|
+
"ruff/DTZ001": "## What it does\nChecks for `datetime` instantiations that do not specify a timezone.\n\n## Why is this bad?\n`datetime` objects are \"naive\" by default, in that they do not include\ntimezone information. \"Naive\" objects are easy to understand, but ignore\nsome aspects of reality, which can lead to subtle bugs. Timezone-aware\n`datetime` objects are preferred, as they represent a specific moment in\ntime, unlike \"naive\" objects.\n\nBy providing a non-`None` value for `tzinfo`, a `datetime` can be made\ntimezone-aware.\n\n## Example\n```python\nimport datetime\n\ndatetime.datetime(2000, 1, 1, 0, 0, 0)\n```\n\nUse instead:\n```python\nimport datetime\n\ndatetime.datetime(2000, 1, 1, 0, 0, 0, tzinfo=datetime.timezone.utc)\n```\n\nOr, on Python 3.11 and later:\n```python\nimport datetime\n\ndatetime.datetime(2000, 1, 1, 0, 0, 0, tzinfo=datetime.UTC)\n```\n\n## References\n- [Python documentation: Aware and Naive Objects](https://docs.python.org/3/library/datetime.html#aware-and-naive-objects)\n",
|
|
206
|
+
"ruff/DTZ002": "## What it does\nChecks for usage of `datetime.datetime.today()`.\n\n## Why is this bad?\n`datetime` objects are \"naive\" by default, in that they do not include\ntimezone information. \"Naive\" objects are easy to understand, but ignore\nsome aspects of reality, which can lead to subtle bugs. Timezone-aware\n`datetime` objects are preferred, as they represent a specific moment in\ntime, unlike \"naive\" objects.\n\n`datetime.datetime.today()` creates a \"naive\" object; instead, use\n`datetime.datetime.now(tz=...)` to create a timezone-aware object.\n\nThe name `today()` can be misleading, because it suggests a calendar date,\nbut it actually returns the current local date and time as a `datetime`.\nThat can make intent harder to infer when reading code.\n\n## Example\n```python\nimport datetime\n\ndatetime.datetime.today()\n```\n\nUse instead:\n```python\nimport datetime\n\ndatetime.datetime.now(tz=datetime.timezone.utc)\n```\n\nOr, for Python 3.11 and later:\n```python\nimport datetime\n\ndatetime.datetime.now(tz=datetime.UTC)\n```\n\n## References\n- [Python documentation: Aware and Naive Objects](https://docs.python.org/3/library/datetime.html#aware-and-naive-objects)\n",
|
|
207
|
+
"ruff/DTZ003": "## What it does\nChecks for usage of `datetime.datetime.utcnow()`.\n\n## Why is this bad?\nPython datetime objects can be naive or timezone-aware. While an aware\nobject represents a specific moment in time, a naive object does not\ncontain enough information to unambiguously locate itself relative to other\ndatetime objects. Since this can lead to errors, it is recommended to\nalways use timezone-aware objects.\n\n`datetime.datetime.utcnow()` returns a naive datetime object; instead, use\n`datetime.datetime.now(tz=...)` to create a timezone-aware object.\n\n## Example\n```python\nimport datetime\n\ndatetime.datetime.utcnow()\n```\n\nUse instead:\n```python\nimport datetime\n\ndatetime.datetime.now(tz=datetime.timezone.utc)\n```\n\nOr, for Python 3.11 and later:\n```python\nimport datetime\n\ndatetime.datetime.now(tz=datetime.UTC)\n```\n\n## References\n- [Python documentation: Aware and Naive Objects](https://docs.python.org/3/library/datetime.html#aware-and-naive-objects)\n",
|
|
208
|
+
"ruff/DTZ004": "## What it does\nChecks for usage of `datetime.datetime.utcfromtimestamp()`.\n\n## Why is this bad?\nPython datetime objects can be naive or timezone-aware. While an aware\nobject represents a specific moment in time, a naive object does not\ncontain enough information to unambiguously locate itself relative to other\ndatetime objects. Since this can lead to errors, it is recommended to\nalways use timezone-aware objects.\n\n`datetime.datetime.utcfromtimestamp()` returns a naive datetime\nobject; instead, use `datetime.datetime.fromtimestamp(ts, tz=...)`\nto create a timezone-aware object.\n\n## Example\n```python\nimport datetime\n\ndatetime.datetime.utcfromtimestamp(946684800)\n```\n\nUse instead:\n```python\nimport datetime\n\ndatetime.datetime.fromtimestamp(946684800, tz=datetime.timezone.utc)\n```\n\nOr, on Python 3.11 and later:\n```python\nimport datetime\n\ndatetime.datetime.fromtimestamp(946684800, tz=datetime.UTC)\n```\n\n## References\n- [Python documentation: Aware and Naive Objects](https://docs.python.org/3/library/datetime.html#aware-and-naive-objects)\n",
|
|
209
|
+
"ruff/DTZ005": "## What it does\nChecks for usages of `datetime.datetime.now()` that do not specify a timezone.\n\n## Why is this bad?\nPython datetime objects can be naive or timezone-aware. While an aware\nobject represents a specific moment in time, a naive object does not\ncontain enough information to unambiguously locate itself relative to other\ndatetime objects. Since this can lead to errors, it is recommended to\nalways use timezone-aware objects.\n\n`datetime.datetime.now()` or `datetime.datetime.now(tz=None)` returns a naive\ndatetime object. Instead, use `datetime.datetime.now(tz=<timezone>)` to create\na timezone-aware object.\n\n## Example\n```python\nimport datetime\n\ndatetime.datetime.now()\n```\n\nUse instead:\n```python\nimport datetime\n\ndatetime.datetime.now(tz=datetime.timezone.utc)\n```\n\nOr, for Python 3.11 and later:\n```python\nimport datetime\n\ndatetime.datetime.now(tz=datetime.UTC)\n```\n\n## References\n- [Python documentation: Aware and Naive Objects](https://docs.python.org/3/library/datetime.html#aware-and-naive-objects)\n",
|
|
210
|
+
"ruff/DTZ006": "## What it does\nChecks for usage of `datetime.datetime.fromtimestamp()` that do not specify\na timezone.\n\n## Why is this bad?\nPython datetime objects can be naive or timezone-aware. While an aware\nobject represents a specific moment in time, a naive object does not\ncontain enough information to unambiguously locate itself relative to other\ndatetime objects. Since this can lead to errors, it is recommended to\nalways use timezone-aware objects.\n\n`datetime.datetime.fromtimestamp(ts)` or\n`datetime.datetime.fromtimestamp(ts, tz=None)` returns a naive datetime\nobject. Instead, use `datetime.datetime.fromtimestamp(ts, tz=<timezone>)`\nto create a timezone-aware object.\n\n## Example\n```python\nimport datetime\n\ndatetime.datetime.fromtimestamp(946684800)\n```\n\nUse instead:\n```python\nimport datetime\n\ndatetime.datetime.fromtimestamp(946684800, tz=datetime.timezone.utc)\n```\n\nOr, on Python 3.11 and later:\n```python\nimport datetime\n\ndatetime.datetime.fromtimestamp(946684800, tz=datetime.UTC)\n```\n\n## References\n- [Python documentation: Aware and Naive Objects](https://docs.python.org/3/library/datetime.html#aware-and-naive-objects)\n",
|
|
211
|
+
"ruff/DTZ007": "## What it does\nChecks for uses of `datetime.datetime.strptime()` that lead to naive\ndatetime objects.\n\n## Why is this bad?\nPython datetime objects can be naive or timezone-aware. While an aware\nobject represents a specific moment in time, a naive object does not\ncontain enough information to unambiguously locate itself relative to other\ndatetime objects. Since this can lead to errors, it is recommended to\nalways use timezone-aware objects.\n\n`datetime.datetime.strptime()` without `%z` returns a naive datetime\nobject. Follow it with `.replace(tzinfo=<timezone>)` or `.astimezone()`.\n\n## Example\n```python\nimport datetime\n\ndatetime.datetime.strptime(\"2022/01/31\", \"%Y/%m/%d\")\n```\n\nInstead, use `.replace(tzinfo=<timezone>)`:\n```python\nimport datetime\n\ndatetime.datetime.strptime(\"2022/01/31\", \"%Y/%m/%d\").replace(\n tzinfo=datetime.timezone.utc\n)\n```\n\nOr, use `.astimezone()`:\n```python\nimport datetime\n\ndatetime.datetime.strptime(\"2022/01/31\", \"%Y/%m/%d\").astimezone(datetime.timezone.utc)\n```\n\nOn Python 3.11 and later, `datetime.timezone.utc` can be replaced with\n`datetime.UTC`.\n\n## References\n- [Python documentation: Aware and Naive Objects](https://docs.python.org/3/library/datetime.html#aware-and-naive-objects)\n- [Python documentation: `strftime()` and `strptime()` Behavior](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior)\n",
|
|
212
|
+
"ruff/DTZ011": "## What it does\nChecks for usage of `datetime.date.today()`.\n\n## Why is this bad?\nPython date objects are naive, that is, not timezone-aware. While an aware\nobject represents a specific moment in time, a naive object does not\ncontain enough information to unambiguously locate itself relative to other\ndatetime objects. Since this can lead to errors, it is recommended to\nalways use timezone-aware objects.\n\n`datetime.date.today` returns a naive date object without taking timezones\ninto account. Instead, use `datetime.datetime.now(tz=...).date()` to\ncreate a timezone-aware object and retrieve its date component.\n\n## Example\n```python\nimport datetime\n\ndatetime.date.today()\n```\n\nUse instead:\n```python\nimport datetime\n\ndatetime.datetime.now(tz=datetime.timezone.utc).date()\n```\n\nOr, for Python 3.11 and later:\n```python\nimport datetime\n\ndatetime.datetime.now(tz=datetime.UTC).date()\n```\n\n## References\n- [Python documentation: Aware and Naive Objects](https://docs.python.org/3/library/datetime.html#aware-and-naive-objects)\n",
|
|
213
|
+
"ruff/DTZ012": "## What it does\nChecks for usage of `datetime.date.fromtimestamp()`.\n\n## Why is this bad?\nPython date objects are naive, that is, not timezone-aware. While an aware\nobject represents a specific moment in time, a naive object does not\ncontain enough information to unambiguously locate itself relative to other\ndatetime objects. Since this can lead to errors, it is recommended to\nalways use timezone-aware objects.\n\n`datetime.date.fromtimestamp(ts)` returns a naive date object.\nInstead, use `datetime.datetime.fromtimestamp(ts, tz=...).date()` to\ncreate a timezone-aware datetime object and retrieve its date component.\n\n## Example\n```python\nimport datetime\n\ndatetime.date.fromtimestamp(946684800)\n```\n\nUse instead:\n```python\nimport datetime\n\ndatetime.datetime.fromtimestamp(946684800, tz=datetime.timezone.utc).date()\n```\n\nOr, for Python 3.11 and later:\n```python\nimport datetime\n\ndatetime.datetime.fromtimestamp(946684800, tz=datetime.UTC).date()\n```\n\n## References\n- [Python documentation: Aware and Naive Objects](https://docs.python.org/3/library/datetime.html#aware-and-naive-objects)\n",
|
|
214
|
+
"ruff/DTZ901": "## What it does\nChecks for uses of `datetime.datetime.min` and `datetime.datetime.max`.\n\n## Why is this bad?\n`datetime.min` and `datetime.max` are non-timezone-aware datetime objects.\n\nAs such, operations on `datetime.min` and `datetime.max` may behave\nunexpectedly, as in:\n\n```python\nimport datetime\n\n# Timezone: UTC-14\ndatetime.datetime.min.timestamp() # ValueError: year 0 is out of range\ndatetime.datetime.max.timestamp() # ValueError: year 10000 is out of range\n```\n\n## Example\n```python\nimport datetime\n\ndatetime.datetime.max\n```\n\nUse instead:\n```python\nimport datetime\n\ndatetime.datetime.max.replace(tzinfo=datetime.UTC)\n```\n\n## References\n- [Python documentation: Aware and Naive Objects](https://docs.python.org/3/library/datetime.html#aware-and-naive-objects)\n",
|
|
215
|
+
"ruff/T100": "## What it does\nChecks for the presence of debugger calls and imports.\n\n## Why is this bad?\nDebugger calls and imports should be used for debugging purposes only. The\npresence of a debugger call or import in production code is likely a\nmistake and may cause unintended behavior, such as exposing sensitive\ninformation or causing the program to hang.\n\nInstead, consider using a logging library to log information about the\nprogram's state, and writing tests to verify that the program behaves\nas expected.\n\n## Example\n```python\ndef foo():\n breakpoint()\n```\n\n## References\n- [Python documentation: `pdb` \u2014 The Python Debugger](https://docs.python.org/3/library/pdb.html)\n- [Python documentation: `logging` \u2014 Logging facility for Python](https://docs.python.org/3/library/logging.html)\n",
|
|
216
|
+
"ruff/DJ001": "## What it does\nChecks nullable string-based fields (like `CharField` and `TextField`)\nin Django models.\n\n## Why is this bad?\nIf a string-based field is nullable, then your model will have two possible\nrepresentations for \"no data\": `None` and the empty string. This can lead to\nconfusion, as clients of the API have to check for both `None` and the\nempty string when trying to determine if the field has data.\n\nThe Django convention is to use the empty string in lieu of `None` for\nstring-based fields.\n\n## Example\n```python\nfrom django.db import models\n\n\nclass MyModel(models.Model):\n field = models.CharField(max_length=255, null=True)\n```\n\nUse instead:\n```python\nfrom django.db import models\n\n\nclass MyModel(models.Model):\n field = models.CharField(max_length=255, default=\"\")\n```\n",
|
|
217
|
+
"ruff/DJ003": "## What it does\nChecks for the use of `locals()` in `render` functions.\n\n## Why is this bad?\nUsing `locals()` can expose internal variables or other unintentional\ndata to the rendered template.\n\n## Example\n```python\nfrom django.shortcuts import render\n\n\ndef index(request):\n posts = Post.objects.all()\n return render(request, \"app/index.html\", locals())\n```\n\nUse instead:\n```python\nfrom django.shortcuts import render\n\n\ndef index(request):\n posts = Post.objects.all()\n context = {\"posts\": posts}\n return render(request, \"app/index.html\", context)\n```\n",
|
|
218
|
+
"ruff/DJ006": "## What it does\nChecks for the use of `exclude` in Django `ModelForm` classes.\n\n## Why is this bad?\nIf a `ModelForm` includes the `exclude` attribute, any new field that\nis added to the model will automatically be exposed for modification.\n\n## Example\n```python\nfrom django.forms import ModelForm\n\n\nclass PostForm(ModelForm):\n class Meta:\n model = Post\n exclude = [\"author\"]\n```\n\nUse instead:\n```python\nfrom django.forms import ModelForm\n\n\nclass PostForm(ModelForm):\n class Meta:\n model = Post\n fields = [\"title\", \"content\"]\n```\n",
|
|
219
|
+
"ruff/DJ007": "## What it does\nChecks for the use of `fields = \"__all__\"` in Django `ModelForm`\nclasses.\n\n## Why is this bad?\nIf a `ModelForm` includes the `fields = \"__all__\"` attribute, any new\nfield that is added to the model will automatically be exposed for\nmodification.\n\n## Example\n```python\nfrom django.forms import ModelForm\n\n\nclass PostForm(ModelForm):\n class Meta:\n model = Post\n fields = \"__all__\"\n```\n\nUse instead:\n```python\nfrom django.forms import ModelForm\n\n\nclass PostForm(ModelForm):\n class Meta:\n model = Post\n fields = [\"title\", \"content\"]\n```\n",
|
|
220
|
+
"ruff/DJ008": "## What it does\nChecks that a `__str__` method is defined in Django models.\n\n## Why is this bad?\nDjango models should define a `__str__` method to return a string representation\nof the model instance, as Django calls this method to display the object in\nthe Django Admin and elsewhere.\n\nModels without a `__str__` method will display a non-meaningful representation\nof the object in the Django Admin.\n\n## Example\n```python\nfrom django.db import models\n\n\nclass MyModel(models.Model):\n field = models.CharField(max_length=255)\n```\n\nUse instead:\n```python\nfrom django.db import models\n\n\nclass MyModel(models.Model):\n field = models.CharField(max_length=255)\n\n def __str__(self):\n return f\"{self.field}\"\n```\n",
|
|
221
|
+
"ruff/DJ012": "## What it does\nChecks for the order of Model's inner classes, methods, and fields as per\nthe [Django Style Guide].\n\n## Why is this bad?\nThe [Django Style Guide] specifies that the order of Model inner classes,\nattributes and methods should be as follows:\n\n1. All database fields\n2. Custom manager attributes\n3. `class Meta`\n4. `def __str__()`\n5. `def save()`\n6. `def get_absolute_url()`\n7. Any custom methods\n\n## Example\n```python\nfrom django.db import models\n\n\nclass StrBeforeFieldModel(models.Model):\n class Meta:\n verbose_name = \"test\"\n verbose_name_plural = \"tests\"\n\n def __str__(self):\n return \"foobar\"\n\n first_name = models.CharField(max_length=32)\n last_name = models.CharField(max_length=40)\n```\n\nUse instead:\n```python\nfrom django.db import models\n\n\nclass StrBeforeFieldModel(models.Model):\n first_name = models.CharField(max_length=32)\n last_name = models.CharField(max_length=40)\n\n class Meta:\n verbose_name = \"test\"\n verbose_name_plural = \"tests\"\n\n def __str__(self):\n return \"foobar\"\n```\n\n[Django Style Guide]: https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/coding-style/#model-style\n",
|
|
222
|
+
"ruff/DJ013": "## What it does\nChecks that Django's `@receiver` decorator is listed first, prior to\nany other decorators.\n\n## Why is this bad?\nDjango's `@receiver` decorator is special in that it does not return\na wrapped function. Rather, `@receiver` connects the decorated function\nto a signal. If any other decorators are listed before `@receiver`,\nthe decorated function will not be connected to the signal.\n\n## Example\n```python\nfrom django.dispatch import receiver\nfrom django.db.models.signals import post_save\n\n\n@transaction.atomic\n@receiver(post_save, sender=MyModel)\ndef my_handler(sender, instance, created, **kwargs):\n pass\n```\n\nUse instead:\n```python\nfrom django.dispatch import receiver\nfrom django.db.models.signals import post_save\n\n\n@receiver(post_save, sender=MyModel)\n@transaction.atomic\ndef my_handler(sender, instance, created, **kwargs):\n pass\n```\n",
|
|
223
|
+
"ruff/EM101": "## What it does\nChecks for the use of string literals in exception constructors.\n\n## Why is this bad?\nPython includes the `raise` in the default traceback (and formatters\nlike Rich and IPython do too).\n\nBy using a string literal, the error message will be duplicated in the\ntraceback, which can make the traceback less readable.\n\n## Example\nGiven:\n```python\nraise RuntimeError(\"'Some value' is incorrect\")\n```\n\nPython will produce a traceback like:\n```console\nTraceback (most recent call last):\n File \"tmp.py\", line 2, in <module>\n raise RuntimeError(\"'Some value' is incorrect\")\nRuntimeError: 'Some value' is incorrect\n```\n\nInstead, assign the string to a variable:\n```python\nmsg = \"'Some value' is incorrect\"\nraise RuntimeError(msg)\n```\n\nWhich will produce a traceback like:\n```console\nTraceback (most recent call last):\n File \"tmp.py\", line 3, in <module>\n raise RuntimeError(msg)\nRuntimeError: 'Some value' is incorrect\n```\n\n## Options\n\n- `lint.flake8-errmsg.max-string-length`\n",
|
|
224
|
+
"ruff/EM102": "## What it does\nChecks for the use of f-strings in exception constructors.\n\n## Why is this bad?\nPython includes the `raise` in the default traceback (and formatters\nlike Rich and IPython do too).\n\nBy using an f-string, the error message will be duplicated in the\ntraceback, which can make the traceback less readable.\n\n## Example\nGiven:\n```python\nsub = \"Some value\"\nraise RuntimeError(f\"{sub!r} is incorrect\")\n```\n\nPython will produce a traceback like:\n```console\nTraceback (most recent call last):\n File \"tmp.py\", line 2, in <module>\n raise RuntimeError(f\"{sub!r} is incorrect\")\nRuntimeError: 'Some value' is incorrect\n```\n\nInstead, assign the string to a variable:\n```python\nsub = \"Some value\"\nmsg = f\"{sub!r} is incorrect\"\nraise RuntimeError(msg)\n```\n\nWhich will produce a traceback like:\n```console\nTraceback (most recent call last):\n File \"tmp.py\", line 3, in <module>\n raise RuntimeError(msg)\nRuntimeError: 'Some value' is incorrect\n```\n",
|
|
225
|
+
"ruff/EM103": "## What it does\nChecks for the use of `.format` calls on string literals in exception\nconstructors.\n\n## Why is this bad?\nPython includes the `raise` in the default traceback (and formatters\nlike Rich and IPython do too).\n\nBy using a `.format` call, the error message will be duplicated in the\ntraceback, which can make the traceback less readable.\n\n## Example\nGiven:\n```python\nsub = \"Some value\"\nraise RuntimeError(\"'{}' is incorrect\".format(sub))\n```\n\nPython will produce a traceback like:\n```console\nTraceback (most recent call last):\n File \"tmp.py\", line 2, in <module>\n raise RuntimeError(\"'{}' is incorrect\".format(sub))\nRuntimeError: 'Some value' is incorrect\n```\n\nInstead, assign the string to a variable:\n```python\nsub = \"Some value\"\nmsg = \"'{}' is incorrect\".format(sub)\nraise RuntimeError(msg)\n```\n\nWhich will produce a traceback like:\n```console\nTraceback (most recent call last):\n File \"tmp.py\", line 3, in <module>\n raise RuntimeError(msg)\nRuntimeError: 'Some value' is incorrect\n```\n",
|
|
226
|
+
"ruff/EXE001": "## What it does\nChecks for a shebang directive in a file that is not executable.\n\n## Why is this bad?\nIn Python, a shebang (also known as a hashbang) is the first line of a\nscript, which specifies the interpreter that should be used to run the\nscript.\n\nThe presence of a shebang suggests that a file is intended to be\nexecutable. If a file contains a shebang but is not executable, then the\nshebang is misleading, or the file is missing the executable bit.\n\nIf the file is meant to be executable, add the executable bit to the file\n(e.g., `chmod +x __main__.py` or `git update-index --chmod=+x __main__.py`).\n\nOtherwise, remove the shebang.\n\nA file is considered executable if it has the executable bit set (i.e., its\npermissions mode intersects with `0o111`). As such, _this rule is only\navailable on Unix-like systems_, and is not enforced on Windows or WSL.\n\n## Example\n```python\n#!/usr/bin/env python\n```\n\n## References\n- [Python documentation: Executable Python Scripts](https://docs.python.org/3/tutorial/appendix.html#executable-python-scripts)\n- [Git documentation: `git update-index --chmod`](https://git-scm.com/docs/git-update-index#Documentation/git-update-index.txt---chmod-x)\n",
|
|
227
|
+
"ruff/EXE002": "## What it does\nChecks for executable `.py` files that do not have a shebang.\n\n## Why is this bad?\nIn Python, a shebang (also known as a hashbang) is the first line of a\nscript, which specifies the interpreter that should be used to run the\nscript.\n\nIf a `.py` file is executable, but does not have a shebang, it may be run\nwith the wrong interpreter, or fail to run at all.\n\nIf the file is meant to be executable, add a shebang, as in:\n```python\n#!/usr/bin/env python\n```\n\nOtherwise, remove the executable bit from the file\n(e.g., `chmod -x __main__.py` or `git update-index --chmod=-x __main__.py`).\n\nA file is considered executable if it has the executable bit set (i.e., its\npermissions mode intersects with `0o111`). As such, _this rule is only\navailable on Unix-like systems_, and is not enforced on Windows or WSL.\n\n## References\n- [Python documentation: Executable Python Scripts](https://docs.python.org/3/tutorial/appendix.html#executable-python-scripts)\n- [Git documentation: `git update-index --chmod`](https://git-scm.com/docs/git-update-index#Documentation/git-update-index.txt---chmod-x)\n",
|
|
228
|
+
"ruff/EXE003": "## What it does\nChecks for a shebang directive in `.py` files that does not contain `python`,\n`pytest`, or `uv run`.\n\n## Why is this bad?\nIn Python, a shebang (also known as a hashbang) is the first line of a\nscript, which specifies the command that should be used to run the\nscript.\n\nFor Python scripts, if the shebang does not include a command that explicitly\nor implicitly specifies an interpreter, then the file will be executed with\nthe default interpreter, which is likely a mistake.\n\n## Example\n```python\n#!/usr/bin/env bash\n```\n\nUse instead:\n```python\n#!/usr/bin/env python3\n```\n\n## References\n- [Python documentation: Executable Python Scripts](https://docs.python.org/3/tutorial/appendix.html#executable-python-scripts)\n",
|
|
229
|
+
"ruff/EXE004": "## What it does\nChecks for whitespace before a shebang directive.\n\n## Why is this bad?\nIn Python, a shebang (also known as a hashbang) is the first line of a\nscript, which specifies the interpreter that should be used to run the\nscript.\n\nThe shebang's `#!` prefix must be the first two characters of a file. The\npresence of whitespace before the shebang will cause the shebang to be\nignored, which is likely a mistake.\n\n## Example\n```python\n #!/usr/bin/env python3\n```\n\nUse instead:\n```python\n#!/usr/bin/env python3\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe when the whitespace before the shebang\ncontains a newline. Deleting the newline can activate an encoding declaration\nand change how the file is decoded.\n\n## References\n- [Python documentation: Executable Python Scripts](https://docs.python.org/3/tutorial/appendix.html#executable-python-scripts)\n",
|
|
230
|
+
"ruff/EXE005": "## What it does\nChecks for a shebang directive that is not at the beginning of the file.\n\n## Why is this bad?\nIn Python, a shebang (also known as a hashbang) is the first line of a\nscript, which specifies the interpreter that should be used to run the\nscript.\n\nThe shebang's `#!` prefix must be the first two characters of a file. If\nthe shebang is not at the beginning of the file, it will be ignored, which\nis likely a mistake.\n\n## Example\n```python\nfoo = 1\n#!/usr/bin/env python3\n```\n\nUse instead:\n```python\n#!/usr/bin/env python3\nfoo = 1\n```\n\n## References\n- [Python documentation: Executable Python Scripts](https://docs.python.org/3/tutorial/appendix.html#executable-python-scripts)\n",
|
|
231
|
+
"ruff/FIX001": "## What it does\nChecks for \"FIXME\" comments.\n\n## Why is this bad?\n\"FIXME\" comments are used to describe an issue that should be resolved\n(usually, a bug or unexpected behavior).\n\nConsider resolving the issue before deploying the code.\n\nNote that if you use \"FIXME\" comments as a form of documentation, this\nrule may not be appropriate for your project.\n\n## Example\n```python\ndef speed(distance, time):\n return distance / time # FIXME: Raises ZeroDivisionError for time = 0.\n```\n",
|
|
232
|
+
"ruff/FIX002": "## What it does\nChecks for \"TODO\" comments.\n\n## Why is this bad?\n\"TODO\" comments are used to describe an issue that should be resolved\n(usually, a missing feature, optimization, or refactoring opportunity).\n\nConsider resolving the issue before deploying the code.\n\nNote that if you use \"TODO\" comments as a form of documentation (e.g.,\nto [provide context for future work](https://gist.github.com/dmnd/ed5d8ef8de2e4cfea174bd5dafcda382)),\nthis rule may not be appropriate for your project.\n\n## Example\n```python\ndef greet(name):\n return f\"Hello, {name}!\" # TODO: Add support for custom greetings.\n```\n",
|
|
233
|
+
"ruff/FIX003": "## What it does\nChecks for \"XXX\" comments.\n\n## Why is this bad?\n\"XXX\" comments are used to describe an issue that should be resolved.\n\nConsider resolving the issue before deploying the code, or, at minimum,\nusing a more descriptive comment tag (e.g, \"TODO\").\n\n## Example\n```python\ndef speed(distance, time):\n return distance / time # XXX: Raises ZeroDivisionError for time = 0.\n```\n",
|
|
234
|
+
"ruff/FIX004": "## What it does\nChecks for \"HACK\" comments.\n\n## Why is this bad?\n\"HACK\" comments are used to describe an issue that should be resolved\n(usually, a suboptimal solution or temporary workaround).\n\nConsider resolving the issue before deploying the code.\n\nNote that if you use \"HACK\" comments as a form of documentation, this\nrule may not be appropriate for your project.\n\n## Example\n```python\nimport os\n\n\ndef running_windows(): # HACK: Use platform module instead.\n try:\n os.mkdir(\"C:\\\\Windows\\\\System32\\\\\")\n except FileExistsError:\n return True\n else:\n os.rmdir(\"C:\\\\Windows\\\\System32\\\\\")\n return False\n```\n",
|
|
235
|
+
"ruff/FA100": "## What it does\nChecks for missing `from __future__ import annotations` imports upon\ndetecting type annotations that can be written more succinctly under\nPEP 563.\n\n## Why is this bad?\nPEP 585 enabled the use of a number of convenient type annotations, such as\n`list[str]` instead of `List[str]`. However, these annotations are only\navailable on Python 3.9 and higher, _unless_ the `from __future__ import annotations`\nimport is present.\n\nSimilarly, PEP 604 enabled the use of the `|` operator for unions, such as\n`str | None` instead of `Optional[str]`. However, these annotations are only\navailable on Python 3.10 and higher, _unless_ the `from __future__ import annotations`\nimport is present.\n\nBy adding the `__future__` import, the pyupgrade rules can automatically\nmigrate existing code to use the new syntax, even for older Python versions.\nThis rule thus pairs well with pyupgrade and with Ruff's pyupgrade rules.\n\nThis rule respects the [`target-version`] setting. For example, if your\nproject targets Python 3.10 and above, adding `from __future__ import annotations`\ndoes not impact your ability to leverage PEP 604-style unions (e.g., to\nconvert `Optional[str]` to `str | None`). As such, this rule will only\nflag such usages if your project targets Python 3.9 or below.\n\n## Example\n\n```python\nfrom typing import List, Dict, Optional\n\n\ndef func(obj: Dict[str, Optional[int]]) -> None: ...\n```\n\nUse instead:\n\n```python\nfrom __future__ import annotations\n\nfrom typing import List, Dict, Optional\n\n\ndef func(obj: Dict[str, Optional[int]]) -> None: ...\n```\n\nAfter running the additional pyupgrade rules:\n\n```python\nfrom __future__ import annotations\n\n\ndef func(obj: dict[str, int | None]) -> None: ...\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as adding `from __future__ import annotations`\nmay change the semantics of the program.\n\n## Options\n- `target-version`\n",
|
|
236
|
+
"ruff/FA102": "## What it does\nChecks for uses of PEP 585- and PEP 604-style type annotations in Python\nmodules that lack the required `from __future__ import annotations` import\nfor compatibility with older Python versions.\n\n## Why is this bad?\nUsing PEP 585 and PEP 604 style annotations without a `from __future__ import\nannotations` import will cause runtime errors on Python versions prior to\n3.9 and 3.10, respectively.\n\nBy adding the `__future__` import, the interpreter will no longer interpret\nannotations at evaluation time, making the code compatible with both past\nand future Python versions.\n\nThis rule respects the [`target-version`] setting. For example, if your\nproject targets Python 3.10 and above, adding `from __future__ import annotations`\ndoes not impact your ability to leverage PEP 604-style unions (e.g., to\nconvert `Optional[str]` to `str | None`). As such, this rule will only\nflag such usages if your project targets Python 3.9 or below.\n\n## Example\n\n```python\ndef func(obj: dict[str, int | None]) -> None: ...\n```\n\nUse instead:\n\n```python\nfrom __future__ import annotations\n\n\ndef func(obj: dict[str, int | None]) -> None: ...\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as adding `from __future__ import annotations`\nmay change the semantics of the program.\n\n## Options\n- `target-version`\n",
|
|
237
|
+
"ruff/INT001": "## What it does\nChecks for f-strings in `gettext` function calls.\n\n## Why is this bad?\nIn the `gettext` API, the `gettext` function (often aliased to `_`) returns\na translation of its input argument by looking it up in a translation\ncatalog.\n\nCalling `gettext` with an f-string as its argument can cause unexpected\nbehavior. Since the f-string is resolved before the function call, the\ntranslation catalog will look up the formatted string, rather than the\nf-string template.\n\nInstead, format the value returned by the function call, rather than\nits argument.\n\n## Example\n```python\nfrom gettext import gettext as _\n\nname = \"Maria\"\n_(f\"Hello, {name}!\") # Looks for \"Hello, Maria!\".\n```\n\nUse instead:\n```python\nfrom gettext import gettext as _\n\nname = \"Maria\"\n_(\"Hello, %s!\") % name # Looks for \"Hello, %s!\".\n```\n\n## Options\n\n- `lint.flake8-gettext.function-names`\n\n## References\n- [Python documentation: `gettext` \u2014 Multilingual internationalization services](https://docs.python.org/3/library/gettext.html)\n",
|
|
238
|
+
"ruff/INT002": "## What it does\nChecks for `str.format` calls in `gettext` function calls.\n\n## Why is this bad?\nIn the `gettext` API, the `gettext` function (often aliased to `_`) returns\na translation of its input argument by looking it up in a translation\ncatalog.\n\nCalling `gettext` with a formatted string as its argument can cause\nunexpected behavior. Since the formatted string is resolved before the\nfunction call, the translation catalog will look up the formatted string,\nrather than the `str.format`-style template.\n\nInstead, format the value returned by the function call, rather than\nits argument.\n\n## Example\n```python\nfrom gettext import gettext as _\n\nname = \"Maria\"\n_(\"Hello, {}!\".format(name)) # Looks for \"Hello, Maria!\".\n```\n\nUse instead:\n```python\nfrom gettext import gettext as _\n\nname = \"Maria\"\n_(\"Hello, %s!\") % name # Looks for \"Hello, %s!\".\n```\n\n## Options\n\n- `lint.flake8-gettext.function-names`\n\n## References\n- [Python documentation: `gettext` \u2014 Multilingual internationalization services](https://docs.python.org/3/library/gettext.html)\n",
|
|
239
|
+
"ruff/INT003": "## What it does\nChecks for printf-style formatted strings in `gettext` function calls.\n\n## Why is this bad?\nIn the `gettext` API, the `gettext` function (often aliased to `_`) returns\na translation of its input argument by looking it up in a translation\ncatalog.\n\nCalling `gettext` with a formatted string as its argument can cause\nunexpected behavior. Since the formatted string is resolved before the\nfunction call, the translation catalog will look up the formatted string,\nrather than the printf-style template.\n\nInstead, format the value returned by the function call, rather than\nits argument.\n\n## Example\n```python\nfrom gettext import gettext as _\n\nname = \"Maria\"\n_(\"Hello, %s!\" % name) # Looks for \"Hello, Maria!\".\n```\n\nUse instead:\n```python\nfrom gettext import gettext as _\n\nname = \"Maria\"\n_(\"Hello, %s!\") % name # Looks for \"Hello, %s!\".\n```\n\n## Options\n\n- `lint.flake8-gettext.function-names`\n\n## References\n- [Python documentation: `gettext` \u2014 Multilingual internationalization services](https://docs.python.org/3/library/gettext.html)\n",
|
|
240
|
+
"ruff/ISC001": "## What it does\nChecks for implicitly concatenated strings on a single line.\n\n## Why is this bad?\nWhile it is valid Python syntax to concatenate multiple string or byte\nliterals implicitly (via whitespace delimiters), it is unnecessary and\nnegatively affects code readability.\n\nIn some cases, the implicit concatenation may also be unintentional, as\ncode formatters are capable of introducing single-line implicit\nconcatenations when collapsing long lines.\n\n## Example\n```python\nz = \"The quick \" \"brown fox.\"\n```\n\nUse instead:\n```python\nz = \"The quick brown fox.\"\n```\n",
|
|
241
|
+
"ruff/ISC002": "## What it does\nChecks for implicitly concatenated strings that span multiple lines.\n\n## Why is this bad?\nFor string literals that wrap across multiple lines, [PEP 8] recommends\nthe use of implicit string concatenation within parentheses instead of\nusing a backslash for line continuation, as the former is more readable\nthan the latter.\n\nBy default, this rule will only trigger if the string literal is\nconcatenated via a backslash. To disallow implicit string concatenation\naltogether, set the [`lint.flake8-implicit-str-concat.allow-multiline`] option\nto `false`.\n\n## Example\n```python\nz = \"The quick brown fox jumps over the lazy \"\\\n \"dog.\"\n```\n\nUse instead:\n```python\nz = (\n \"The quick brown fox jumps over the lazy \"\n \"dog.\"\n)\n```\n\n## Options\n- `lint.flake8-implicit-str-concat.allow-multiline`\n\n## Formatter compatibility\nUsing this rule with `allow-multiline = false` can be incompatible with the\nformatter because the [formatter] can introduce new multi-line implicitly\nconcatenated strings. We recommend to either:\n\n* Enable `ISC001` to disallow all implicit concatenated strings\n* Setting `allow-multiline = true`\n\n[PEP 8]: https://peps.python.org/pep-0008/#maximum-line-length\n[formatter]:https://docs.astral.sh/ruff/formatter/\n",
|
|
242
|
+
"ruff/ISC003": "## What it does\nChecks for string literals that are explicitly concatenated (using the\n`+` operator).\n\n## Why is this bad?\nFor string literals that wrap across multiple lines, implicit string\nconcatenation within parentheses is preferred over explicit\nconcatenation using the `+` operator, as the former is more readable.\n\n## Example\n```python\nz = (\n \"The quick brown fox jumps over the lazy \"\n + \"dog\"\n)\n```\n\nUse instead:\n```python\nz = (\n \"The quick brown fox jumps over the lazy \"\n \"dog\"\n)\n```\n\n## Fix safety\n\nThe fix is marked as unsafe when it would create a docstring.\n\n## Options\n\nSetting `lint.flake8-implicit-str-concat.allow-multiline = false` will disable this rule because\nit would leave no allowed way to write a multi-line string.\n\n- `lint.flake8-implicit-str-concat.allow-multiline`\n",
|
|
243
|
+
"ruff/ISC004": "## What it does\nChecks for implicitly concatenated strings inside list, tuple, and set literals.\n\n## Why is this bad?\nIn collection literals, implicit string concatenation is often the result of\na missing comma between elements, which can silently merge items together.\n\n## Example\n```python\nfacts = (\n \"Lobsters have blue blood.\",\n \"The liver is the only human organ that can fully regenerate itself.\",\n \"Clarinets are made almost entirely out of wood from the mpingo tree.\"\n \"In 1971, astronaut Alan Shepard played golf on the moon.\",\n)\n```\n\nInstead, you likely intended:\n```python\nfacts = (\n \"Lobsters have blue blood.\",\n \"The liver is the only human organ that can fully regenerate itself.\",\n \"Clarinets are made almost entirely out of wood from the mpingo tree.\",\n \"In 1971, astronaut Alan Shepard played golf on the moon.\",\n)\n```\n\nIf the concatenation is intentional, wrap it in parentheses to make it\nexplicit:\n```python\nfacts = (\n \"Lobsters have blue blood.\",\n \"The liver is the only human organ that can fully regenerate itself.\",\n (\n \"Clarinets are made almost entirely out of wood from the mpingo tree.\"\n \"In 1971, astronaut Alan Shepard played golf on the moon.\"\n ),\n)\n```\n\n## Fix safety\nThe fix is safe in that it does not change the semantics of your code.\nHowever, the issue is that you may often want to change semantics\nby adding a missing comma. Thus, the fix is always marked as unsafe.\n",
|
|
244
|
+
"ruff/ICN001": "## What it does\nChecks for imports that are typically imported using a common convention,\nlike `import pandas as pd`, and enforces that convention.\n\n## Why is this bad?\nConsistency is good. Use a common convention for imports to make your code\nmore readable and idiomatic.\n\nFor example, `import pandas as pd` is a common\nconvention for importing the `pandas` library, and users typically expect\nPandas to be aliased as `pd`.\n\n## Example\n```python\nimport pandas\n```\n\nUse instead:\n```python\nimport pandas as pd\n```\n\n## Options\n- `lint.flake8-import-conventions.aliases`\n- `lint.flake8-import-conventions.extend-aliases`\n",
|
|
245
|
+
"ruff/ICN002": "## What it does\nChecks for imports that use non-standard naming conventions, like\n`import tensorflow.keras.backend as K`.\n\n## Why is this bad?\nConsistency is good. Avoid using a non-standard naming convention for\nimports, and, in particular, choosing import aliases that violate PEP 8.\n\nFor example, aliasing via `import tensorflow.keras.backend as K` violates\nthe guidance of PEP 8, and is thus avoided in some projects.\n\n## Example\n```python\nimport tensorflow.keras.backend as K\n```\n\nUse instead:\n```python\nimport tensorflow as tf\n\ntf.keras.backend\n```\n\n## Options\n- `lint.flake8-import-conventions.banned-aliases`\n",
|
|
246
|
+
"ruff/ICN003": "## What it does\nChecks for member imports that should instead be accessed by importing the\nmodule.\n\n## Why is this bad?\nConsistency is good. Use a common convention for imports to make your code\nmore readable and idiomatic.\n\nFor example, it's common to import `pandas` as `pd`, and then access\nmembers like `Series` via `pd.Series`, rather than importing `Series`\ndirectly.\n\n## Example\n```python\nfrom pandas import Series\n```\n\nUse instead:\n```python\nimport pandas as pd\n\npd.Series\n```\n\n## Options\n- `lint.flake8-import-conventions.banned-from`\n",
|
|
247
|
+
"ruff/LOG001": "## What it does\nChecks for direct instantiation of `logging.Logger`, as opposed to using\n`logging.getLogger()`.\n\n## Why is this bad?\nThe [Logger Objects] documentation states that:\n\n> Note that Loggers should NEVER be instantiated directly, but always\n> through the module-level function `logging.getLogger(name)`.\n\nIf a logger is directly instantiated, it won't be added to the logger\ntree, and will bypass all configuration. Messages logged to it will\nonly be sent to the \"handler of last resort\", skipping any filtering\nor formatting.\n\n## Example\n```python\nimport logging\n\nlogger = logging.Logger(__name__)\n```\n\nUse instead:\n```python\nimport logging\n\nlogger = logging.getLogger(__name__)\n```\n\n## Fix safety\nThis fix is always unsafe, as changing from `Logger` to `getLogger`\nchanges program behavior by will adding the logger to the logging tree.\n\n[Logger Objects]: https://docs.python.org/3/library/logging.html#logger-objects\n",
|
|
248
|
+
"ruff/LOG002": "## What it does\nChecks for any usage of `__cached__` and `__file__` as an argument to\n`logging.getLogger()`.\n\n## Why is this bad?\nThe [logging documentation] recommends this pattern:\n\n```python\nlogging.getLogger(__name__)\n```\n\nHere, `__name__` is the fully qualified module name, such as `foo.bar`,\nwhich is the intended format for logger names.\n\nThis rule detects probably-mistaken usage of similar module-level dunder constants:\n\n* `__cached__` - the pathname of the module's compiled version, such as `foo/__pycache__/bar.cpython-311.pyc`.\n* `__file__` - the pathname of the module, such as `foo/bar.py`.\n\n## Example\n```python\nimport logging\n\nlogger = logging.getLogger(__file__)\n```\n\nUse instead:\n```python\nimport logging\n\nlogger = logging.getLogger(__name__)\n```\n\n## Fix safety\nThis fix is always unsafe, as changing the arguments to `getLogger` can change the\nreceived logger object, and thus program behavior.\n\n[logging documentation]: https://docs.python.org/3/library/logging.html#logger-objects\n",
|
|
249
|
+
"ruff/LOG004": "## What it does\nChecks for `.exception()` logging calls outside of exception handlers.\n\n## Why is this bad?\n[The documentation] states:\n> This function should only be called from an exception handler.\n\nCalling `.exception()` outside of an exception handler\nattaches `None` as exception information, leading to confusing messages:\n\n```pycon\n>>> logging.exception(\"example\")\nERROR:root:example\nNoneType: None\n```\n\n## Example\n\n```python\nimport logging\n\nlogging.exception(\"Foobar\")\n```\n\nUse instead:\n\n```python\nimport logging\n\nlogging.error(\"Foobar\")\n```\n\n## Known limitations\nThis rule checks whether a call is _defined_ inside an exception handler, not\nwhether it _executes_ inside one. A function defined in an `except` block but\ncalled outside of it will not be flagged, despite the fact that the call may\nnot have access to an active exception at runtime:\n\n```python\nimport logging\n\n\ntry:\n raise ValueError()\nexcept Exception:\n\n def handler():\n logging.exception(\"Foobar\") # LOG004 not raised (false negative)\n\n\nhandler()\n```\n\n## Fix safety\nThe fix, if available, will always be marked as unsafe, as it changes runtime behavior.\n\n## Options\n\n- `lint.logger-objects`\n\n[The documentation]: https://docs.python.org/3/library/logging.html#logging.exception\n",
|
|
250
|
+
"ruff/LOG007": "## What it does\nChecks for uses of `logging.exception()` with `exc_info` set to `False`.\n\n## Why is this bad?\nThe `logging.exception()` method captures the exception automatically, but\naccepts an optional `exc_info` argument to override this behavior. Setting\n`exc_info` to `False` disables the automatic capture of the exception and\nstack trace.\n\nInstead of setting `exc_info` to `False`, prefer `logging.error()`, which\nhas equivalent behavior to `logging.exception()` with `exc_info` set to\n`False`, but is clearer in intent.\n\n## Example\n```python\nlogging.exception(\"...\", exc_info=False)\n```\n\nUse instead:\n```python\nlogging.error(\"...\")\n```\n\n## Options\n\n- `lint.logger-objects`\n",
|
|
251
|
+
"ruff/LOG009": "## What it does\nChecks for uses of `logging.WARN`.\n\n## Why is this bad?\nThe `logging.WARN` constant is an undocumented alias for `logging.WARNING`.\n\nAlthough it\u2019s not explicitly deprecated, `logging.WARN` is not mentioned\nin the `logging` documentation. Prefer `logging.WARNING` instead.\n\n## Example\n```python\nimport logging\n\n\nlogging.basicConfig(level=logging.WARN)\n```\n\nUse instead:\n```python\nimport logging\n\n\nlogging.basicConfig(level=logging.WARNING)\n```\n",
|
|
252
|
+
"ruff/LOG014": "## What it does\nChecks for logging calls with `exc_info=` outside exception handlers.\n\n## Why is this bad?\nUsing `exc_info=True` outside of an exception handler\nattaches `None` as the exception information, leading to confusing messages:\n\n```pycon\n>>> logging.warning(\"Uh oh\", exc_info=True)\nWARNING:root:Uh oh\nNoneType: None\n```\n\n## Example\n\n```python\nimport logging\n\n\nlogging.warning(\"Foobar\", exc_info=True)\n```\n\nUse instead:\n\n```python\nimport logging\n\n\nlogging.warning(\"Foobar\")\n```\n\n## Known limitations\nThis rule checks whether a call is _defined_ inside an exception handler, not\nwhether it _executes_ inside one. A function defined in an `except` block but\ncalled outside of it will not be flagged, despite the fact that the call may\nnot have access to an active exception at runtime:\n\n```python\nimport logging\n\n\ntry:\n raise ValueError()\nexcept Exception:\n\n def handler():\n logging.error(\"Foobar\", exc_info=True) # LOG014 not raised (false negative)\n\n\nhandler()\n```\n\n## Fix safety\nThe fix is always marked as unsafe, as it changes runtime behavior.\n\n## Options\n\n- `lint.logger-objects`\n",
|
|
253
|
+
"ruff/LOG015": "## What it does\nChecks for usages of the following `logging` top-level functions:\n`debug`, `info`, `warn`, `warning`, `error`, `critical`, `log`, `exception`.\n\n## Why is this bad?\nUsing the root logger causes the messages to have no source information,\nmaking them less useful for debugging.\n\n## Example\n```python\nimport logging\n\nlogging.info(\"Foobar\")\n```\n\nUse instead:\n```python\nimport logging\n\nlogger = logging.getLogger(__name__)\nlogger.info(\"Foobar\")\n```\n",
|
|
254
|
+
"ruff/G001": "## What it does\nChecks for uses of `str.format` to format logging messages.\n\n## Why is this bad?\nThe `logging` module provides a mechanism for passing additional values to\nbe logged using the `extra` keyword argument. This is more consistent, more\nefficient, and less error-prone than formatting the string directly.\n\nUsing `str.format` to format a logging message requires that Python eagerly\nformat the string, even if the logging statement is never executed (e.g.,\nif the log level is above the level of the logging statement), whereas\nusing the `extra` keyword argument defers formatting until required.\n\nAdditionally, the use of `extra` will ensure that the values are made\navailable to all handlers, which can then be configured to log the values\nin a consistent manner.\n\nAs an alternative to `extra`, passing values as arguments to the logging\nmethod can also be used to defer string formatting until required.\n\n## Known problems\n\nThis rule detects uses of the `logging` module via a heuristic.\nSpecifically, it matches against:\n\n- Uses of the `logging` module itself (e.g., `import logging; logging.info(...)`).\n- Uses of `flask.current_app.logger` (e.g., `from flask import current_app; current_app.logger.info(...)`).\n- Objects whose name starts with `log` or ends with `logger` or `logging`,\n when used in the same file in which they are defined (e.g., `logger = logging.getLogger(); logger.info(...)`).\n- Imported objects marked as loggers via the [`lint.logger-objects`] setting, which can be\n used to enforce these rules against shared logger objects (e.g., `from module import logger; logger.info(...)`,\n when [`lint.logger-objects`] is set to `[\"module.logger\"]`).\n\n## Example\n```python\nimport logging\n\nlogging.basicConfig(format=\"%(message)s\", level=logging.INFO)\n\nuser = \"Maria\"\n\nlogging.info(\"{} - Something happened\".format(user))\n```\n\nUse instead:\n```python\nimport logging\n\nlogging.basicConfig(format=\"%(user_id)s - %(message)s\", level=logging.INFO)\n\nuser = \"Maria\"\n\nlogging.info(\"Something happened\", extra={\"user_id\": user})\n```\n\nOr:\n```python\nimport logging\n\nlogging.basicConfig(format=\"%(message)s\", level=logging.INFO)\n\nuser = \"Maria\"\n\nlogging.info(\"%s - Something happened\", user)\n```\n\n## Options\n- `lint.logger-objects`\n\n## References\n- [Python documentation: `logging`](https://docs.python.org/3/library/logging.html)\n- [Python documentation: Optimization](https://docs.python.org/3/howto/logging.html#optimization)\n",
|
|
255
|
+
"ruff/G002": "## What it does\nChecks for uses of `printf`-style format strings to format logging\nmessages.\n\n## Why is this bad?\nThe `logging` module provides a mechanism for passing additional values to\nbe logged using the `extra` keyword argument. This is more consistent, more\nefficient, and less error-prone than formatting the string directly.\n\nUsing `printf`-style format strings to format a logging message requires\nthat Python eagerly format the string, even if the logging statement is\nnever executed (e.g., if the log level is above the level of the logging\nstatement), whereas using the `extra` keyword argument defers formatting\nuntil required.\n\nAdditionally, the use of `extra` will ensure that the values are made\navailable to all handlers, which can then be configured to log the values\nin a consistent manner.\n\nAs an alternative to `extra`, passing values as arguments to the logging\nmethod can also be used to defer string formatting until required.\n\n## Known problems\n\nThis rule detects uses of the `logging` module via a heuristic.\nSpecifically, it matches against:\n\n- Uses of the `logging` module itself (e.g., `import logging; logging.info(...)`).\n- Uses of `flask.current_app.logger` (e.g., `from flask import current_app; current_app.logger.info(...)`).\n- Objects whose name starts with `log` or ends with `logger` or `logging`,\n when used in the same file in which they are defined (e.g., `logger = logging.getLogger(); logger.info(...)`).\n- Imported objects marked as loggers via the [`lint.logger-objects`] setting, which can be\n used to enforce these rules against shared logger objects (e.g., `from module import logger; logger.info(...)`,\n when [`lint.logger-objects`] is set to `[\"module.logger\"]`).\n\n## Example\n```python\nimport logging\n\nlogging.basicConfig(format=\"%(message)s\", level=logging.INFO)\n\nuser = \"Maria\"\n\nlogging.info(\"%s - Something happened\" % user)\n```\n\nUse instead:\n```python\nimport logging\n\nlogging.basicConfig(format=\"%(user_id)s - %(message)s\", level=logging.INFO)\n\nuser = \"Maria\"\n\nlogging.info(\"Something happened\", extra=dict(user_id=user))\n```\n\nOr:\n```python\nimport logging\n\nlogging.basicConfig(format=\"%(message)s\", level=logging.INFO)\n\nuser = \"Maria\"\n\nlogging.info(\"%s - Something happened\", user)\n```\n\n## Options\n- `lint.logger-objects`\n\n## References\n- [Python documentation: `logging`](https://docs.python.org/3/library/logging.html)\n- [Python documentation: Optimization](https://docs.python.org/3/howto/logging.html#optimization)\n",
|
|
256
|
+
"ruff/G003": "## What it does\nChecks for uses string concatenation via the `+` operator to format logging\nmessages.\n\n## Why is this bad?\nThe `logging` module provides a mechanism for passing additional values to\nbe logged using the `extra` keyword argument. This is more consistent, more\nefficient, and less error-prone than formatting the string directly.\n\nUsing concatenation to format a logging message requires that Python\neagerly format the string, even if the logging statement is never executed\n(e.g., if the log level is above the level of the logging statement),\nwhereas using the `extra` keyword argument defers formatting until required.\n\nAdditionally, the use of `extra` will ensure that the values are made\navailable to all handlers, which can then be configured to log the values\nin a consistent manner.\n\nAs an alternative to `extra`, passing values as arguments to the logging\nmethod can also be used to defer string formatting until required.\n\n## Known problems\n\nThis rule detects uses of the `logging` module via a heuristic.\nSpecifically, it matches against:\n\n- Uses of the `logging` module itself (e.g., `import logging; logging.info(...)`).\n- Uses of `flask.current_app.logger` (e.g., `from flask import current_app; current_app.logger.info(...)`).\n- Objects whose name starts with `log` or ends with `logger` or `logging`,\n when used in the same file in which they are defined (e.g., `logger = logging.getLogger(); logger.info(...)`).\n- Imported objects marked as loggers via the [`lint.logger-objects`] setting, which can be\n used to enforce these rules against shared logger objects (e.g., `from module import logger; logger.info(...)`,\n when [`lint.logger-objects`] is set to `[\"module.logger\"]`).\n\n## Example\n```python\nimport logging\n\nlogging.basicConfig(format=\"%(message)s\", level=logging.INFO)\n\nuser = \"Maria\"\n\nlogging.info(user + \" - Something happened\")\n```\n\nUse instead:\n```python\nimport logging\n\nlogging.basicConfig(format=\"%(user_id)s - %(message)s\", level=logging.INFO)\n\nuser = \"Maria\"\n\nlogging.info(\"Something happened\", extra=dict(user_id=user))\n```\n\nOr:\n```python\nimport logging\n\nlogging.basicConfig(format=\"%(message)s\", level=logging.INFO)\n\nuser = \"Maria\"\n\nlogging.info(\"%s - Something happened\", user)\n```\n\n## Options\n- `lint.logger-objects`\n\n## References\n- [Python documentation: `logging`](https://docs.python.org/3/library/logging.html)\n- [Python documentation: Optimization](https://docs.python.org/3/howto/logging.html#optimization)\n",
|
|
257
|
+
"ruff/G004": "## What it does\nChecks for uses of f-strings to format logging messages.\n\n## Why is this bad?\nThe `logging` module provides a mechanism for passing additional values to\nbe logged using the `extra` keyword argument. This is more consistent, more\nefficient, and less error-prone than formatting the string directly.\n\nUsing f-strings to format a logging message requires that Python eagerly\nformat the string, even if the logging statement is never executed (e.g.,\nif the log level is above the level of the logging statement), whereas\nusing the `extra` keyword argument defers formatting until required.\n\nAdditionally, the use of `extra` will ensure that the values are made\navailable to all handlers, which can then be configured to log the values\nin a consistent manner.\n\nAs an alternative to `extra`, passing values as arguments to the logging\nmethod can also be used to defer string formatting until required.\n\n## Known problems\n\nThis rule detects uses of the `logging` module via a heuristic.\nSpecifically, it matches against:\n\n- Uses of the `logging` module itself (e.g., `import logging; logging.info(...)`).\n- Uses of `flask.current_app.logger` (e.g., `from flask import current_app; current_app.logger.info(...)`).\n- Objects whose name starts with `log` or ends with `logger` or `logging`,\n when used in the same file in which they are defined (e.g., `logger = logging.getLogger(); logger.info(...)`).\n- Imported objects marked as loggers via the [`lint.logger-objects`] setting, which can be\n used to enforce these rules against shared logger objects (e.g., `from module import logger; logger.info(...)`,\n when [`lint.logger-objects`] is set to `[\"module.logger\"]`).\n\n## Example\n```python\nimport logging\n\nlogging.basicConfig(format=\"%(message)s\", level=logging.INFO)\n\nuser = \"Maria\"\n\nlogging.info(f\"{user} - Something happened\")\n```\n\nUse instead:\n```python\nimport logging\n\nlogging.basicConfig(format=\"%(user_id)s - %(message)s\", level=logging.INFO)\n\nuser = \"Maria\"\n\nlogging.info(\"Something happened\", extra=dict(user_id=user))\n```\n\nOr:\n```python\nimport logging\n\nlogging.basicConfig(format=\"%(message)s\", level=logging.INFO)\n\nuser = \"Maria\"\n\nlogging.info(\"%s - Something happened\", user)\n```\n\n## Options\n- `lint.logger-objects`\n\n## References\n- [Python documentation: `logging`](https://docs.python.org/3/library/logging.html)\n- [Python documentation: Optimization](https://docs.python.org/3/howto/logging.html#optimization)\n",
|
|
258
|
+
"ruff/G010": "## What it does\nChecks for uses of `logging.warn` and `logging.Logger.warn`.\n\n## Why is this bad?\n`logging.warn` and `logging.Logger.warn` are deprecated in favor of\n`logging.warning` and `logging.Logger.warning`, which are functionally\nequivalent.\n\n## Known problems\n\nThis rule detects uses of the `logging` module via a heuristic.\nSpecifically, it matches against:\n\n- Uses of the `logging` module itself (e.g., `import logging; logging.info(...)`).\n- Uses of `flask.current_app.logger` (e.g., `from flask import current_app; current_app.logger.info(...)`).\n- Objects whose name starts with `log` or ends with `logger` or `logging`,\n when used in the same file in which they are defined (e.g., `logger = logging.getLogger(); logger.info(...)`).\n- Imported objects marked as loggers via the [`lint.logger-objects`] setting, which can be\n used to enforce these rules against shared logger objects (e.g., `from module import logger; logger.info(...)`,\n when [`lint.logger-objects`] is set to `[\"module.logger\"]`).\n\n## Example\n```python\nimport logging\n\nlogging.warn(\"Something happened\")\n```\n\nUse instead:\n```python\nimport logging\n\nlogging.warning(\"Something happened\")\n```\n\n## Options\n- `lint.logger-objects`\n\n## References\n- [Python documentation: `logging.warning`](https://docs.python.org/3/library/logging.html#logging.warning)\n- [Python documentation: `logging.Logger.warning`](https://docs.python.org/3/library/logging.html#logging.Logger.warning)\n",
|
|
259
|
+
"ruff/G101": "## What it does\nChecks for `extra` keywords in logging statements that clash with\n`LogRecord` attributes.\n\n## Why is this bad?\nThe `logging` module provides a mechanism for passing additional values to\nbe logged using the `extra` keyword argument. These values are then passed\nto the `LogRecord` constructor.\n\nProviding a value via `extra` that clashes with one of the attributes of\nthe `LogRecord` constructor will raise a `KeyError` when the `LogRecord` is\nconstructed.\n\n## Known problems\n\nThis rule detects uses of the `logging` module via a heuristic.\nSpecifically, it matches against:\n\n- Uses of the `logging` module itself (e.g., `import logging; logging.info(...)`).\n- Uses of `flask.current_app.logger` (e.g., `from flask import current_app; current_app.logger.info(...)`).\n- Objects whose name starts with `log` or ends with `logger` or `logging`,\n when used in the same file in which they are defined (e.g., `logger = logging.getLogger(); logger.info(...)`).\n- Imported objects marked as loggers via the [`lint.logger-objects`] setting, which can be\n used to enforce these rules against shared logger objects (e.g., `from module import logger; logger.info(...)`,\n when [`lint.logger-objects`] is set to `[\"module.logger\"]`).\n\n## Example\n```python\nimport logging\n\nlogging.basicConfig(format=\"%(name) - %(message)s\", level=logging.INFO)\n\nusername = \"Maria\"\n\nlogging.info(\"Something happened\", extra=dict(name=username))\n```\n\nUse instead:\n```python\nimport logging\n\nlogging.basicConfig(format=\"%(user_id)s - %(message)s\", level=logging.INFO)\n\nusername = \"Maria\"\n\nlogging.info(\"Something happened\", extra=dict(user_id=username))\n```\n\n## Options\n- `lint.logger-objects`\n\n## References\n- [Python documentation: LogRecord attributes](https://docs.python.org/3/library/logging.html#logrecord-attributes)\n",
|
|
260
|
+
"ruff/G201": "## What it does\nChecks for uses of `logging.error` that pass `exc_info=True`.\n\n## Why is this bad?\nCalling `logging.error` with `exc_info=True` is equivalent to calling\n`logging.exception`. Using `logging.exception` is more concise, more\nreadable, and conveys the intent of the logging statement more clearly.\n\n## Known problems\n\nThis rule detects uses of the `logging` module via a heuristic.\nSpecifically, it matches against:\n\n- Uses of the `logging` module itself (e.g., `import logging; logging.info(...)`).\n- Uses of `flask.current_app.logger` (e.g., `from flask import current_app; current_app.logger.info(...)`).\n- Objects whose name starts with `log` or ends with `logger` or `logging`,\n when used in the same file in which they are defined (e.g., `logger = logging.getLogger(); logger.info(...)`).\n- Imported objects marked as loggers via the [`lint.logger-objects`] setting, which can be\n used to enforce these rules against shared logger objects (e.g., `from module import logger; logger.info(...)`,\n when [`lint.logger-objects`] is set to `[\"module.logger\"]`).\n\n## Example\n```python\nimport logging\n\ntry:\n ...\nexcept ValueError:\n logging.error(\"Exception occurred\", exc_info=True)\n```\n\nUse instead:\n```python\nimport logging\n\ntry:\n ...\nexcept ValueError:\n logging.exception(\"Exception occurred\")\n```\n\n## Options\n- `lint.logger-objects`\n\n## References\n- [Python documentation: `logging.exception`](https://docs.python.org/3/library/logging.html#logging.exception)\n- [Python documentation: `exception`](https://docs.python.org/3/library/logging.html#logging.Logger.exception)\n- [Python documentation: `logging.error`](https://docs.python.org/3/library/logging.html#logging.error)\n- [Python documentation: `error`](https://docs.python.org/3/library/logging.html#logging.Logger.error)\n",
|
|
261
|
+
"ruff/G202": "## What it does\nChecks for redundant `exc_info` keyword arguments in logging statements.\n\n## Why is this bad?\n`exc_info` is `True` by default for `logging.exception`, and `False` by\ndefault for `logging.error`.\n\nPassing `exc_info=True` to `logging.exception` calls is redundant, as is\npassing `exc_info=False` to `logging.error` calls.\n\n## Known problems\n\nThis rule detects uses of the `logging` module via a heuristic.\nSpecifically, it matches against:\n\n- Uses of the `logging` module itself (e.g., `import logging; logging.info(...)`).\n- Uses of `flask.current_app.logger` (e.g., `from flask import current_app; current_app.logger.info(...)`).\n- Objects whose name starts with `log` or ends with `logger` or `logging`,\n when used in the same file in which they are defined (e.g., `logger = logging.getLogger(); logger.info(...)`).\n- Imported objects marked as loggers via the [`lint.logger-objects`] setting, which can be\n used to enforce these rules against shared logger objects (e.g., `from module import logger; logger.info(...)`,\n when [`lint.logger-objects`] is set to `[\"module.logger\"]`).\n\n## Example\n```python\nimport logging\n\ntry:\n ...\nexcept ValueError:\n logging.exception(\"Exception occurred\", exc_info=True)\n```\n\nUse instead:\n```python\nimport logging\n\ntry:\n ...\nexcept ValueError:\n logging.exception(\"Exception occurred\")\n```\n\n## Options\n- `lint.logger-objects`\n\n## References\n- [Python documentation: `logging.exception`](https://docs.python.org/3/library/logging.html#logging.exception)\n- [Python documentation: `exception`](https://docs.python.org/3/library/logging.html#logging.Logger.exception)\n- [Python documentation: `logging.error`](https://docs.python.org/3/library/logging.html#logging.error)\n- [Python documentation: `error`](https://docs.python.org/3/library/logging.html#logging.Logger.error)\n",
|
|
262
|
+
"ruff/INP001": "## What it does\nChecks for packages that are missing an `__init__.py` file.\n\n## Why is this bad?\nPython packages are directories that contain a file named `__init__.py`.\nThe existence of this file indicates that the directory is a Python\npackage, and so it can be imported the same way a module can be\nimported.\n\nDirectories that lack an `__init__.py` file can still be imported, but\nthey're indicative of a special kind of package, known as a \"namespace\npackage\" (see: [PEP 420](https://peps.python.org/pep-0420/)).\nNamespace packages are less widely used, so a package that lacks an\n`__init__.py` file is typically meant to be a regular package, and\nthe absence of the `__init__.py` file is probably an oversight.\n\n## Options\n- `namespace-packages`\n",
|
|
263
|
+
"ruff/PIE790": "## What it does\nChecks for unnecessary `pass` statements and ellipsis (`...`) literals in\nfunctions, classes, and other blocks.\n\n## Why is this bad?\nIn Python, the `pass` statement and ellipsis (`...`) literal serve as\nplaceholders, allowing for syntactically correct empty code blocks. The\nprimary purpose of these nodes is to avoid syntax errors in situations\nwhere a statement or expression is syntactically required, but no code\nneeds to be executed.\n\nIf a `pass` or ellipsis is present in a code block that includes at least\none other statement (even, e.g., a docstring), it is unnecessary and should\nbe removed.\n\n## Example\n```python\ndef func():\n \"\"\"Placeholder docstring.\"\"\"\n pass\n```\n\nUse instead:\n```python\ndef func():\n \"\"\"Placeholder docstring.\"\"\"\n```\n\nOr, given:\n```python\ndef func():\n \"\"\"Placeholder docstring.\"\"\"\n ...\n```\n\nUse instead:\n```python\ndef func():\n \"\"\"Placeholder docstring.\"\"\"\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe in the rare case that the `pass` or ellipsis\nis followed by a string literal, since removal of the placeholder would convert the\nsubsequent string literal into a docstring.\n\n## References\n- [Python documentation: The `pass` statement](https://docs.python.org/3/reference/simple_stmts.html#the-pass-statement)\n",
|
|
264
|
+
"ruff/PIE794": "## What it does\nChecks for duplicate field definitions in classes.\n\n## Why is this bad?\nDefining a field multiple times in a class body is redundant and likely a\nmistake.\n\n## Example\n```python\nclass Person:\n name = Tom\n ...\n name = Ben\n```\n\nUse instead:\n```python\nclass Person:\n name = Tom\n ...\n```\n\n## Fix safety\nThis fix is always marked as unsafe since we cannot know\nfor certain which assignment was intended.\n",
|
|
265
|
+
"ruff/PIE796": "## What it does\nChecks for enums that contain duplicate values.\n\n## Why is this bad?\nEnum values should be unique. Non-unique values are redundant and likely a\nmistake.\n\n## Example\n```python\nfrom enum import Enum\n\n\nclass Foo(Enum):\n A = 1\n B = 2\n C = 1\n```\n\nUse instead:\n```python\nfrom enum import Enum\n\n\nclass Foo(Enum):\n A = 1\n B = 2\n C = 3\n```\n\n## References\n- [Python documentation: `enum.Enum`](https://docs.python.org/3/library/enum.html#enum.Enum)\n",
|
|
266
|
+
"ruff/PIE800": "## What it does\nChecks for unnecessary dictionary unpacking operators (`**`).\n\n## Why is this bad?\nUnpacking a dictionary into another dictionary is redundant. The unpacking\noperator can be removed, making the code more readable.\n\n## Example\n```python\nfoo = {\"A\": 1, \"B\": 2}\nbar = {**foo, **{\"C\": 3}}\n```\n\nUse instead:\n```python\nfoo = {\"A\": 1, \"B\": 2}\nbar = {**foo, \"C\": 3}\n```\n\n## References\n- [Python documentation: Dictionary displays](https://docs.python.org/3/reference/expressions.html#dictionary-displays)\n",
|
|
267
|
+
"ruff/PIE804": "## What it does\nChecks for unnecessary `dict` kwargs.\n\n## Why is this bad?\nIf the `dict` keys are valid identifiers, they can be passed as keyword\narguments directly, without constructing unnecessary dictionary.\nThis also makes code more type-safe as type checkers often cannot\nprecisely verify dynamic keyword arguments.\n\n## Example\n\n```python\ndef foo(bar):\n return bar + 1\n\n\nprint(foo(**{\"bar\": 2})) # prints 3\n\n# No typing errors, but results in an exception at runtime.\nprint(foo(**{\"bar\": 2, \"baz\": 3}))\n```\n\nUse instead:\n\n```python\ndef foo(bar):\n return bar + 1\n\n\nprint(foo(bar=2)) # prints 3\n\n# Typing error detected: No parameter named \"baz\".\nprint(foo(bar=2, baz=3))\n```\n\n## Fix safety\n\nThis rule's fix is marked as unsafe for dictionaries with comments interleaved between\nthe items, as comments may be removed.\n\nFor example, the fix would be marked as unsafe in the following case:\n\n```python\nfoo(\n **{\n # comment\n \"x\": 1.0,\n # comment\n \"y\": 2.0,\n }\n)\n```\n\nas this is converted to `foo(x=1.0, y=2.0)` without any of the comments.\n\n## References\n- [Python documentation: Dictionary displays](https://docs.python.org/3/reference/expressions.html#dictionary-displays)\n- [Python documentation: Calls](https://docs.python.org/3/reference/expressions.html#calls)\n",
|
|
268
|
+
"ruff/PIE807": "## What it does\nChecks for lambdas that can be replaced with the `list` or `dict` builtins.\n\n## Why is this bad?\nUsing container builtins are more succinct and idiomatic than wrapping\nthe literal in a lambda.\n\n## Example\n```python\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass Foo:\n bar: list[int] = field(default_factory=lambda: [])\n```\n\nUse instead:\n```python\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass Foo:\n bar: list[int] = field(default_factory=list)\n baz: dict[str, int] = field(default_factory=dict)\n```\n\n## References\n- [Python documentation: `list`](https://docs.python.org/3/library/functions.html#func-list)\n",
|
|
269
|
+
"ruff/PIE808": "## What it does\nChecks for `range` calls with an unnecessary `start` argument.\n\n## Why is this bad?\n`range(0, x)` is equivalent to `range(x)`, as `0` is the default value for\nthe `start` argument. Omitting the `start` argument makes the code more\nconcise and idiomatic.\n\n## Example\n```python\nrange(0, 3)\n```\n\nUse instead:\n```python\nrange(3)\n```\n\n## References\n- [Python documentation: `range`](https://docs.python.org/3/library/stdtypes.html#range)\n",
|
|
270
|
+
"ruff/PIE810": "## What it does\nChecks for `startswith` or `endswith` calls on the same value with\ndifferent prefixes or suffixes.\n\n## Why is this bad?\nThe `startswith` and `endswith` methods accept tuples of prefixes or\nsuffixes respectively. Passing a tuple of prefixes or suffixes is more\nefficient and readable than calling the method multiple times.\n\n## Example\n```python\nmsg = \"Hello, world!\"\nif msg.startswith(\"Hello\") or msg.startswith(\"Hi\"):\n print(\"Greetings!\")\n```\n\nUse instead:\n```python\nmsg = \"Hello, world!\"\nif msg.startswith((\"Hello\", \"Hi\")):\n print(\"Greetings!\")\n```\n\n## Fix safety\nThis rule's fix is unsafe, as in some cases, it will be unable to determine\nwhether the argument to an existing `.startswith` or `.endswith` call is a\ntuple. For example, given `msg.startswith(x) or msg.startswith(y)`, if `x`\nor `y` is a tuple, and the semantic model is unable to detect it as such,\nthe rule will suggest `msg.startswith((x, y))`, which will error at\nruntime.\n\n## References\n- [Python documentation: `str.startswith`](https://docs.python.org/3/library/stdtypes.html#str.startswith)\n- [Python documentation: `str.endswith`](https://docs.python.org/3/library/stdtypes.html#str.endswith)\n",
|
|
271
|
+
"ruff/T201": "## What it does\nChecks for `print` statements.\n\n## Why is this bad?\n`print` statements used for debugging should be omitted from production\ncode. They can lead the accidental inclusion of sensitive information in\nlogs, and are not configurable by clients, unlike `logging` statements.\n\n`print` statements used to produce output as a part of a command-line\ninterface program are not typically a problem.\n\n## Example\n```python\ndef sum_less_than_four(a, b):\n print(f\"Calling sum_less_than_four\")\n return a + b < 4\n```\n\nThe automatic fix will remove the print statement entirely:\n\n```python\ndef sum_less_than_four(a, b):\n return a + b < 4\n```\n\nTo keep the line for logging purposes, instead use something like:\n\n```python\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\ndef sum_less_than_four(a, b):\n logger.debug(\"Calling sum_less_than_four\")\n return a + b < 4\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO)\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as it will remove `print` statements\nthat are used beyond debugging purposes.\n",
|
|
272
|
+
"ruff/T203": "## What it does\nChecks for `pprint` statements.\n\n## Why is this bad?\nLike `print` statements, `pprint` statements used for debugging should\nbe omitted from production code. They can lead the accidental inclusion\nof sensitive information in logs, and are not configurable by clients,\nunlike `logging` statements.\n\n`pprint` statements used to produce output as a part of a command-line\ninterface program are not typically a problem.\n\n## Example\n```python\nimport pprint\n\n\ndef merge_dicts(dict_a, dict_b):\n dict_c = {**dict_a, **dict_b}\n pprint.pprint(dict_c)\n return dict_c\n```\n\nUse instead:\n```python\ndef merge_dicts(dict_a, dict_b):\n dict_c = {**dict_a, **dict_b}\n return dict_c\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as it will remove `pprint` statements\nthat are used beyond debugging purposes.\n",
|
|
273
|
+
"ruff/PYI001": "## What it does\nChecks that type `TypeVar`s, `ParamSpec`s, and `TypeVarTuple`s in stubs\nhave names prefixed with `_`.\n\n## Why is this bad?\nPrefixing type parameters with `_` avoids accidentally exposing names\ninternal to the stub.\n\n## Example\n```pyi\nfrom typing import TypeVar\n\nT = TypeVar(\"T\")\n```\n\nUse instead:\n```pyi\nfrom typing import TypeVar\n\n_T = TypeVar(\"_T\")\n```\n",
|
|
274
|
+
"ruff/PYI002": "## What it does\nChecks for `if` statements with complex conditionals in stubs.\n\n## Why is this bad?\nType checkers understand simple conditionals to express variations between\ndifferent Python versions and platforms. However, complex tests may not be\nunderstood by a type checker, leading to incorrect inferences when they\nanalyze your code.\n\n## Example\n```pyi\nimport sys\n\nif (3, 10) <= sys.version_info < (3, 12): ...\n```\n\nUse instead:\n```pyi\nimport sys\n\nif sys.version_info >= (3, 10) and sys.version_info < (3, 12): ...\n```\n\n## References\n- [Typing documentation: Version and platform checking](https://typing.python.org/en/latest/spec/directives.html#version-and-platform-checks)\n",
|
|
275
|
+
"ruff/PYI003": "## What it does\nChecks for problematic `sys.version_info`-related conditions in stubs.\n\n## Why is this bad?\nStub files support simple conditionals to test for differences in Python\nversions using `sys.version_info`. However, there are a number of common\nmistakes involving `sys.version_info` comparisons that should be avoided.\nFor example, comparing against a string can lead to unexpected behavior.\n\n## Example\n```pyi\nimport sys\n\nif sys.version_info[0] == \"2\": ...\n```\n\nUse instead:\n```pyi\nimport sys\n\nif sys.version_info[0] == 2: ...\n```\n\n## References\n- [Typing documentation: Version and Platform checking](https://typing.python.org/en/latest/spec/directives.html#version-and-platform-checks)\n",
|
|
276
|
+
"ruff/PYI004": "## What it does\nChecks for Python version comparisons in stubs that compare against patch\nversions (e.g., Python 3.8.3) instead of major and minor versions (e.g.,\nPython 3.8).\n\n## Why is this bad?\nStub files support simple conditionals to test for differences in Python\nversions and platforms. However, type checkers only understand a limited\nsubset of these conditionals. In particular, type checkers don't support\npatch versions (e.g., Python 3.8.3), only major and minor versions (e.g.,\nPython 3.8). Therefore, version checks in stubs should only use the major\nand minor versions.\n\n## Example\n```pyi\nimport sys\n\nif sys.version_info >= (3, 4, 3): ...\n```\n\nUse instead:\n```pyi\nimport sys\n\nif sys.version_info >= (3, 4): ...\n```\n\n## References\n- [Typing documentation: Version and Platform checking](https://typing.python.org/en/latest/spec/directives.html#version-and-platform-checks)\n",
|
|
277
|
+
"ruff/PYI005": "## What it does\nChecks for Python version comparisons that compare against a tuple of the\nwrong length.\n\n## Why is this bad?\nStub files support simple conditionals to test for differences in Python\nversions and platforms. When comparing against `sys.version_info`, avoid\ncomparing against tuples of the wrong length, which can lead to unexpected\nbehavior.\n\n## Example\n```pyi\nimport sys\n\nif sys.version_info[:2] == (3,): ...\n```\n\nUse instead:\n```pyi\nimport sys\n\nif sys.version_info[0] == 3: ...\n```\n\n## References\n- [Typing documentation: Version and Platform checking](https://typing.python.org/en/latest/spec/directives.html#version-and-platform-checks)\n",
|
|
278
|
+
"ruff/PYI006": "## What it does\nChecks for uses of comparators other than `<` and `>=` for\n`sys.version_info` checks. All other comparators, such\nas `>`, `<=`, and `==`, are banned.\n\n## Why is this bad?\nComparing `sys.version_info` with `==` or `<=` has unexpected behavior\nand can lead to bugs.\n\nFor example, `sys.version_info > (3, 8, 1)` will resolve to `True` if your\nPython version is 3.8.1; meanwhile, `sys.version_info <= (3, 8)` will _not_\nresolve to `True` if your Python version is 3.8.10:\n\n```python\n>>> import sys\n>>> print(sys.version_info)\nsys.version_info(major=3, minor=8, micro=10, releaselevel='final', serial=0)\n>>> print(sys.version_info > (3, 8))\nTrue\n>>> print(sys.version_info == (3, 8))\nFalse\n>>> print(sys.version_info <= (3, 8))\nFalse\n>>> print(sys.version_info in (3, 8))\nFalse\n```\n\n## Example\n```py\nimport sys\n\nif sys.version_info > (3, 8): ...\n```\n\nUse instead:\n```py\nimport sys\n\nif sys.version_info >= (3, 9): ...\n```\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
279
|
+
"ruff/PYI007": "## What it does\nCheck for unrecognized `sys.platform` checks. Platform checks should be\nsimple string comparisons.\n\n**Note**: this rule is only enabled in `.pyi` stub files.\n\n## Why is this bad?\nSome `sys.platform` checks are too complex for type checkers to\nunderstand, and thus result in incorrect inferences by these tools.\n`sys.platform` checks should be simple string comparisons, like\n`if sys.platform == \"linux\"`.\n\n## Example\n```pyi\nimport sys\n\nif sys.platform == \"xunil\"[::-1]:\n # Linux specific definitions\n ...\nelse:\n # Posix specific definitions\n ...\n```\n\nInstead, use a simple string comparison, such as `==` or `!=`:\n```pyi\nimport sys\n\nif sys.platform == \"linux\":\n # Linux specific definitions\n ...\nelse:\n # Posix specific definitions\n ...\n```\n\n## References\n- [Typing documentation: Version and Platform checking](https://typing.python.org/en/latest/spec/directives.html#version-and-platform-checks)\n",
|
|
280
|
+
"ruff/PYI008": "## What it does\nCheck for unrecognized platform names in `sys.platform` checks.\n\n**Note**: this rule is only enabled in `.pyi` stub files.\n\n## Why is this bad?\nIf a `sys.platform` check compares to a platform name outside of a\nsmall set of known platforms (e.g. \"linux\", \"win32\", etc.), it's likely\na typo or a platform name that is not recognized by type checkers.\n\nThe list of known platforms is: \"linux\", \"win32\", \"cygwin\", \"darwin\".\n\n## Example\n```pyi\nimport sys\n\nif sys.platform == \"linus\": ...\n```\n\nUse instead:\n```pyi\nimport sys\n\nif sys.platform == \"linux\": ...\n```\n\n## References\n- [Typing documentation: Version and Platform checking](https://typing.python.org/en/latest/spec/directives.html#version-and-platform-checks)\n",
|
|
281
|
+
"ruff/PYI009": "## What it does\nChecks for `pass` statements in empty stub bodies.\n\n## Why is this bad?\nFor stylistic consistency, `...` should always be used rather than `pass`\nin stub files.\n\n## Example\n```pyi\ndef foo(bar: int) -> list[int]: pass\n```\n\nUse instead:\n```pyi\ndef foo(bar: int) -> list[int]: ...\n```\n\n## References\n- [Typing documentation - Writing and Maintaining Stub Files](https://typing.python.org/en/latest/guides/writing_stubs.html)\n",
|
|
282
|
+
"ruff/PYI010": "## What it does\nChecks for non-empty function stub bodies.\n\n## Why is this bad?\nStub files are never executed at runtime; they should be thought of as\n\"data files\" for type checkers or IDEs. Function bodies are redundant\nfor this purpose.\n\n## Example\n```pyi\ndef double(x: int) -> int:\n return x * 2\n```\n\nUse instead:\n```pyi\ndef double(x: int) -> int: ...\n```\n\n## References\n- [Typing documentation - Writing and Maintaining Stub Files](https://typing.python.org/en/latest/guides/writing_stubs.html)\n",
|
|
283
|
+
"ruff/PYI011": "## What it does\nChecks for typed function arguments in stubs with complex default values.\n\n## Why is this bad?\nStub (`.pyi`) files exist as \"data files\" for static analysis tools, and\nare not evaluated at runtime. While simple default values may be useful for\nsome tools that consume stubs, such as IDEs, they are ignored by type\ncheckers.\n\nInstead of including and reproducing a complex value, use `...` to indicate\nthat the assignment has a default value, but that the value is \"complex\" or\nvaries according to the current platform or Python version. For the\npurposes of this rule, any default value counts as \"complex\" unless it is\na literal `int`, `float`, `complex`, `bytes`, `str`, `bool`, `None`, `...`,\nor a simple container literal.\n\n## Example\n\n```pyi\ndef foo(arg: list[int] = list(range(10_000))) -> None: ...\n```\n\nUse instead:\n\n```pyi\ndef foo(arg: list[int] = ...) -> None: ...\n```\n\n## References\n- [`flake8-pyi`](https://github.com/PyCQA/flake8-pyi/blob/main/ERRORCODES.md)\n",
|
|
284
|
+
"ruff/PYI012": "## What it does\nChecks for the presence of the `pass` statement in non-empty class bodies\nin `.pyi` files.\n\n## Why is this bad?\nThe `pass` statement is always unnecessary in non-empty class bodies in\nstubs.\n\n## Example\n```pyi\nclass MyClass:\n x: int\n pass\n```\n\nUse instead:\n```pyi\nclass MyClass:\n x: int\n```\n",
|
|
285
|
+
"ruff/PYI013": "## What it does\nRemoves ellipses (`...`) in otherwise non-empty class bodies.\n\n## Why is this bad?\nAn ellipsis in a class body is only necessary if the class body is\notherwise empty. If the class body is non-empty, then the ellipsis\nis redundant.\n\n## Example\n```pyi\nclass Foo:\n ...\n value: int\n```\n\nUse instead:\n```pyi\nclass Foo:\n value: int\n```\n",
|
|
286
|
+
"ruff/PYI014": "## What it does\nChecks for untyped function arguments in stubs with default values that\nare not \"simple\" /// (i.e., `int`, `float`, `complex`, `bytes`, `str`,\n`bool`, `None`, `...`, or simple container literals).\n\n## Why is this bad?\nStub (`.pyi`) files exist to define type hints, and are not evaluated at\nruntime. As such, function arguments in stub files should not have default\nvalues, as they are ignored by type checkers.\n\nHowever, the use of default values may be useful for IDEs and other\nconsumers of stub files, and so \"simple\" values may be worth including and\nare permitted by this rule.\n\nInstead of including and reproducing a complex value, use `...` to indicate\nthat the assignment has a default value, but that the value is non-simple\nor varies according to the current platform or Python version.\n\n## Example\n\n```pyi\ndef foo(arg=bar()) -> None: ...\n```\n\nUse instead:\n\n```pyi\ndef foo(arg=...) -> None: ...\n```\n\n## References\n- [`flake8-pyi`](https://github.com/PyCQA/flake8-pyi/blob/main/ERRORCODES.md)\n",
|
|
287
|
+
"ruff/PYI015": "## What it does\nChecks for assignments in stubs with default values that are not \"simple\"\n(i.e., `int`, `float`, `complex`, `bytes`, `str`, `bool`, `None`, `...`, or\nsimple container literals).\n\n## Why is this bad?\nStub (`.pyi`) files exist to define type hints, and are not evaluated at\nruntime. As such, assignments in stub files should not include values,\nas they are ignored by type checkers.\n\nHowever, the use of such values may be useful for IDEs and other consumers\nof stub files, and so \"simple\" values may be worth including and are\npermitted by this rule.\n\nInstead of including and reproducing a complex value, use `...` to indicate\nthat the assignment has a default value, but that the value is non-simple\nor varies according to the current platform or Python version.\n\n## Example\n```pyi\nfoo: str = bar()\n```\n\nUse instead:\n```pyi\nfoo: str = ...\n```\n\n## References\n- [`flake8-pyi`](https://github.com/PyCQA/flake8-pyi/blob/main/ERRORCODES.md)\n",
|
|
288
|
+
"ruff/PYI016": "## What it does\nChecks for duplicate union members.\n\n## Why is this bad?\nDuplicate union members are redundant and should be removed.\n\n## Example\n```python\nfoo: str | str\n```\n\nUse instead:\n```python\nfoo: str\n```\n\n## Fix safety\nThis rule's fix is marked as safe unless the union contains comments.\n\nFor nested union, the fix will flatten type expressions into a single\ntop-level union.\n\n## References\n- [Python documentation: `typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union)\n",
|
|
289
|
+
"ruff/PYI017": "## What it does\nChecks for assignments with multiple or non-name targets in stub files.\n\n## Why is this bad?\nIn general, stub files should be thought of as \"data files\" for a type\nchecker, and are not intended to be executed. As such, it's useful to\nenforce that only a subset of Python syntax is allowed in a stub file, to\nensure that everything in the stub is unambiguous for the type checker.\n\nThe need to perform multi-assignment, or assignment to a non-name target,\nlikely indicates a misunderstanding of how stub files are intended to be\nused.\n\n## Example\n\n```pyi\nfrom typing import TypeAlias\n\na = b = int\n\nclass Klass: ...\n\nKlass.X: TypeAlias = int\n```\n\nUse instead:\n\n```pyi\nfrom typing import TypeAlias\n\na: TypeAlias = int\nb: TypeAlias = int\n\nclass Klass:\n X: TypeAlias = int\n```\n",
|
|
290
|
+
"ruff/PYI018": "## What it does\nChecks for the presence of unused private `TypeVar`, `ParamSpec` or\n`TypeVarTuple` declarations.\n\n## Why is this bad?\nA private `TypeVar` that is defined but not used is likely a mistake. It\nshould either be used, made public, or removed to avoid confusion. A type\nvariable is considered \"private\" if its name starts with an underscore.\n\n## Example\n```pyi\nimport typing\nimport typing_extensions\n\n_T = typing.TypeVar(\"_T\")\n_Ts = typing_extensions.TypeVarTuple(\"_Ts\")\n```\n\n## Fix safety\nThe fix is always marked as unsafe, as it would break your code if the type\nvariable is imported by another module.\n",
|
|
291
|
+
"ruff/PYI019": "## What it does\nChecks for methods that use custom [`TypeVar`s][typing_TypeVar] in their\nannotations when they could use [`Self`][Self] instead.\n\n## Why is this bad?\nWhile the semantics are often identical, using `Self` is more intuitive\nand succinct (per [PEP 673]) than a custom `TypeVar`. For example, the\nuse of `Self` will typically allow for the omission of type parameters\non the `self` and `cls` arguments.\n\nThis check currently applies to instance methods that return `self`,\nclass methods that return an instance of `cls`, class methods that return\n`cls`, and `__new__` methods.\n\n## Example\n\n```pyi\nfrom typing import TypeVar\n\n_S = TypeVar(\"_S\", bound=\"Foo\")\n\nclass Foo:\n def __new__(cls: type[_S], *args: str, **kwargs: int) -> _S: ...\n def foo(self: _S, arg: bytes) -> _S: ...\n @classmethod\n def bar(cls: type[_S], arg: int) -> _S: ...\n```\n\nUse instead:\n\n```pyi\nfrom typing import Self\n\nclass Foo:\n def __new__(cls, *args: str, **kwargs: int) -> Self: ...\n def foo(self, arg: bytes) -> Self: ...\n @classmethod\n def bar(cls, arg: int) -> Self: ...\n```\n\n## Fix behaviour\nThe fix replaces all references to the custom type variable in the method's header and body\nwith references to `Self`. The fix also adds an import of `Self` if neither `Self` nor `typing`\nis already imported in the module. If your [`target-version`] setting is set to Python 3.11 or\nnewer, the fix imports `Self` from the standard-library `typing` module; otherwise, the fix\nimports `Self` from the third-party [`typing_extensions`][typing_extensions] backport package.\n\nIf the custom type variable is a [PEP-695]-style `TypeVar`, the fix also removes the `TypeVar`\ndeclaration from the method's [type parameter list]. However, if the type variable is an\nold-style `TypeVar`, the declaration of the type variable will not be removed by this rule's\nfix, as the type variable could still be used by other functions, methods or classes. See\n[`unused-private-type-var`][PYI018] for a rule that will clean up unused private type\nvariables.\n\n## Fix safety\nThe fix is only marked as unsafe if there is the possibility that it might delete a comment\nfrom your code.\n\n## Availability\n\nBecause this rule relies on the third-party `typing_extensions` module for Python versions\nbefore 3.11, its diagnostic will not be emitted, and no fix will be offered, if\n`typing_extensions` imports have been disabled by the [`lint.typing-extensions`] linter option.\n\n## Options\n\n- `lint.typing-extensions`\n\n[PEP 673]: https://peps.python.org/pep-0673/#motivation\n[PEP-695]: https://peps.python.org/pep-0695/\n[PYI018]: https://docs.astral.sh/ruff/rules/unused-private-type-var/\n[type parameter list]: https://docs.python.org/3/reference/compound_stmts.html#type-params\n[Self]: https://docs.python.org/3/library/typing.html#typing.Self\n[typing_TypeVar]: https://docs.python.org/3/library/typing.html#typing.TypeVar\n[typing_extensions]: https://typing-extensions.readthedocs.io/en/latest/\n",
|
|
292
|
+
"ruff/PYI020": "## What it does\nChecks for quoted type annotations in stub (`.pyi`) files, which should be avoided.\n\n## Why is this bad?\nStub files natively support forward references in all contexts, as stubs\nare never executed at runtime. (They should be thought of as \"data files\"\nfor type checkers and IDEs.) As such, quotes are never required for type\nannotations in stub files, and should be omitted.\n\n## Example\n\n```pyi\ndef function() -> \"int\": ...\n```\n\nUse instead:\n\n```pyi\ndef function() -> int: ...\n```\n\n## References\n- [Typing documentation - Writing and Maintaining Stub Files](https://typing.python.org/en/latest/guides/writing_stubs.html)\n",
|
|
293
|
+
"ruff/PYI021": "## What it does\nChecks for the presence of docstrings in stub files.\n\n## Why is this bad?\nStub files should omit docstrings, as they're intended to provide type\nhints, rather than documentation.\n\n## Example\n\n```pyi\ndef func(param: int) -> str:\n \"\"\"This is a docstring.\"\"\"\n ...\n```\n\nUse instead:\n\n```pyi\ndef func(param: int) -> str: ...\n```\n",
|
|
294
|
+
"ruff/PYI024": "## What it does\nChecks for uses of `collections.namedtuple` in stub files.\n\n## Why is this bad?\n`typing.NamedTuple` is the \"typed version\" of `collections.namedtuple`.\n\nInheriting from `typing.NamedTuple` creates a custom `tuple` subclass in\nthe same way as using the `collections.namedtuple` factory function.\nHowever, using `typing.NamedTuple` allows you to provide a type annotation\nfor each field in the class. This means that type checkers will have more\ninformation to work with, and will be able to analyze your code more\nprecisely.\n\n## Example\n```pyi\nfrom collections import namedtuple\n\nPerson = namedtuple(\"Person\", [\"name\", \"age\"])\n```\n\nUse instead:\n```pyi\nfrom typing import NamedTuple\n\nclass Person(NamedTuple):\n name: str\n age: int\n```\n",
|
|
295
|
+
"ruff/PYI025": "## What it does\nChecks for `from collections.abc import Set` imports that do not alias\n`Set` to `AbstractSet`.\n\n## Why is this bad?\nThe `Set` type in `collections.abc` is an abstract base class for set-like types.\nIt is easily confused with, and not equivalent to, the `set` builtin.\n\nTo avoid confusion, `Set` should be aliased to `AbstractSet` when imported. This\nmakes it clear that the imported type is an abstract base class, and not the\n`set` builtin.\n\n## Example\n```pyi\nfrom collections.abc import Set\n```\n\nUse instead:\n```pyi\nfrom collections.abc import Set as AbstractSet\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe for `Set` imports defined at the\ntop-level of a `.py` module. Top-level symbols are implicitly exported by the\nmodule, and so renaming a top-level symbol may break downstream modules\nthat import it.\n\nThe same is not true for `.pyi` files, where imported symbols are only\nre-exported if they are included in `__all__`, use a \"redundant\"\n`import foo as foo` alias, or are imported via a `*` import. As such, the\nfix is marked as safe in more cases for `.pyi` files.\n",
|
|
296
|
+
"ruff/PYI026": "## What it does\nChecks for type alias definitions that are not annotated with\n`typing.TypeAlias`.\n\n## Why is this bad?\nIn Python, a type alias is defined by assigning a type to a variable (e.g.,\n`Vector = list[float]`).\n\nIt's best to annotate type aliases with the `typing.TypeAlias` type to\nmake it clear that the statement is a type alias declaration, as opposed\nto a normal variable assignment.\n\n## Example\n```pyi\nVector = list[float]\n```\n\nUse instead:\n```pyi\nfrom typing import TypeAlias\n\nVector: TypeAlias = list[float]\n```\n\n## Availability\n\nBecause this rule relies on the third-party `typing_extensions` module for Python versions\nbefore 3.10, its diagnostic will not be emitted, and no fix will be offered, if\n`typing_extensions` imports have been disabled by the [`lint.typing-extensions`] linter option.\n\n## Options\n\n- `lint.typing-extensions`\n",
|
|
297
|
+
"ruff/PYI029": "## What it does\nChecks for redundant definitions of `__str__` or `__repr__` in stubs.\n\n## Why is this bad?\nDefining `__str__` or `__repr__` in a stub is almost always redundant,\nas the signatures are almost always identical to those of the default\nequivalent, `object.__str__` and `object.__repr__`, respectively.\n\n## Example\n\n```pyi\nclass Foo:\n def __repr__(self) -> str: ...\n```\n",
|
|
298
|
+
"ruff/PYI030": "## What it does\nChecks for the presence of multiple literal types in a union.\n\n## Why is this bad?\n`Literal[\"foo\", 42]` has identical semantics to\n`Literal[\"foo\"] | Literal[42]`, but is clearer and more concise.\n\n## Example\n```pyi\nfrom typing import Literal\n\nfield: Literal[1] | Literal[2] | str\n```\n\nUse instead:\n```pyi\nfrom typing import Literal\n\nfield: Literal[1, 2] | str\n```\n\n## Fix safety\nThis fix is marked unsafe if it would delete any comments within the replacement range.\n\nAn example to illustrate where comments are preserved and where they are not:\n\n```pyi\nfrom typing import Literal\n\nfield: (\n # deleted comment\n Literal[\"a\", \"b\"] # deleted comment\n # deleted comment\n | Literal[\"c\", \"d\"] # preserved comment\n)\n```\n\n## References\n- [Python documentation: `typing.Literal`](https://docs.python.org/3/library/typing.html#typing.Literal)\n",
|
|
299
|
+
"ruff/PYI032": "## What it does\nChecks for `__eq__` and `__ne__` implementations that use `typing.Any` as\nthe type annotation for their second parameter.\n\n## Why is this bad?\nThe Python documentation recommends the use of `object` to \"indicate that a\nvalue could be any type in a typesafe manner\". `Any`, on the other hand,\nshould be seen as an \"escape hatch when you need to mix dynamically and\nstatically typed code\". Since using `Any` allows you to write highly unsafe\ncode, you should generally only use `Any` when the semantics of your code\nwould otherwise be inexpressible to the type checker.\n\nThe expectation in Python is that a comparison of two arbitrary objects\nusing `==` or `!=` should never raise an exception. This contract can be\nfully expressed in the type system and does not involve requesting unsound\nbehaviour from a type checker. As such, `object` is a more appropriate\nannotation than `Any` for the second parameter of the methods implementing\nthese comparison operators -- `__eq__` and `__ne__`.\n\n## Example\n\n```pyi\nfrom typing import Any\n\nclass Foo:\n def __eq__(self, obj: Any) -> bool: ...\n```\n\nUse instead:\n\n```pyi\nclass Foo:\n def __eq__(self, obj: object) -> bool: ...\n```\n## References\n- [Python documentation: The `Any` type](https://docs.python.org/3/library/typing.html#the-any-type)\n- [Mypy documentation: Any vs. object](https://mypy.readthedocs.io/en/latest/dynamic_typing.html#any-vs-object)\n",
|
|
300
|
+
"ruff/PYI033": "## What it does\nChecks for the use of type comments (e.g., `x = 1 # type: int`).\n\nBy default, this check only runs on stub files. If [`preview`] mode is enabled,\nthe check also runs on `.py` files.\n\n## Why is this bad?\nType comments are a soft-deprecated form of type annotation. They are unsupported\nby some modern type checkers, including ty and Pyrefly, and are only necessary when\nsupporting end-of-life Python versions such as 3.5 or older. They are never necessary\nin stub files, which are not executed at runtime.\n\nThis rule does not apply to `# type: ignore` suppression comments.\n\n## Example\n```pyi\nx = 1 # type: int\n```\n\nUse instead:\n```pyi\nx: int = 1\n```\n",
|
|
301
|
+
"ruff/PYI034": "## What it does\nChecks for methods that are annotated with a fixed return type which\nshould instead be returning `Self`.\n\n## Why is this bad?\nIf methods that generally return `self` at runtime are annotated with a\nfixed return type, and the class is subclassed, type checkers will not be\nable to infer the correct return type.\n\nFor example:\n```python\nclass Shape:\n def set_scale(self, scale: float) -> Shape:\n self.scale = scale\n return self\n\nclass Circle(Shape):\n def set_radius(self, radius: float) -> Circle:\n self.radius = radius\n return self\n\n# Type checker infers return type as `Shape`, not `Circle`.\nCircle().set_scale(0.5)\n\n# Thus, this expression is invalid, as `Shape` has no attribute `set_radius`.\nCircle().set_scale(0.5).set_radius(2.7)\n```\n\nSpecifically, this check enforces that the return type of the following\nmethods is `Self`:\n\n1. In-place binary-operation dunder methods, like `__iadd__`, `__imul__`, etc.,\n if those methods return the class name.\n1. `__new__`, `__enter__`, and `__aenter__`, if those methods return the\n class name.\n1. `__iter__` methods that return `Iterator`, despite the class inheriting\n directly from `Iterator`.\n1. `__aiter__` methods that return `AsyncIterator`, despite the class\n inheriting directly from `AsyncIterator`.\n\nThe rule attempts to avoid flagging methods on metaclasses, since\n[PEP 673] specifies that `Self` is disallowed in metaclasses. Ruff can\ndetect a class as being a metaclass if it inherits from a stdlib\nmetaclass such as `builtins.type` or `abc.ABCMeta`, and additionally\ninfers that a class may be a metaclass if it has a `__new__` method\nwith a similar signature to `type.__new__`. The heuristic used to\nidentify a metaclass-like `__new__` method signature is that it:\n\n1. Has exactly 5 parameters (including `cls`)\n1. Has a second parameter annotated with `str`\n1. Has a third parameter annotated with a `tuple` type\n1. Has a fourth parameter annotated with a `dict` type\n1. Has a fifth parameter is keyword-variadic (`**kwargs`)\n\nFor example, the following class would be detected as a metaclass, disabling\nthe rule:\n\n```python\nclass MyMetaclass(django.db.models.base.ModelBase):\n def __new__(cls, name: str, bases: tuple[Any, ...], attrs: dict[str, Any], **kwargs: Any) -> MyMetaclass:\n ...\n```\n\n## Example\n\n```pyi\nclass Foo:\n def __new__(cls, *args: Any, **kwargs: Any) -> Foo: ...\n def __enter__(self) -> Foo: ...\n async def __aenter__(self) -> Foo: ...\n def __iadd__(self, other: Foo) -> Foo: ...\n```\n\nUse instead:\n\n```pyi\nfrom typing_extensions import Self\n\nclass Foo:\n def __new__(cls, *args: Any, **kwargs: Any) -> Self: ...\n def __enter__(self) -> Self: ...\n async def __aenter__(self) -> Self: ...\n def __iadd__(self, other: Foo) -> Self: ...\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe as it changes the meaning of your type annotations.\n\n## Availability\n\nBecause this rule relies on the third-party `typing_extensions` module for Python versions\nbefore 3.11, its diagnostic will not be emitted, and no fix will be offered, if\n`typing_extensions` imports have been disabled by the [`lint.typing-extensions`] linter option.\n\n## Options\n\n- `lint.typing-extensions`\n\n## References\n- [Python documentation: `typing.Self`](https://docs.python.org/3/library/typing.html#typing.Self)\n\n[PEP 673]: https://peps.python.org/pep-0673/#valid-locations-for-self\n",
|
|
302
|
+
"ruff/PYI035": "## What it does\nChecks that `__all__`, `__match_args__`, and `__slots__` variables are\nassigned to values when defined in stub files.\n\n## Why is this bad?\nSpecial variables like `__all__` have the same semantics in stub files\nas they do in Python modules, and so should be consistent with their\nruntime counterparts.\n\n## Example\n```pyi\n__all__: list[str]\n```\n\nUse instead:\n```pyi\n__all__: list[str] = [\"foo\", \"bar\"]\n```\n",
|
|
303
|
+
"ruff/PYI036": "## What it does\nChecks for incorrect function signatures on `__exit__` and `__aexit__`\nmethods.\n\n## Why is this bad?\nImproperly annotated `__exit__` and `__aexit__` methods can cause\nunexpected behavior when interacting with type checkers.\n\n## Example\n\n```pyi\nfrom types import TracebackType\n\nclass Foo:\n def __exit__(\n self, typ: BaseException, exc: BaseException, tb: TracebackType\n ) -> None: ...\n```\n\nUse instead:\n\n```pyi\nfrom types import TracebackType\n\nclass Foo:\n def __exit__(\n self,\n typ: type[BaseException] | None,\n exc: BaseException | None,\n tb: TracebackType | None,\n ) -> None: ...\n```\n",
|
|
304
|
+
"ruff/PYI041": "## What it does\nChecks for parameter annotations that contain redundant unions between\nbuiltin numeric types (e.g., `int | float`).\n\n## Why is this bad?\nThe [typing specification] states:\n\n> Python\u2019s numeric types `complex`, `float` and `int` are not subtypes of\n> each other, but to support common use cases, the type system contains a\n> straightforward shortcut: when an argument is annotated as having type\n> `float`, an argument of type `int` is acceptable; similar, for an\n> argument annotated as having type `complex`, arguments of type `float` or\n> `int` are acceptable.\n\nAs such, a union that includes both `int` and `float` is redundant in the\nspecific context of a parameter annotation, as it is equivalent to a union\nthat only includes `float`. For readability and clarity, unions should omit\nredundant elements.\n\n## Example\n\n```pyi\ndef foo(x: float | int | str) -> None: ...\n```\n\nUse instead:\n\n```pyi\ndef foo(x: float | str) -> None: ...\n```\n\n## Fix safety\nThis rule's fix is marked as safe, unless the type annotation contains comments.\n\nNote that while the fix may flatten nested unions into a single top-level union,\nthe semantics of the annotation will remain unchanged.\n\n## References\n- [Python documentation: The numeric tower](https://docs.python.org/3/library/numbers.html#the-numeric-tower)\n- [PEP 484: The numeric tower](https://peps.python.org/pep-0484/#the-numeric-tower)\n\n[typing specification]: https://typing.python.org/en/latest/spec/special-types.html#special-cases-for-float-and-complex\n",
|
|
305
|
+
"ruff/PYI042": "## What it does\nChecks for type aliases that do not use the CamelCase naming convention.\n\n## Why is this bad?\nIt's conventional to use the CamelCase naming convention for type aliases,\nto distinguish them from other variables.\n\n## Example\n```pyi\nfrom typing import TypeAlias\n\ntype_alias_name: TypeAlias = int\n```\n\nUse instead:\n```pyi\nfrom typing import TypeAlias\n\nTypeAliasName: TypeAlias = int\n```\n",
|
|
306
|
+
"ruff/PYI043": "## What it does\nChecks for private type alias definitions suffixed with 'T'.\n\n## Why is this bad?\nIt's conventional to use the 'T' suffix for type variables; the use of\nsuch a suffix implies that the object is a `TypeVar`.\n\nAdding the 'T' suffix to a non-`TypeVar`, it can be misleading and should\nbe avoided.\n\n## Example\n```pyi\nfrom typing import TypeAlias\n\n_MyTypeT: TypeAlias = int\n```\n\nUse instead:\n```pyi\nfrom typing import TypeAlias\n\n_MyType: TypeAlias = int\n```\n\n## References\n- [PEP 484: Type Aliases](https://peps.python.org/pep-0484/#type-aliases)\n",
|
|
307
|
+
"ruff/PYI044": "## What it does\nChecks for the presence of the `from __future__ import annotations` import\nstatement in stub files.\n\n## Why is this bad?\nStub files natively support forward references in all contexts, as stubs are\nnever executed at runtime. (They should be thought of as \"data files\" for\ntype checkers.) As such, the `from __future__ import annotations` import\nstatement has no effect and should be omitted.\n\n## References\n- [Typing Style Guide](https://typing.python.org/en/latest/guides/writing_stubs.html#language-features)\n",
|
|
308
|
+
"ruff/PYI045": "## What it does\nChecks for `__iter__` methods in stubs that return `Iterable[T]` instead\nof an `Iterator[T]`.\n\n## Why is this bad?\n`__iter__` methods should always should return an `Iterator` of some kind,\nnot an `Iterable`.\n\nIn Python, an `Iterable` is an object that has an `__iter__` method; an\n`Iterator` is an object that has `__iter__` and `__next__` methods. All\n`__iter__` methods are expected to return `Iterator`s. Type checkers may\nnot always recognize an object as being iterable if its `__iter__` method\ndoes not return an `Iterator`.\n\nEvery `Iterator` is an `Iterable`, but not every `Iterable` is an `Iterator`.\nFor example, `list` is an `Iterable`, but not an `Iterator`; you can obtain\nan iterator over a list's elements by passing the list to `iter()`:\n\n```pycon\n>>> import collections.abc\n>>> x = [42]\n>>> isinstance(x, collections.abc.Iterable)\nTrue\n>>> isinstance(x, collections.abc.Iterator)\nFalse\n>>> next(x)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: 'list' object is not an iterator\n>>> y = iter(x)\n>>> isinstance(y, collections.abc.Iterable)\nTrue\n>>> isinstance(y, collections.abc.Iterator)\nTrue\n>>> next(y)\n42\n```\n\nUsing `Iterable` rather than `Iterator` as a return type for an `__iter__`\nmethods would imply that you would not necessarily be able to call `next()`\non the returned object, violating the expectations of the interface.\n\n## Example\n\n```python\nimport collections.abc\n\n\nclass Klass:\n def __iter__(self) -> collections.abc.Iterable[str]: ...\n```\n\nUse instead:\n\n```python\nimport collections.abc\n\n\nclass Klass:\n def __iter__(self) -> collections.abc.Iterator[str]: ...\n```\n",
|
|
309
|
+
"ruff/PYI046": "## What it does\nChecks for the presence of unused private `typing.Protocol` definitions.\n\n## Why is this bad?\nA private `typing.Protocol` that is defined but not used is likely a\nmistake. It should either be used, made public, or removed to avoid\nconfusion.\n\n## Example\n\n```pyi\nimport typing\n\nclass _PrivateProtocol(typing.Protocol):\n foo: int\n```\n\nUse instead:\n\n```pyi\nimport typing\n\nclass _PrivateProtocol(typing.Protocol):\n foo: int\n\ndef func(arg: _PrivateProtocol) -> None: ...\n```\n",
|
|
310
|
+
"ruff/PYI047": "## What it does\nChecks for the presence of unused private type aliases.\n\n## Why is this bad?\nA private type alias that is defined but not used is likely a\nmistake. It should either be used, made public, or removed to avoid\nconfusion.\n\n## Example\n\n```pyi\nimport typing\n\n_UnusedTypeAlias: typing.TypeAlias = int\n```\n\nUse instead:\n\n```pyi\nimport typing\n\n_UsedTypeAlias: typing.TypeAlias = int\n\ndef func(arg: _UsedTypeAlias) -> _UsedTypeAlias: ...\n```\n",
|
|
311
|
+
"ruff/PYI048": "## What it does\nChecks for functions in stub (`.pyi`) files that contain multiple\nstatements.\n\n## Why is this bad?\nStub files are never executed, and are only intended to define type hints.\nAs such, functions in stub files should not contain functional code, and\nshould instead contain only a single statement (e.g., `...`).\n\n## Example\n\n```pyi\ndef function():\n x = 1\n y = 2\n return x + y\n```\n\nUse instead:\n\n```pyi\ndef function(): ...\n```\n",
|
|
312
|
+
"ruff/PYI049": "## What it does\nChecks for the presence of unused private `typing.TypedDict` definitions.\n\n## Why is this bad?\nA private `typing.TypedDict` that is defined but not used is likely a\nmistake. It should either be used, made public, or removed to avoid\nconfusion.\n\n## Example\n\n```pyi\nimport typing\n\nclass _UnusedPrivateTypedDict(typing.TypedDict):\n foo: list[int]\n```\n\nUse instead:\n\n```pyi\nimport typing\n\nclass _UsedPrivateTypedDict(typing.TypedDict):\n foo: set[str]\n\ndef func(arg: _UsedPrivateTypedDict) -> _UsedPrivateTypedDict: ...\n```\n",
|
|
313
|
+
"ruff/PYI050": "## What it does\nChecks for uses of `typing.NoReturn` (and `typing_extensions.NoReturn`) for\nparameter annotations.\n\n## Why is this bad?\nPrefer `Never` over `NoReturn` for parameter annotations. `Never` has a\nclearer name in these contexts, since it makes little sense to talk about a\nparameter annotation \"not returning\".\n\nThis is a purely stylistic lint: the two types have identical semantics for\ntype checkers. Both represent Python's \"[bottom type]\" (a type that has no\nmembers).\n\n## Example\n```pyi\nfrom typing import NoReturn\n\ndef foo(x: NoReturn): ...\n```\n\nUse instead:\n```pyi\nfrom typing import Never\n\ndef foo(x: Never): ...\n```\n\n## References\n- [Python documentation: `typing.Never`](https://docs.python.org/3/library/typing.html#typing.Never)\n- [Python documentation: `typing.NoReturn`](https://docs.python.org/3/library/typing.html#typing.NoReturn)\n\n[bottom type]: https://en.wikipedia.org/wiki/Bottom_type\n",
|
|
314
|
+
"ruff/PYI051": "## What it does\nChecks for redundant unions between a `Literal` and a builtin supertype of\nthat `Literal`.\n\n## Why is this bad?\nUsing a `Literal` type in a union with its builtin supertype is redundant,\nas the supertype will be strictly more general than the `Literal` type.\nFor example, `Literal[\"A\"] | str` is equivalent to `str`, and\n`Literal[1] | int` is equivalent to `int`, as `str` and `int` are the\nsupertypes of `\"A\"` and `1` respectively.\n\n## Example\n```pyi\nfrom typing import Literal\n\nx: Literal[\"A\", b\"B\"] | str\n```\n\nUse instead:\n```pyi\nfrom typing import Literal\n\nx: Literal[b\"B\"] | str\n```\n\n## Known issues\nThis rule is opinionated and may not be appropriate for projects that keep\nliteral members for editor suggestions, generated documentation, or another\nnon-type-checking purpose. In those cases, disabling this rule for the\naffected annotations may be reasonable.\n",
|
|
315
|
+
"ruff/PYI052": "## What it does\nChecks for unannotated assignments in stub (`.pyi`) files.\n\n## Why is this bad?\nStub files exist to provide type hints, and are never executed. As such,\nall assignments in stub files should be annotated with a type.\n",
|
|
316
|
+
"ruff/PYI053": "## What it does\nChecks for the use of string and bytes literals longer than 50 characters\nin stub (`.pyi`) files.\n\n## Why is this bad?\nIf a function or variable has a default value where the string or bytes\nrepresentation is greater than 50 characters long, it is likely to be an\nimplementation detail or a constant that varies depending on the system\nyou're running on.\n\nAlthough IDEs may find them useful, default values are ignored by type\ncheckers, the primary consumers of stub files. Replace very long constants\nwith ellipses (`...`) to simplify the stub.\n\nThe rule does not apply to long entries in `__all__`, which are assumed to\nbe outside the stub author's control.\n\n## Example\n\n```pyi\ndef foo(arg: str = \"51 character stringgggggggggggggggggggggggggggggggg\") -> None: ...\n```\n\nUse instead:\n\n```pyi\ndef foo(arg: str = ...) -> None: ...\n```\n",
|
|
317
|
+
"ruff/PYI054": "## What it does\nChecks for numeric literals with a string representation longer than ten\ncharacters.\n\n## Why is this bad?\nIf a function has a default value where the literal representation is\ngreater than 10 characters, the value is likely to be an implementation\ndetail or a constant that varies depending on the system you're running on.\n\nDefault values like these should generally be omitted from stubs. Use\nellipses (`...`) instead.\n\n## Example\n\n```pyi\ndef foo(arg: int = 693568516352839939918568862861217771399698285293568) -> None: ...\n```\n\nUse instead:\n\n```pyi\ndef foo(arg: int = ...) -> None: ...\n```\n",
|
|
318
|
+
"ruff/PYI055": "## What it does\nChecks for the presence of multiple `type`s in a union.\n\n## Why is this bad?\n`type[T | S]` has identical semantics to `type[T] | type[S]` in a type\nannotation, but is cleaner and more concise.\n\n## Example\n```pyi\nfield: type[int] | type[float] | str\n```\n\nUse instead:\n```pyi\nfield: type[int | float] | str\n```\n\n## Fix safety\nThis rule's fix is marked as safe, unless the type annotation contains comments.\n\nNote that while the fix may flatten nested unions into a single top-level union,\nthe semantics of the annotation will remain unchanged.\n",
|
|
319
|
+
"ruff/PYI056": "## What it does\nChecks that `append`, `extend` and `remove` methods are not called on\n`__all__`.\n\n## Why is this bad?\nDifferent type checkers have varying levels of support for calling these\nmethods on `__all__`. Instead, use the `+=` operator to add items to\n`__all__`, which is known to be supported by all major type checkers.\n\n## Example\n```pyi\nimport sys\n\n__all__ = [\"A\", \"B\"]\n\nif sys.version_info >= (3, 10):\n __all__.append(\"C\")\n\nif sys.version_info >= (3, 11):\n __all__.remove(\"B\")\n```\n\nUse instead:\n```pyi\nimport sys\n\n__all__ = [\"A\"]\n\nif sys.version_info < (3, 11):\n __all__ += [\"B\"]\n\nif sys.version_info >= (3, 10):\n __all__ += [\"C\"]\n```\n",
|
|
320
|
+
"ruff/PYI057": "## What it does\nChecks for uses of `typing.ByteString` or `collections.abc.ByteString`.\n\n## Why is this bad?\n`ByteString` has been deprecated since Python 3.9 and will be removed in\nPython 3.17. The Python documentation recommends using either\n`collections.abc.Buffer` (or the `typing_extensions` backport\non Python <3.12) or a union like `bytes | bytearray | memoryview` instead.\n\n## Example\n```python\nfrom typing import ByteString\n```\n\nUse instead:\n```python\nfrom collections.abc import Buffer\n```\n\n## References\n- [Python documentation: The `ByteString` type](https://docs.python.org/3/library/typing.html#typing.ByteString)\n",
|
|
321
|
+
"ruff/PYI058": "## What it does\nChecks for simple `__iter__` methods that return `Generator`, and for\nsimple `__aiter__` methods that return `AsyncGenerator`.\n\n## Why is this bad?\nUsing `(Async)Iterator` for these methods is simpler and more elegant. More\nimportantly, it also reflects the fact that the precise kind of iterator\nreturned from an `__iter__` method is usually an implementation detail that\ncould change at any time. Type annotations help define a contract for a\nfunction; implementation details should not leak into that contract.\n\nFor example:\n```python\nfrom collections.abc import AsyncGenerator, Generator\nfrom typing import Any\n\n\nclass CustomIterator:\n def __iter__(self) -> Generator:\n yield from range(42)\n\n\nclass CustomIterator2:\n def __iter__(self) -> Generator[str, Any, None]:\n yield from \"abcdefg\"\n```\n\nUse instead:\n```python\nfrom collections.abc import Iterator\n\n\nclass CustomIterator:\n def __iter__(self) -> Iterator:\n yield from range(42)\n\n\nclass CustomIterator2:\n def __iter__(self) -> Iterator[str]:\n yield from \"abdefg\"\n```\n\n## Fix safety\nThis rule tries hard to avoid false-positive errors, and the rule's fix\nshould always be safe for `.pyi` stub files. However, there is a slightly\nhigher chance that a false positive might be emitted by this rule when\napplied to runtime Python (`.py` files). As such, the fix is marked as\nunsafe for any `__iter__` or `__aiter__` method in a `.py` file that has\nmore than two statements (including docstrings) in its body.\n",
|
|
322
|
+
"ruff/PYI059": "## What it does\nChecks for classes inheriting from `typing.Generic[]` where `Generic[]` is\nnot the last base class in the bases tuple.\n\n## Why is this bad?\nIf `Generic[]` is not the final class in the bases tuple, unexpected\nbehaviour can occur at runtime (See [this CPython issue][1] for an example).\n\nThe rule is also applied to stub files, where it won't cause issues at\nruntime. This is because type checkers may not be able to infer an\naccurate [MRO] for the class, which could lead to unexpected or\ninaccurate results when they analyze your code.\n\nFor example:\n```python\nfrom collections.abc import Container, Iterable, Sized\nfrom typing import Generic, TypeVar\n\n\nT = TypeVar(\"T\")\nK = TypeVar(\"K\")\nV = TypeVar(\"V\")\n\n\nclass LinkedList(Generic[T], Sized):\n def push(self, item: T) -> None:\n self._items.append(item)\n\n\nclass MyMapping(\n Generic[K, V],\n Iterable[tuple[K, V]],\n Container[tuple[K, V]],\n):\n ...\n```\n\nUse instead:\n```python\nfrom collections.abc import Container, Iterable, Sized\nfrom typing import Generic, TypeVar\n\n\nT = TypeVar(\"T\")\nK = TypeVar(\"K\")\nV = TypeVar(\"V\")\n\n\nclass LinkedList(Sized, Generic[T]):\n def push(self, item: T) -> None:\n self._items.append(item)\n\n\nclass MyMapping(\n Iterable[tuple[K, V]],\n Container[tuple[K, V]],\n Generic[K, V],\n):\n ...\n```\n\n## Fix safety\n\nThis rule's fix is always unsafe because reordering base classes can change\nthe behavior of the code by modifying the class's MRO. The fix will also\ndelete trailing comments after the `Generic` base class in multi-line base\nclass lists, if any are present.\n\n## Fix availability\n\nThis rule's fix is only available when there are no `*args` present in the base class list.\n\n## References\n- [`typing.Generic` documentation](https://docs.python.org/3/library/typing.html#typing.Generic)\n\n[1]: https://github.com/python/cpython/issues/106102\n[MRO]: https://docs.python.org/3/glossary.html#term-method-resolution-order\n",
|
|
323
|
+
"ruff/PYI061": "## What it does\nChecks for redundant `Literal[None]` annotations.\n\n## Why is this bad?\nWhile `Literal[None]` is a valid type annotation, it is semantically equivalent to `None`.\nPrefer `None` over `Literal[None]` for both consistency and readability.\n\n## Example\n```python\nfrom typing import Literal\n\nLiteral[None]\nLiteral[1, 2, 3, \"foo\", 5, None]\n```\n\nUse instead:\n```python\nfrom typing import Literal\n\nNone\nLiteral[1, 2, 3, \"foo\", 5] | None\n```\n\n## Fix safety and availability\nIn Python files, this rule's fix is marked as unsafe because replacing\n`Literal[...]` can change runtime-visible annotation objects, such as the\nresult of `typing.get_args`.\n\nIn stub files, the fix is marked as safe unless the literal contains comments.\n\nThere is currently no fix available when applying the fix would lead to\na `TypeError` from an expression of the form `None | None` or when we\nare unable to import the symbol `typing.Optional` and the Python version\nis 3.9 or below.\n\n## References\n- [Typing documentation: Legal parameters for `Literal` at type check time](https://typing.python.org/en/latest/spec/literal.html#legal-parameters-for-literal-at-type-check-time)\n",
|
|
324
|
+
"ruff/PYI062": "## What it does\nChecks for duplicate members in a `typing.Literal[]` slice.\n\n## Why is this bad?\nDuplicate literal members are redundant and should be removed.\n\n## Example\n```python\nfrom typing import Literal\n\nfoo: Literal[\"a\", \"b\", \"a\"]\n```\n\nUse instead:\n```python\nfrom typing import Literal\n\nfoo: Literal[\"a\", \"b\"]\n```\n\n## Fix safety\nThis rule's fix is marked as safe, unless the type annotation contains comments.\n\nNote that while the fix may flatten nested literals into a single top-level literal,\nthe semantics of the annotation will remain unchanged.\n\n## References\n- [Python documentation: `typing.Literal`](https://docs.python.org/3/library/typing.html#typing.Literal)\n",
|
|
325
|
+
"ruff/PYI063": "## What it does\nChecks for the presence of [PEP 484]-style positional-only parameters.\n\n## Why is this bad?\nHistorically, [PEP 484] recommended prefixing parameter names with double\nunderscores (`__`) to indicate to a type checker that they were\npositional-only. However, [PEP 570] (introduced in Python 3.8) introduced\ndedicated syntax for positional-only arguments. If a forward slash (`/`) is\npresent in a function signature on Python 3.8+, all parameters prior to the\nslash are interpreted as positional-only.\n\nThe new syntax should be preferred as it is more widely used, more concise\nand more readable. It is also respected by Python at runtime, whereas the\nold-style syntax was only understood by type checkers.\n\n## Example\n\n```pyi\ndef foo(__x: int) -> None: ...\n```\n\nUse instead:\n\n```pyi\ndef foo(x: int, /) -> None: ...\n```\n\n## Options\n- `target-version`\n\n[PEP 484]: https://peps.python.org/pep-0484/#positional-only-arguments\n[PEP 570]: https://peps.python.org/pep-0570\n",
|
|
326
|
+
"ruff/PYI064": "## What it does\nChecks for redundant `Final[Literal[...]]` annotations.\n\n## Why is this bad?\nAll constant variables annotated as `Final` are understood as implicitly\nhaving `Literal` types by a type checker. As such, a `Final[Literal[...]]`\nannotation can often be replaced with a bare `Final`, annotation, which\nwill have the same meaning to the type checker while being more concise and\nmore readable.\n\n## Example\n\n```pyi\nfrom typing import Final, Literal\n\nx: Final[Literal[42]]\ny: Final[Literal[42]] = 42\n```\n\nUse instead:\n```pyi\nfrom typing import Final, Literal\n\nx: Final = 42\ny: Final = 42\n```\n",
|
|
327
|
+
"ruff/PYI066": "## What it does\nChecks for code that branches on `sys.version_info` comparisons where\nbranches corresponding to older Python versions come before branches\ncorresponding to newer Python versions.\n\n## Why is this bad?\nAs a convention, branches that correspond to newer Python versions should\ncome first. This makes it easier to understand the desired behavior, which\ntypically corresponds to the latest Python versions.\n\nThis rule enforces the convention by checking for `if` tests that compare\n`sys.version_info` with `<` rather than `>=`.\n\nBy default, this rule only applies to stub files.\nIn [preview], it will also flag this anti-pattern in non-stub files.\n\n## Example\n\n```pyi\nimport sys\n\nif sys.version_info < (3, 10):\n def read_data(x, *, preserve_order=True): ...\n\nelse:\n def read_data(x): ...\n```\n\nUse instead:\n\n```pyi\nif sys.version_info >= (3, 10):\n def read_data(x): ...\n\nelse:\n def read_data(x, *, preserve_order=True): ...\n```\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
328
|
+
"ruff/PT001": "## What it does\nChecks for argument-free `@pytest.fixture()` decorators with or without\nparentheses, depending on the [`lint.flake8-pytest-style.fixture-parentheses`]\nsetting.\n\n## Why is this bad?\nIf a `@pytest.fixture()` doesn't take any arguments, the parentheses are\noptional.\n\nEither removing those unnecessary parentheses _or_ requiring them for all\nfixtures is fine, but it's best to be consistent. The rule defaults to\nremoving unnecessary parentheses, to match the documentation of the\nofficial pytest projects.\n\n## Example\n\n```python\nimport pytest\n\n\n@pytest.fixture()\ndef my_fixture(): ...\n```\n\nUse instead:\n\n```python\nimport pytest\n\n\n@pytest.fixture\ndef my_fixture(): ...\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe if there's comments in the\n`pytest.fixture` decorator.\n\nFor example, the fix would be marked as unsafe in the following case:\n```python\nimport pytest\n\n\n@pytest.fixture(\n # comment\n # scope = \"module\"\n)\ndef my_fixture(): ...\n```\n\n## Options\n- `lint.flake8-pytest-style.fixture-parentheses`\n\n## References\n- [`pytest` documentation: API Reference: Fixtures](https://docs.pytest.org/en/latest/reference/reference.html#fixtures-api)\n",
|
|
329
|
+
"ruff/PT002": "## What it does\nChecks for `pytest.fixture` calls with positional arguments.\n\n## Why is this bad?\nFor clarity and consistency, prefer using keyword arguments to specify\nfixture configuration.\n\n## Example\n\n```python\nimport pytest\n\n\n@pytest.fixture(\"module\")\ndef my_fixture(): ...\n```\n\nUse instead:\n\n```python\nimport pytest\n\n\n@pytest.fixture(scope=\"module\")\ndef my_fixture(): ...\n```\n\n## References\n- [`pytest` documentation: `@pytest.fixture` functions](https://docs.pytest.org/en/latest/reference/reference.html#pytest-fixture)\n",
|
|
330
|
+
"ruff/PT003": "## What it does\nChecks for `pytest.fixture` calls with `scope=\"function\"`.\n\n## Why is this bad?\n`scope=\"function\"` can be omitted, as it is the default.\n\n## Example\n\n```python\nimport pytest\n\n\n@pytest.fixture(scope=\"function\")\ndef my_fixture(): ...\n```\n\nUse instead:\n\n```python\nimport pytest\n\n\n@pytest.fixture()\ndef my_fixture(): ...\n```\n\n## References\n- [`pytest` documentation: `@pytest.fixture` functions](https://docs.pytest.org/en/latest/reference/reference.html#pytest-fixture)\n",
|
|
331
|
+
"ruff/PT004": "## Removal\nThis rule has been removed because marking fixtures that do not return a value with an underscore\nisn't a practice recommended by the pytest community.\n\n## What it does\nChecks for `pytest` fixtures that do not return a value, but are not named\nwith a leading underscore.\n\n## Why is this bad?\nBy convention, fixtures that don't return a value should be named with a\nleading underscore, while fixtures that do return a value should not.\n\nThis rule ignores abstract fixtures and generators.\n\n## Example\n```python\nimport pytest\n\n\n@pytest.fixture()\ndef patch_something(mocker):\n mocker.patch(\"module.object\")\n\n\n@pytest.fixture()\ndef use_context():\n with create_context():\n yield\n```\n\nUse instead:\n```python\nimport pytest\n\n\n@pytest.fixture()\ndef _patch_something(mocker):\n mocker.patch(\"module.object\")\n\n\n@pytest.fixture()\ndef _use_context():\n with create_context():\n yield\n```\n\n## References\n- [`pytest` documentation: `@pytest.fixture` functions](https://docs.pytest.org/en/latest/reference/reference.html#pytest-fixture)\n",
|
|
332
|
+
"ruff/PT005": "## Removal\nThis rule has been removed because marking fixtures that do not return a value with an underscore\nisn't a practice recommended by the pytest community.\n\n## What it does\nChecks for `pytest` fixtures that return a value, but are named with a\nleading underscore.\n\n## Why is this bad?\nBy convention, fixtures that don't return a value should be named with a\nleading underscore, while fixtures that do return a value should not.\n\nThis rule ignores abstract fixtures.\n\n## Example\n```python\nimport pytest\n\n\n@pytest.fixture()\ndef _some_object():\n return SomeClass()\n\n\n@pytest.fixture()\ndef _some_object_with_cleanup():\n obj = SomeClass()\n yield obj\n obj.cleanup()\n```\n\nUse instead:\n```python\nimport pytest\n\n\n@pytest.fixture()\ndef some_object():\n return SomeClass()\n\n\n@pytest.fixture()\ndef some_object_with_cleanup():\n obj = SomeClass()\n yield obj\n obj.cleanup()\n```\n\n## References\n- [`pytest` documentation: `@pytest.fixture` functions](https://docs.pytest.org/en/latest/reference/reference.html#pytest-fixture)\n",
|
|
333
|
+
"ruff/PT006": "## What it does\nChecks for the type of parameter names passed to `pytest.mark.parametrize`.\n\n## Why is this bad?\nThe `argnames` argument of `pytest.mark.parametrize` takes a string or\na sequence of strings. For a single parameter, it's preferable to use a\nstring. For multiple parameters, it's preferable to use the style\nconfigured via the [`lint.flake8-pytest-style.parametrize-names-type`] setting.\n\n## Example\n\n```python\nimport pytest\n\n\n# single parameter, always expecting string\n@pytest.mark.parametrize((\"param\",), [1, 2, 3])\ndef test_foo(param): ...\n\n\n# multiple parameters, expecting tuple\n@pytest.mark.parametrize([\"param1\", \"param2\"], [(1, 2), (3, 4)])\ndef test_bar(param1, param2): ...\n\n\n# multiple parameters, expecting tuple\n@pytest.mark.parametrize(\"param1,param2\", [(1, 2), (3, 4)])\ndef test_baz(param1, param2): ...\n```\n\nUse instead:\n\n```python\nimport pytest\n\n\n@pytest.mark.parametrize(\"param\", [1, 2, 3])\ndef test_foo(param): ...\n\n\n@pytest.mark.parametrize((\"param1\", \"param2\"), [(1, 2), (3, 4)])\ndef test_bar(param1, param2): ...\n```\n\n## Options\n- `lint.flake8-pytest-style.parametrize-names-type`\n\n## References\n- [`pytest` documentation: How to parametrize fixtures and test functions](https://docs.pytest.org/en/latest/how-to/parametrize.html#pytest-mark-parametrize)\n",
|
|
334
|
+
"ruff/PT007": "## What it does\nChecks for the type of parameter values passed to `pytest.mark.parametrize`.\n\n## Why is this bad?\nThe `argvalues` argument of `pytest.mark.parametrize` takes an iterator of\nparameter values, which can be provided as lists or tuples.\n\nTo aid in readability, it's recommended to use a consistent style for the\nlist of values rows, and, in the case of multiple parameters, for each row\nof values.\n\nThe style for the list of values rows can be configured via the\n[`lint.flake8-pytest-style.parametrize-values-type`] setting, while the\nstyle for each row of values can be configured via the\n[`lint.flake8-pytest-style.parametrize-values-row-type`] setting.\n\nFor example, [`lint.flake8-pytest-style.parametrize-values-type`] will lead to\nthe following expectations:\n\n- `tuple`: `@pytest.mark.parametrize(\"value\", (\"a\", \"b\", \"c\"))`\n- `list`: `@pytest.mark.parametrize(\"value\", [\"a\", \"b\", \"c\"])`\n\nSimilarly, [`lint.flake8-pytest-style.parametrize-values-row-type`] will lead to\nthe following expectations:\n\n- `tuple`: `@pytest.mark.parametrize((\"key\", \"value\"), [(\"a\", \"b\"), (\"c\", \"d\")])`\n- `list`: `@pytest.mark.parametrize((\"key\", \"value\"), [[\"a\", \"b\"], [\"c\", \"d\"]])`\n\n## Example\n\n```python\nimport pytest\n\n\n# expected list, got tuple\n@pytest.mark.parametrize(\"param\", (1, 2))\ndef test_foo(param): ...\n\n\n# expected top-level list, got tuple\n@pytest.mark.parametrize(\n (\"param1\", \"param2\"),\n (\n (1, 2),\n (3, 4),\n ),\n)\ndef test_bar(param1, param2): ...\n\n\n# expected individual rows to be tuples, got lists\n@pytest.mark.parametrize(\n (\"param1\", \"param2\"),\n [\n [1, 2],\n [3, 4],\n ],\n)\ndef test_baz(param1, param2): ...\n```\n\nUse instead:\n\n```python\nimport pytest\n\n\n@pytest.mark.parametrize(\"param\", [1, 2, 3])\ndef test_foo(param): ...\n\n\n@pytest.mark.parametrize((\"param1\", \"param2\"), [(1, 2), (3, 4)])\ndef test_bar(param1, param2): ...\n```\n\n## Options\n- `lint.flake8-pytest-style.parametrize-values-type`\n- `lint.flake8-pytest-style.parametrize-values-row-type`\n\n## References\n- [`pytest` documentation: How to parametrize fixtures and test functions](https://docs.pytest.org/en/latest/how-to/parametrize.html#pytest-mark-parametrize)\n",
|
|
335
|
+
"ruff/PT008": "## What it does\nChecks for mocked calls that use a dummy `lambda` function instead of\n`return_value`.\n\n## Why is this bad?\nWhen patching calls, an explicit `return_value` better conveys the intent\nthan a `lambda` function, assuming the `lambda` does not use the arguments\npassed to it.\n\n`return_value` is also robust to changes in the patched function's\nsignature, and enables additional assertions to verify behavior. For\nexample, `return_value` allows for verification of the number of calls or\nthe arguments passed to the patched function via `assert_called_once_with`\nand related methods.\n\n## Example\n```python\ndef test_foo(mocker):\n mocker.patch(\"module.target\", lambda x, y: 7)\n```\n\nUse instead:\n```python\ndef test_foo(mocker):\n mocker.patch(\"module.target\", return_value=7)\n\n # If the lambda makes use of the arguments, no diagnostic is emitted.\n mocker.patch(\"module.other_target\", lambda x, y: x)\n```\n\n## References\n- [Python documentation: `unittest.mock.patch`](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch)\n- [PyPI: `pytest-mock`](https://pypi.org/project/pytest-mock/)\n",
|
|
336
|
+
"ruff/PT009": "## What it does\nChecks for uses of assertion methods from the `unittest` module.\n\n## Why is this bad?\nTo make use of `pytest`'s assertion rewriting, a regular `assert` statement\nis preferred over `unittest`'s assertion methods.\n\n## Example\n```python\nimport unittest\n\n\nclass TestFoo(unittest.TestCase):\n def test_foo(self):\n self.assertEqual(a, b)\n```\n\nUse instead:\n```python\nimport unittest\n\n\nclass TestFoo(unittest.TestCase):\n def test_foo(self):\n assert a == b\n```\n\n## References\n- [`pytest` documentation: Assertion introspection details](https://docs.pytest.org/en/7.1.x/how-to/assert.html#assertion-introspection-details)\n",
|
|
337
|
+
"ruff/PT010": "## What it does\nChecks for `pytest.raises` calls without an expected exception.\n\n## Why is this bad?\n`pytest.raises` expects to receive an expected exception as its first\nargument. If omitted, the `pytest.raises` call will fail at runtime.\nThe rule will also accept calls without an expected exception but with\n`match` and/or `check` keyword arguments, which are also valid after\npytest version 8.4.0.\n\n## Example\n```python\nimport pytest\n\n\ndef test_foo():\n with pytest.raises():\n do_something()\n```\n\nUse instead:\n```python\nimport pytest\n\n\ndef test_foo():\n with pytest.raises(SomeException):\n do_something()\n```\n\n## References\n- [`pytest` documentation: `pytest.raises`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-raises)\n",
|
|
338
|
+
"ruff/PT011": "## What it does\nChecks for `pytest.raises` calls without a `match` or `check` parameter.\n\n## Why is this bad?\n`pytest.raises(Error)` will catch any `Error` and may catch errors that are\nunrelated to the code under test. To avoid this, `pytest.raises` should be\ncalled with a `match` parameter (to constrain the exception message) or a\n`check` parameter (to constrain the exception itself). The exception names\nthat require a `match` or `check` parameter can be configured via the\n[`lint.flake8-pytest-style.raises-require-match-for`] and\n[`lint.flake8-pytest-style.raises-extend-require-match-for`] settings.\n\n## Example\n```python\nimport pytest\n\n\ndef test_foo():\n with pytest.raises(ValueError):\n ...\n\n # empty string is also an error\n with pytest.raises(ValueError, match=\"\"):\n ...\n```\n\nUse instead:\n```python\nimport pytest\n\n\ndef test_foo():\n with pytest.raises(ValueError, match=\"expected message\"):\n ...\n```\n\nOr, for pytest 8.4.0 and later:\n```python\nimport pytest\n\n\ndef test_foo():\n with pytest.raises(OSError, check=lambda e: e.errno == 42):\n ...\n```\n\n## Options\n- `lint.flake8-pytest-style.raises-require-match-for`\n- `lint.flake8-pytest-style.raises-extend-require-match-for`\n\n## References\n- [`pytest` documentation: `pytest.raises`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-raises)\n",
|
|
339
|
+
"ruff/PT012": "## What it does\nChecks for `pytest.raises` context managers with multiple statements.\n\nThis rule allows `pytest.raises` bodies to contain `for`\nloops with empty bodies (e.g., `pass` or `...` statements), to test\niterator behavior.\n\n## Why is this bad?\nWhen a `pytest.raises` is used as a context manager and contains multiple\nstatements, it can lead to the test passing when it actually should fail.\n\nA `pytest.raises` context manager should only contain a single simple\nstatement that raises the expected exception.\n\n## Example\n```python\nimport pytest\n\n\ndef test_foo():\n with pytest.raises(MyError):\n setup()\n func_to_test() # not executed if `setup()` raises `MyError`\n assert foo() # not executed\n```\n\nUse instead:\n```python\nimport pytest\n\n\ndef test_foo():\n setup()\n with pytest.raises(MyError):\n func_to_test()\n assert foo()\n```\n\n## References\n- [`pytest` documentation: `pytest.raises`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-raises)\n",
|
|
340
|
+
"ruff/PT013": "## What it does\nChecks for incorrect import of pytest.\n\n## Why is this bad?\nFor consistency, `pytest` should be imported as `import pytest` and its members should be\naccessed in the form of `pytest.xxx.yyy` for consistency\n\n## Example\n```python\nimport pytest as pt\nfrom pytest import fixture\n```\n\nUse instead:\n```python\nimport pytest\n```\n",
|
|
341
|
+
"ruff/PT014": "## What it does\nChecks for duplicate test cases in `pytest.mark.parametrize`.\n\n## Why is this bad?\nDuplicate test cases are redundant and should be removed.\n\n## Example\n\n```python\nimport pytest\n\n\n@pytest.mark.parametrize(\n (\"param1\", \"param2\"),\n [\n (1, 2),\n (1, 2),\n ],\n)\ndef test_foo(param1, param2): ...\n```\n\nUse instead:\n\n```python\nimport pytest\n\n\n@pytest.mark.parametrize(\n (\"param1\", \"param2\"),\n [\n (1, 2),\n ],\n)\ndef test_foo(param1, param2): ...\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as tests that rely on mutable global\nstate may be affected by removing duplicate test cases.\n\n## References\n- [`pytest` documentation: How to parametrize fixtures and test functions](https://docs.pytest.org/en/latest/how-to/parametrize.html#pytest-mark-parametrize)\n",
|
|
342
|
+
"ruff/PT015": "## What it does\nChecks for `assert` statements whose test expression is a falsy value.\n\n## Why is this bad?\n`pytest.fail` conveys the intent more clearly than `assert falsy_value`.\n\n## Example\n```python\ndef test_foo():\n if some_condition:\n assert False, \"some_condition was True\"\n```\n\nUse instead:\n```python\nimport pytest\n\n\ndef test_foo():\n if some_condition:\n pytest.fail(\"some_condition was True\")\n ...\n```\n\n## References\n- [`pytest` documentation: `pytest.fail`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-fail)\n",
|
|
343
|
+
"ruff/PT016": "## What it does\nChecks for `pytest.fail` calls without a message.\n\n## Why is this bad?\n`pytest.fail` calls without a message make it harder to understand and debug test failures.\n\n## Example\n```python\nimport pytest\n\n\ndef test_foo():\n pytest.fail()\n\n\ndef test_bar():\n pytest.fail(\"\")\n\n\ndef test_baz():\n pytest.fail(reason=\"\")\n```\n\nUse instead:\n```python\nimport pytest\n\n\ndef test_foo():\n pytest.fail(\"...\")\n\n\ndef test_bar():\n pytest.fail(reason=\"...\")\n```\n\n## References\n- [`pytest` documentation: `pytest.fail`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-fail)\n",
|
|
344
|
+
"ruff/PT017": "## What it does\nChecks for `assert` statements in `except` clauses.\n\n## Why is this bad?\nWhen testing for exceptions, `pytest.raises()` should be used instead of\n`assert` statements in `except` clauses, as it's more explicit and\nidiomatic. Further, `pytest.raises()` will fail if the exception is _not_\nraised, unlike the `assert` statement.\n\n## Example\n```python\ndef test_foo():\n try:\n 1 / 0\n except ZeroDivisionError as e:\n assert e.args\n```\n\nUse instead:\n```python\nimport pytest\n\n\ndef test_foo():\n with pytest.raises(ZeroDivisionError) as exc_info:\n 1 / 0\n assert exc_info.value.args\n```\n\nOr, for pytest 8.4.0 and later:\n```python\nimport pytest\n\n\ndef test_foo():\n with pytest.raises(ZeroDivisionError, check=lambda e: e.args):\n 1 / 0\n```\n\n## References\n- [`pytest` documentation: `pytest.raises`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-raises)\n",
|
|
345
|
+
"ruff/PT018": "## What it does\nChecks for assertions that combine multiple independent conditions.\n\n## Why is this bad?\nComposite assertion statements are harder to debug upon failure, as the\nfailure message will not indicate which condition failed.\n\n## Example\n```python\ndef test_foo():\n assert something and something_else\n\n\ndef test_bar():\n assert not (something or something_else)\n```\n\nUse instead:\n```python\ndef test_foo():\n assert something\n assert something_else\n\n\ndef test_bar():\n assert not something\n assert not something_else\n```\n\n## Fix safety\n\nOn stable, the rule's fix is always unsafe and not offered when it would remove comments in the\ncompound assertion. In [preview], the fix is only unsafe when it would delete such comments and\nsafe otherwise.\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
346
|
+
"ruff/PT019": "## What it does\nChecks for `pytest` test functions that should be decorated with\n`@pytest.mark.usefixtures`.\n\n## Why is this bad?\nIn `pytest`, fixture injection is used to activate fixtures in a test\nfunction.\n\nFixtures can be injected either by passing them as parameters to the test\nfunction, or by using the `@pytest.mark.usefixtures` decorator.\n\nIf the test function depends on the fixture being activated, but does not\nuse it in the test body or otherwise rely on its return value, prefer\nthe `@pytest.mark.usefixtures` decorator, to make the dependency explicit\nand avoid the confusion caused by unused arguments.\n\n## Example\n\n```python\nimport pytest\n\n\n@pytest.fixture\ndef _patch_something(): ...\n\n\ndef test_foo(_patch_something): ...\n```\n\nUse instead:\n\n```python\nimport pytest\n\n\n@pytest.fixture\ndef _patch_something(): ...\n\n\n@pytest.mark.usefixtures(\"_patch_something\")\ndef test_foo(): ...\n```\n\n## References\n- [`pytest` documentation: `pytest.mark.usefixtures`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-mark-usefixtures)\n",
|
|
347
|
+
"ruff/PT020": "## What it does\nChecks for `pytest.yield_fixture` usage.\n\n## Why is this bad?\n`pytest.fixture` has supported `yield` since pytest 3.0, which left\n`pytest.yield_fixture` as a plain alias for it. The alias has been\ndeprecated since pytest 6.2, now raises a `PytestRemovedIn10Warning`, and\nwill be removed in pytest 10.\n\nThe two are the same function, so switching to `pytest.fixture` is a\nrename with no other consequence.\n\n## Example\n```python\nimport pytest\n\n\n@pytest.yield_fixture()\ndef my_fixture():\n obj = SomeClass()\n yield obj\n obj.cleanup()\n```\n\nUse instead:\n```python\nimport pytest\n\n\n@pytest.fixture()\ndef my_fixture():\n obj = SomeClass()\n yield obj\n obj.cleanup()\n```\n\n## Fix safety\nThis rule's fix is marked as safe, unless the decorator contains comments\nthat the fix would remove. `pytest.yield_fixture` and `pytest.fixture` are\nthe same function; the only behavioral difference is the deprecation\nwarning that `pytest.yield_fixture` emits.\n\n## References\n- [`pytest` documentation: the `yield_fixture` function/decorator](https://docs.pytest.org/en/stable/deprecations.html#the-yield-fixture-function-decorator)\n",
|
|
348
|
+
"ruff/PT021": "## What it does\nChecks for unnecessary `request.addfinalizer` usages in `pytest` fixtures.\n\n## Why is this bad?\n`pytest` offers two ways to perform cleanup in fixture code. The first is\nsequential (via the `yield` statement), the second callback-based (via\n`request.addfinalizer`).\n\nThe sequential approach is more readable and should be preferred, unless\nthe fixture uses the \"factory as fixture\" pattern.\n\n## Example\n```python\nimport pytest\n\n\n@pytest.fixture()\ndef my_fixture(request):\n resource = acquire_resource()\n request.addfinalizer(resource.release)\n return resource\n```\n\nUse instead:\n```python\nimport pytest\n\n\n@pytest.fixture()\ndef my_fixture():\n resource = acquire_resource()\n yield resource\n resource.release()\n\n\n# \"factory-as-fixture\" pattern\n@pytest.fixture()\ndef my_factory(request):\n def create_resource(arg):\n resource = acquire_resource(arg)\n request.addfinalizer(resource.release)\n return resource\n\n return create_resource\n```\n\n## References\n- [`pytest` documentation: Adding finalizers directly](https://docs.pytest.org/en/latest/how-to/fixtures.html#adding-finalizers-directly)\n- [`pytest` documentation: Factories as fixtures](https://docs.pytest.org/en/latest/how-to/fixtures.html#factories-as-fixtures)\n",
|
|
349
|
+
"ruff/PT022": "## What it does\nChecks for unnecessary `yield` expressions in `pytest` fixtures.\n\n## Why is this bad?\nIn `pytest` fixtures, the `yield` expression should only be used for fixtures\nthat include teardown code, to clean up the fixture after the test function\nhas finished executing.\n\n## Example\n```python\nimport pytest\n\n\n@pytest.fixture()\ndef my_fixture():\n resource = acquire_resource()\n yield resource\n```\n\nUse instead:\n```python\nimport pytest\n\n\n@pytest.fixture()\ndef my_fixture_with_teardown():\n resource = acquire_resource()\n yield resource\n resource.release()\n\n\n@pytest.fixture()\ndef my_fixture_without_teardown():\n resource = acquire_resource()\n return resource\n```\n\n## Fix safety\n\nThis rule's fix is always marked unsafe because removing the `yield` can change the behavior of\ncode that relies on implicit cleanup, such as when a value is garbage-collected.\n\n## References\n- [`pytest` documentation: Teardown/Cleanup](https://docs.pytest.org/en/latest/how-to/fixtures.html#teardown-cleanup-aka-fixture-finalization)\n",
|
|
350
|
+
"ruff/PT023": "## What it does\nChecks for argument-free `@pytest.mark.<marker>()` decorators with or\nwithout parentheses, depending on the [`lint.flake8-pytest-style.mark-parentheses`]\nsetting.\n\nThe rule defaults to removing unnecessary parentheses,\nto match the documentation of the official pytest projects.\n\n## Why is this bad?\nIf a `@pytest.mark.<marker>()` doesn't take any arguments, the parentheses are\noptional.\n\nEither removing those unnecessary parentheses _or_ requiring them for all\nfixtures is fine, but it's best to be consistent.\n\n## Example\n\n```python\nimport pytest\n\n\n@pytest.mark.foo()\ndef test_something(): ...\n```\n\nUse instead:\n\n```python\nimport pytest\n\n\n@pytest.mark.foo\ndef test_something(): ...\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe if there's comments in the\n`pytest.mark.<marker>` decorator.\n```python\nimport pytest\n\n\n@pytest.mark.foo(\n # comment\n)\ndef test_something(): ...\n```\n\n## Options\n- `lint.flake8-pytest-style.mark-parentheses`\n\n## References\n- [`pytest` documentation: Marks](https://docs.pytest.org/en/latest/reference/reference.html#marks)\n",
|
|
351
|
+
"ruff/PT024": "## What it does\nChecks for unnecessary `@pytest.mark.asyncio` decorators applied to fixtures.\n\n## Why is this bad?\n`pytest.mark.asyncio` is unnecessary for fixtures.\n\n## Example\n```python\nimport pytest\n\n\n@pytest.mark.asyncio()\n@pytest.fixture()\nasync def my_fixture():\n return 0\n```\n\nUse instead:\n```python\nimport pytest\n\n\n@pytest.fixture()\nasync def my_fixture():\n return 0\n```\n\n## References\n- [PyPI: `pytest-asyncio`](https://pypi.org/project/pytest-asyncio/)\n",
|
|
352
|
+
"ruff/PT025": "## What it does\nChecks for `pytest.mark.usefixtures` decorators applied to `pytest`\nfixtures.\n\n## Why is this bad?\nThe `pytest.mark.usefixtures` decorator has no effect on `pytest` fixtures.\n\n## Example\n```python\nimport pytest\n\n\n@pytest.fixture()\ndef a():\n pass\n\n\n@pytest.mark.usefixtures(\"a\")\n@pytest.fixture()\ndef b(a):\n pass\n```\n\nUse instead:\n```python\nimport pytest\n\n\n@pytest.fixture()\ndef a():\n pass\n\n\n@pytest.fixture()\ndef b(a):\n pass\n```\n\n## References\n- [`pytest` documentation: `pytest.mark.usefixtures`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-mark-usefixtures)\n",
|
|
353
|
+
"ruff/PT026": "## What it does\nChecks for `@pytest.mark.usefixtures()` decorators that aren't passed any\narguments.\n\n## Why is this bad?\nA `@pytest.mark.usefixtures()` decorator that isn't passed any arguments is\nuseless and should be removed.\n\n## Example\n\n```python\nimport pytest\n\n\n@pytest.mark.usefixtures()\ndef test_something(): ...\n```\n\nUse instead:\n\n```python\ndef test_something(): ...\n```\n\n## References\n- [`pytest` documentation: `pytest.mark.usefixtures`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-mark-usefixtures)\n",
|
|
354
|
+
"ruff/PT027": "## What it does\nChecks for uses of exception-related assertion methods from the `unittest`\nmodule.\n\n## Why is this bad?\nTo enforce the assertion style recommended by `pytest`, `pytest.raises` is\npreferred over the exception-related assertion methods in `unittest`, like\n`assertRaises`.\n\n## Example\n```python\nimport unittest\n\n\nclass TestFoo(unittest.TestCase):\n def test_foo(self):\n with self.assertRaises(ValueError):\n raise ValueError(\"foo\")\n```\n\nUse instead:\n```python\nimport unittest\nimport pytest\n\n\nclass TestFoo(unittest.TestCase):\n def test_foo(self):\n with pytest.raises(ValueError):\n raise ValueError(\"foo\")\n```\n\n## References\n- [`pytest` documentation: Assertions about expected exceptions](https://docs.pytest.org/en/latest/how-to/assert.html#assertions-about-expected-exceptions)\n",
|
|
355
|
+
"ruff/PT028": "## What it does\nChecks for parameters of test functions with default arguments.\n\n## Why is this bad?\nSuch a parameter will always have the default value during the test\nregardless of whether a fixture with the same name is defined.\n\n## Example\n\n```python\ndef test_foo(a=1): ...\n```\n\nUse instead:\n\n```python\ndef test_foo(a): ...\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as modifying a function signature can\nchange the behavior of the code.\n\n## References\n- [Original Pytest issue](https://github.com/pytest-dev/pytest/issues/12693)\n",
|
|
356
|
+
"ruff/PT029": "## What it does\nChecks for `pytest.warns` calls without an expected warning.\n\n## Why is this bad?\n`pytest.warns` expects to receive an expected warning as its first\nargument. If omitted, the `pytest.warns` call will fail at runtime.\n\n## Example\n```python\nimport pytest\n\n\ndef test_foo():\n with pytest.warns():\n do_something()\n```\n\nUse instead:\n```python\nimport pytest\n\n\ndef test_foo():\n with pytest.warns(SomeWarning):\n do_something()\n```\n\n## References\n- [`pytest` documentation: `pytest.warns`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-warns)\n",
|
|
357
|
+
"ruff/PT030": "## What it does\nChecks for `pytest.warns` calls without a `match` parameter.\n\n## Why is this bad?\n`pytest.warns(Warning)` will catch any `Warning` and may catch warnings that\nare unrelated to the code under test. To avoid this, `pytest.warns` should\nbe called with a `match` parameter. The warning names that require a `match`\nparameter can be configured via the\n[`lint.flake8-pytest-style.warns-require-match-for`] and\n[`lint.flake8-pytest-style.warns-extend-require-match-for`] settings.\n\n## Example\n```python\nimport pytest\n\n\ndef test_foo():\n with pytest.warns(Warning):\n ...\n\n # empty string is also an error\n with pytest.warns(Warning, match=\"\"):\n ...\n```\n\nUse instead:\n```python\nimport pytest\n\n\ndef test_foo():\n with pytest.warns(Warning, match=\"expected message\"):\n ...\n```\n\n## Options\n- `lint.flake8-pytest-style.warns-require-match-for`\n- `lint.flake8-pytest-style.warns-extend-require-match-for`\n\n## References\n- [`pytest` documentation: `pytest.warns`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-warns)\n",
|
|
358
|
+
"ruff/PT031": "## What it does\nChecks for `pytest.warns` context managers with multiple statements.\n\nThis rule allows `pytest.warns` bodies to contain `for`\nloops with empty bodies (e.g., `pass` or `...` statements), to test\niterator behavior.\n\n## Why is this bad?\nWhen `pytest.warns` is used as a context manager and contains multiple\nstatements, it can lead to the test passing when it should instead fail.\n\nA `pytest.warns` context manager should only contain a single\nsimple statement that triggers the expected warning.\n\n\n## Example\n```python\nimport pytest\n\n\ndef test_foo_warns():\n with pytest.warns(Warning):\n setup() # False negative if setup triggers a warning but foo does not.\n foo()\n```\n\nUse instead:\n```python\nimport pytest\n\n\ndef test_foo_warns():\n setup()\n with pytest.warns(Warning):\n foo()\n```\n\n## References\n- [`pytest` documentation: `pytest.warns`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-warns)\n",
|
|
359
|
+
"ruff/Q000": "## What it does\nChecks for inline strings that use single quotes or double quotes,\ndepending on the value of the [`lint.flake8-quotes.inline-quotes`] option.\n\n## Why is this bad?\nConsistency is good. Use either single or double quotes for inline\nstrings, but be consistent.\n\n## Example\n```python\nfoo = 'bar'\n```\n\nAssuming `inline-quotes` is set to `double`, use instead:\n```python\nfoo = \"bar\"\n```\n\n## Options\n- `lint.flake8-quotes.inline-quotes`\n\n## Formatter compatibility\nWe recommend against using this rule alongside the [formatter]. The\nformatter enforces consistent quotes for inline strings, making the rule\nredundant.\n\n[formatter]: https://docs.astral.sh/ruff/formatter\n",
|
|
360
|
+
"ruff/Q001": "## What it does\nChecks for multiline strings that use single quotes or double quotes,\ndepending on the value of the [`lint.flake8-quotes.multiline-quotes`]\nsetting.\n\n## Why is this bad?\nConsistency is good. Use either single or double quotes for multiline\nstrings, but be consistent.\n\n## Example\n```python\nfoo = '''\nbar\n'''\n```\n\nAssuming `multiline-quotes` is set to `double`, use instead:\n```python\nfoo = \"\"\"\nbar\n\"\"\"\n```\n\n## Options\n- `lint.flake8-quotes.multiline-quotes`\n\n## Formatter compatibility\nWe recommend against using this rule alongside the [formatter]. The\nformatter enforces double quotes for multiline strings, making the rule\nredundant.\n\n[formatter]: https://docs.astral.sh/ruff/formatter\n",
|
|
361
|
+
"ruff/Q002": "## What it does\nChecks for docstrings that use single quotes or double quotes, depending\non the value of the [`lint.flake8-quotes.docstring-quotes`] setting.\n\n## Why is this bad?\nConsistency is good. Use either single or double quotes for docstring\nstrings, but be consistent.\n\n## Example\n```python\n'''\nbar\n'''\n```\n\nAssuming `docstring-quotes` is set to `double`, use instead:\n```python\n\"\"\"\nbar\n\"\"\"\n```\n\n## Options\n- `lint.flake8-quotes.docstring-quotes`\n\n## Formatter compatibility\nWe recommend against using this rule alongside the [formatter]. The\nformatter enforces double quotes for docstrings, making the rule\nredundant.\n\n[formatter]: https://docs.astral.sh/ruff/formatter\n",
|
|
362
|
+
"ruff/Q003": "## What it does\nChecks for strings that include escaped quotes, and suggests changing\nthe quote style to avoid the need to escape them.\n\n## Why is this bad?\nIt's preferable to avoid escaped quotes in strings. By changing the\nouter quote style, you can avoid escaping inner quotes.\n\n## Example\n```python\nfoo = \"bar\\\"s\"\n```\n\nUse instead:\n```python\nfoo = 'bar\"s'\n```\n\n## Formatter compatibility\nWe recommend against using this rule alongside the [formatter]. The\nformatter automatically removes unnecessary escapes, making the rule\nredundant.\n\n## Options\n\n- `lint.flake8-quotes.inline-quotes`\n\n[formatter]: https://docs.astral.sh/ruff/formatter\n",
|
|
363
|
+
"ruff/Q004": "## What it does\nChecks for strings that include unnecessarily escaped quotes.\n\n## Why is this bad?\nIf a string contains an escaped quote that doesn't match the quote\ncharacter used for the string, it's unnecessary and can be removed.\n\n## Example\n```python\nfoo = \"bar\\'s\"\n```\n\nUse instead:\n```python\nfoo = \"bar's\"\n```\n\n## Formatter compatibility\nWe recommend against using this rule alongside the [formatter]. The\nformatter automatically removes unnecessary escapes, making the rule\nredundant.\n\n[formatter]: https://docs.astral.sh/ruff/formatter\n",
|
|
364
|
+
"ruff/RSE102": "## What it does\nChecks for unnecessary parentheses on raised exceptions.\n\n## Why is this bad?\nIf an exception is raised without any arguments, parentheses are not\nrequired, as the `raise` statement accepts either an exception instance\nor an exception class (which is then implicitly instantiated).\n\nRemoving the parentheses makes the code more concise.\n\n## Known problems\nParentheses can only be omitted if the exception is a class, as opposed to\na function call. This rule isn't always capable of distinguishing between\nthe two.\n\nFor example, if you import a function `module.get_exception` from another\nmodule, and `module.get_exception` returns an exception object, this rule will\nincorrectly mark the parentheses in `raise module.get_exception()` as\nunnecessary.\n\n## Example\n```python\nraise TypeError()\n```\n\nUse instead:\n```python\nraise TypeError\n```\n\n## Fix Safety\nThis rule's fix is marked as unsafe if removing the parentheses would also remove comments\nor if it\u2019s unclear whether the expression is a class or a function call.\n\n## References\n- [Python documentation: The `raise` statement](https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement)\n",
|
|
365
|
+
"ruff/RET501": "## What it does\nChecks for the presence of a `return None` statement when `None` is the only\npossible return value.\n\n## Why is this bad?\nPython implicitly assumes `return None` if an explicit `return` value is\nomitted. Therefore, explicitly returning `None` is redundant and should be\navoided when it is the only possible `return` value across all code paths\nin a given function.\n\n## Example\n```python\ndef foo(bar):\n if not bar:\n return\n return None\n```\n\nUse instead:\n```python\ndef foo(bar):\n if not bar:\n return\n return\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe for cases in which comments would be\ndropped from the `return` statement.\n\n## Options\n\nThis rule ignores functions marked as properties.\n\n- `lint.pydocstyle.property-decorators`\n",
|
|
366
|
+
"ruff/RET502": "## What it does\nChecks for the presence of a `return` statement with no explicit value,\nfor functions that return non-`None` values elsewhere.\n\n## Why is this bad?\nIncluding a `return` statement with no explicit value can cause confusion\nwhen other `return` statements in the function return non-`None` values.\nPython implicitly assumes return `None` if no other return value is present.\nAdding an explicit `return None` can make the code more readable by clarifying\nintent.\n\n## Example\n```python\ndef foo(bar):\n if not bar:\n return\n return 1\n```\n\nUse instead:\n```python\ndef foo(bar):\n if not bar:\n return None\n return 1\n```\n",
|
|
367
|
+
"ruff/RET503": "## What it does\nChecks for missing explicit `return` statements at the end of functions\nthat can return non-`None` values.\n\n## Why is this bad?\nThe lack of an explicit `return` statement at the end of a function that\ncan return non-`None` values can cause confusion. Python implicitly returns\n`None` if no other return value is present. Adding an explicit\n`return None` can make the code more readable by clarifying intent.\n\n## Example\n```python\ndef foo(bar):\n if not bar:\n return 1\n```\n\nUse instead:\n```python\ndef foo(bar):\n if not bar:\n return 1\n return None\n```\n",
|
|
368
|
+
"ruff/RET504": "## What it does\nChecks for variable assignments that immediately precede a `return` of the\nassigned variable.\n\n## Why is this bad?\nThe variable assignment is not necessary, as the value can be returned\ndirectly.\n\n## Example\n```python\ndef foo():\n bar = 1\n return bar\n```\n\nUse instead:\n```python\ndef foo():\n return 1\n```\n",
|
|
369
|
+
"ruff/RET505": "## What it does\nChecks for `else` statements with a `return` statement in the preceding\n`if` block.\n\n## Why is this bad?\nThe `else` statement is not needed as the `return` statement will always\nbreak out of the enclosing function. Removing the `else` will reduce\nnesting and make the code more readable.\n\n## Example\n```python\ndef foo(bar, baz):\n if bar:\n return 1\n else:\n return baz\n```\n\nUse instead:\n```python\ndef foo(bar, baz):\n if bar:\n return 1\n return baz\n```\n",
|
|
370
|
+
"ruff/RET506": "## What it does\nChecks for `else` statements with a `raise` statement in the preceding `if`\nblock.\n\n## Why is this bad?\nThe `else` statement is not needed as the `raise` statement will always\nbreak out of the current scope. Removing the `else` will reduce nesting\nand make the code more readable.\n\n## Example\n```python\ndef foo(bar, baz):\n if bar == \"Specific Error\":\n raise Exception(bar)\n else:\n raise Exception(baz)\n```\n\nUse instead:\n```python\ndef foo(bar, baz):\n if bar == \"Specific Error\":\n raise Exception(bar)\n raise Exception(baz)\n```\n",
|
|
371
|
+
"ruff/RET507": "## What it does\nChecks for `else` statements with a `continue` statement in the preceding\n`if` block.\n\n## Why is this bad?\nThe `else` statement is not needed, as the `continue` statement will always\ncontinue onto the next iteration of a loop. Removing the `else` will reduce\nnesting and make the code more readable.\n\n## Example\n```python\ndef foo(bar, baz):\n for i in bar:\n if i < baz:\n continue\n else:\n x = 0\n```\n\nUse instead:\n```python\ndef foo(bar, baz):\n for i in bar:\n if i < baz:\n continue\n x = 0\n```\n",
|
|
372
|
+
"ruff/RET508": "## What it does\nChecks for `else` statements with a `break` statement in the preceding `if`\nblock.\n\n## Why is this bad?\nThe `else` statement is not needed, as the `break` statement will always\nbreak out of the loop. Removing the `else` will reduce nesting and make the\ncode more readable.\n\n## Example\n```python\ndef foo(bar, baz):\n for i in bar:\n if i > baz:\n break\n else:\n x = 0\n```\n\nUse instead:\n```python\ndef foo(bar, baz):\n for i in bar:\n if i > baz:\n break\n x = 0\n```\n",
|
|
373
|
+
"ruff/SLF001": "## What it does\nChecks for accesses on \"private\" class members.\n\n## Why is this bad?\nIn Python, the convention is such that class members that are prefixed\nwith a single underscore, or prefixed but not suffixed with a double\nunderscore, are considered private and intended for internal use.\n\nUsing such \"private\" members is considered a misuse of the class, as\nthere are no guarantees that the member will be present in future\nversions, that it will have the same type, or that it will have the same\nbehavior. Instead, use the class's public interface.\n\nThis rule ignores accesses on dunder methods (e.g., `__init__`) and sunder\nmethods (e.g., `_missing_`).\n\n## Example\n```python\nclass Class:\n def __init__(self):\n self._private_member = \"...\"\n\n\nvar = Class()\nprint(var._private_member)\n```\n\nUse instead:\n```python\nclass Class:\n def __init__(self):\n self.public_member = \"...\"\n\n\nvar = Class()\nprint(var.public_member)\n```\n\n## Options\n- `lint.flake8-self.ignore-names`\n\n## References\n- [_What is the meaning of single or double underscores before an object name?_](https://stackoverflow.com/questions/1301346/what-is-the-meaning-of-single-and-double-underscore-before-an-object-name)\n",
|
|
374
|
+
"ruff/SIM101": "## What it does\nChecks for multiple `isinstance` calls on the same target.\n\n## Why is this bad?\nTo check if an object is an instance of any one of multiple types\nor classes, it is unnecessary to use multiple `isinstance` calls, as\nthe second argument of the `isinstance` built-in function accepts a\ntuple of types and classes.\n\nUsing a single `isinstance` call implements the same behavior with more\nconcise code and clearer intent.\n\n## Example\n```python\nif isinstance(obj, int) or isinstance(obj, float):\n pass\n```\n\nUse instead:\n```python\nif isinstance(obj, (int, float)):\n pass\n```\n\n## References\n- [Python documentation: `isinstance`](https://docs.python.org/3/library/functions.html#isinstance)\n",
|
|
375
|
+
"ruff/SIM102": "## What it does\nChecks for nested `if` statements that can be collapsed into a single `if`\nstatement.\n\n## Why is this bad?\nNesting `if` statements leads to deeper indentation and makes code harder to\nread. Instead, combine the conditions into a single `if` statement with an\n`and` operator.\n\n## Example\n```python\nif foo:\n if bar:\n ...\n```\n\nUse instead:\n```python\nif foo and bar:\n ...\n```\n## Preview and Fix Safety\nWhen [preview] is enabled, the fix for this rule is considered\nas safe. When [preview] is not enabled, the fix is always\nconsidered unsafe.\n\n[preview]: https://docs.astral.sh/ruff/preview/\n\n## Options\n\nThe rule will consult these two settings when deciding if a fix can be provided:\n\n- `lint.pycodestyle.max-line-length`\n- `indent-width`\n\nLines that would exceed the configured line length will not be fixed automatically.\n\n## References\n- [Python documentation: The `if` statement](https://docs.python.org/3/reference/compound_stmts.html#the-if-statement)\n- [Python documentation: Boolean operations](https://docs.python.org/3/reference/expressions.html#boolean-operations)\n",
|
|
376
|
+
"ruff/SIM103": "## What it does\nChecks for `if` statements that can be replaced with `bool`.\n\n## Why is this bad?\n`if` statements that return `True` for a truthy condition and `False` for\na falsy condition can be replaced with boolean casts.\n\n## Example\nGiven:\n```python\ndef foo(x: int) -> bool:\n if x > 0:\n return True\n else:\n return False\n```\n\nUse instead:\n```python\ndef foo(x: int) -> bool:\n return x > 0\n```\n\nOr, given:\n```python\ndef foo(x: int) -> bool:\n if x > 0:\n return True\n return False\n```\n\nUse instead:\n```python\ndef foo(x: int) -> bool:\n return x > 0\n```\n\n## Fix safety\n\nThis fix is marked as unsafe because it may change the program\u2019s behavior if the condition does not\nreturn a proper Boolean. While the fix will try to wrap non-boolean values in a call to bool,\ncustom implementations of comparison functions like `__eq__` can avoid the bool call and still\nlead to altered behavior.\n\n## References\n- [Python documentation: Truth Value Testing](https://docs.python.org/3/library/stdtypes.html#truth-value-testing)\n",
|
|
377
|
+
"ruff/SIM105": "## What it does\nChecks for `try`-`except`-`pass` blocks that can be replaced with the\n`contextlib.suppress` context manager.\n\n## Why is this bad?\nUsing `contextlib.suppress` is more concise and directly communicates the\nintent of the code: to suppress a given exception.\n\nNote that `contextlib.suppress` is slower than using `try`-`except`-`pass`\ndirectly. For performance-critical code, consider retaining the\n`try`-`except`-`pass` pattern.\n\n## Example\n```python\ntry:\n 1 / 0\nexcept ZeroDivisionError:\n pass\n```\n\nUse instead:\n```python\nimport contextlib\n\nwith contextlib.suppress(ZeroDivisionError):\n 1 / 0\n```\n\n## References\n- [Python documentation: `contextlib.suppress`](https://docs.python.org/3/library/contextlib.html#contextlib.suppress)\n- [Python documentation: `try` statement](https://docs.python.org/3/reference/compound_stmts.html#the-try-statement)\n- [a simpler `try`/`except` (and why maybe shouldn't)](https://www.youtube.com/watch?v=MZAJ8qnC7mk)\n",
|
|
378
|
+
"ruff/SIM107": "## What it does\nChecks for `return` statements in `try`-`except` and `finally` blocks.\n\n## Why is this bad?\nThe `return` statement in a `finally` block will always be executed, even if\nan exception is raised in the `try` or `except` block. This can lead to\nunexpected behavior.\n\n## Example\n```python\ndef squared(n):\n try:\n sqr = n**2\n return sqr\n except Exception:\n return \"An exception occurred\"\n finally:\n return -1 # Always returns -1.\n```\n\nUse instead:\n```python\ndef squared(n):\n try:\n return_value = n**2\n except Exception:\n return_value = \"An exception occurred\"\n finally:\n return_value = -1\n return return_value\n```\n\n## References\n- [Python documentation: Defining Clean-up Actions](https://docs.python.org/3/tutorial/errors.html#defining-clean-up-actions)\n",
|
|
379
|
+
"ruff/SIM108": "## What it does\nCheck for `if`-`else`-blocks that can be replaced with a ternary\nor binary operator.\n\nThe lint is suppressed if the suggested replacement would exceed\nthe maximum line length configured in [pycodestyle.max-line-length].\n\n## Why is this bad?\n`if`-`else`-blocks that assign a value to a variable in both branches can\nbe expressed more concisely by using a ternary or binary operator.\n\n## Example\n\n```python\nif foo:\n bar = x\nelse:\n bar = y\n```\n\nUse instead:\n```python\nbar = x if foo else y\n```\n\nOr:\n\n```python\nif cond:\n z = cond\nelse:\n z = other_cond\n```\n\nUse instead:\n\n```python\nz = cond or other_cond\n```\n\n## Known issues\nThis is an opinionated style rule that may not always be to everyone's\ntaste, especially for code that makes use of complex `if` conditions.\nTernary operators can also make it harder to measure [code coverage]\nwith tools that use line profiling.\n\n## Options\n\n- `lint.pycodestyle.max-line-length`\n- `indent-width`\n\n## References\n- [Python documentation: Conditional expressions](https://docs.python.org/3/reference/expressions.html#conditional-expressions)\n\n[code coverage]: https://github.com/nedbat/coveragepy/issues/509\n[pycodestyle.max-line-length]: https://docs.astral.sh/ruff/settings/#lint_pycodestyle_max-line-length\n",
|
|
380
|
+
"ruff/SIM109": "## What it does\nChecks for boolean expressions that contain multiple equality comparisons\nto the same value.\n\n## Why is this bad?\nTo check if an object is equal to any one of multiple values, it's more\nconcise to use the `in` operator with a tuple of values.\n\n## Example\n```python\nif foo == x or foo == y:\n ...\n```\n\nUse instead:\n```python\nif foo in (x, y):\n ...\n```\n\n## Fix safety\n\nThis fix is always unsafe. It may change the value of the expression if any of the\ncomparators have side effects, and, for expressions that mix equality comparisons with\nother operands, it can change the order in which operands are evaluated. Ruff preserves\nthe original order when an operand falls before or after the group of merged comparisons,\nbut if an unmatched operand falls *between* two merged comparisons (e.g. `foo == x or bar\nor foo == y`), it's moved after the merged `in` comparison.\n\n## References\n- [Python documentation: Membership test operations](https://docs.python.org/3/reference/expressions.html#membership-test-operations)\n",
|
|
381
|
+
"ruff/SIM110": "## What it does\nChecks for `for` loops that can be replaced with a builtin function, like\n`any` or `all`.\n\n## Why is this bad?\nUsing a builtin function is more concise and readable.\n\n## Example\n```python\ndef foo():\n for item in iterable:\n if predicate(item):\n return True\n return False\n```\n\nUse instead:\n```python\ndef foo():\n return any(predicate(item) for item in iterable)\n```\n\n## Fix safety\n\nThis fix is always marked as unsafe because it might remove comments.\n\n## Options\n\nThe rule will avoid flagging cases where using the builtin function would exceed the configured\nline length, as determined by these options:\n\n- `lint.pycodestyle.max-line-length`\n- `indent-width`\n\n## References\n- [Python documentation: `any`](https://docs.python.org/3/library/functions.html#any)\n- [Python documentation: `all`](https://docs.python.org/3/library/functions.html#all)\n",
|
|
382
|
+
"ruff/SIM112": "## What it does\nCheck for environment variables that are not capitalized.\n\n## Why is this bad?\nBy convention, environment variables should be capitalized.\n\nFurthermore, `os.environ` behaves differently across platforms. On Windows,\n`os.environ` automatically converts environment variable names to uppercase.\nThis means that if you define a lowercase environment variable (e.g., `foo=1`),\niterating over `os.environ` will yield `FOO` on Windows, but\n`foo` on Linux and macOS. This can lead to subtle bugs in cross-platform code\nif it assumes environment variables preserve their original case.\n\n## Example\n```python\nimport os\n\nos.environ[\"foo\"]\n```\n\nUse instead:\n```python\nimport os\n\nos.environ[\"FOO\"]\n```\n\n## Fix safety\n\nThis fix is always marked as unsafe because automatically capitalizing environment variable names\ncan change program behavior in environments where the variable names are case-sensitive, such as most\nUnix-like systems.\n\n## References\n- [Python documentation: `os.environ`](https://docs.python.org/3/library/os.html#os.environ)\n",
|
|
383
|
+
"ruff/SIM113": "## What it does\nChecks for `for` loops with explicit loop-index variables that can be replaced\nwith `enumerate()`.\n\nIn [preview], this rule checks for index variables initialized with any integer rather than only\na literal zero.\n\n## Why is this bad?\nWhen iterating over a sequence, it's often desirable to keep track of the\nindex of each element alongside the element itself. Prefer the `enumerate`\nbuiltin over manually incrementing a counter variable within the loop, as\n`enumerate` is more concise and idiomatic.\n\n## Example\n```python\nfruits = [\"apple\", \"banana\", \"cherry\"]\ni = 0\nfor fruit in fruits:\n print(f\"{i + 1}. {fruit}\")\n i += 1\n```\n\nUse instead:\n```python\nfruits = [\"apple\", \"banana\", \"cherry\"]\nfor i, fruit in enumerate(fruits):\n print(f\"{i + 1}. {fruit}\")\n```\n\n## References\n- [Python documentation: `enumerate`](https://docs.python.org/3/library/functions.html#enumerate)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
384
|
+
"ruff/SIM114": "## What it does\nChecks for `if` branches with identical arm bodies.\n\n## Why is this bad?\nIf multiple arms of an `if` statement have the same body, using `or`\nbetter signals the intent of the statement.\n\n## Example\n```python\nif x == 1:\n print(\"Hello\")\nelif x == 2:\n print(\"Hello\")\n```\n\nUse instead:\n```python\nif x == 1 or x == 2:\n print(\"Hello\")\n```\n",
|
|
385
|
+
"ruff/SIM115": "## What it does\nChecks for cases where files are opened (e.g., using the builtin `open()` function)\nwithout using a context manager.\n\n## Why is this bad?\nIf a file is opened without a context manager, it is not guaranteed that\nthe file will be closed (e.g., if an exception is raised), which can cause\nresource leaks. The rule detects a wide array of IO calls where context managers\ncould be used, such as `open`, `pathlib.Path(...).open()`, `tempfile.TemporaryFile()`\nor`tarfile.TarFile(...).gzopen()`.\n\n## Example\n```python\nfile = open(\"foo.txt\")\n...\nfile.close()\n```\n\nUse instead:\n```python\nwith open(\"foo.txt\") as file:\n ...\n```\n\n## References\n- [Python documentation: `open`](https://docs.python.org/3/library/functions.html#open)\n",
|
|
386
|
+
"ruff/SIM116": "## What it does\nChecks for three or more consecutive if-statements with direct returns\n\n## Why is this bad?\nThese can be simplified by using a dictionary\n\n## Example\n```python\ndef find_phrase(x):\n if x == 1:\n return \"Hello\"\n elif x == 2:\n return \"Goodbye\"\n elif x == 3:\n return \"Good morning\"\n else:\n return \"Goodnight\"\n```\n\nUse instead:\n```python\ndef find_phrase(x):\n phrases = {1: \"Hello\", 2: \"Goodbye\", 3: \"Good morning\"}\n return phrases.get(x, \"Goodnight\")\n```\n",
|
|
387
|
+
"ruff/SIM117": "## What it does\nChecks for the unnecessary nesting of multiple consecutive context\nmanagers.\n\n## Why is this bad?\nIn Python 3, a single `with` block can include multiple context\nmanagers.\n\nCombining multiple context managers into a single `with` statement\nwill minimize the indentation depth of the code, making it more\nreadable.\n\nThe following context managers are exempt when used as standalone\nstatements:\n\n - `anyio`.{`CancelScope`, `fail_after`, `move_on_after`}\n - `asyncio`.{`timeout`, `timeout_at`}\n - `trio`.{`fail_after`, `fail_at`, `move_on_after`, `move_on_at`}\n\n## Example\n```python\nwith A() as a:\n with B() as b:\n pass\n```\n\nUse instead:\n```python\nwith A() as a, B() as b:\n pass\n```\n\n## Options\n\nThe rule will consult these two settings when deciding if a fix can be provided:\n\n- `lint.pycodestyle.max-line-length`\n- `indent-width`\n\nLines that would exceed the configured line length will not be fixed automatically.\n\n## References\n- [Python documentation: The `with` statement](https://docs.python.org/3/reference/compound_stmts.html#the-with-statement)\n",
|
|
388
|
+
"ruff/SIM118": "## What it does\nChecks for key-existence checks against `dict.keys()` calls.\n\n## Why is this bad?\nWhen checking for the existence of a key in a given dictionary, using\n`key in dict` is more readable and efficient than `key in dict.keys()`,\nwhile having the same semantics.\n\n## Example\n```python\nkey in foo.keys()\n```\n\nUse instead:\n```python\nkey in foo\n```\n\n## Fix safety\nGiven `key in obj.keys()`, `obj` _could_ be a dictionary, or it could be\nanother type that defines a `.keys()` method. In the latter case, removing\nthe `.keys()` attribute could lead to a runtime error. The fix is marked\nas safe when the type of `obj` is known to be a dictionary; otherwise, it\nis marked as unsafe.\n\n## References\n- [Python documentation: Mapping Types](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict)\n",
|
|
389
|
+
"ruff/SIM201": "## What it does\nChecks for negated `==` operators.\n\n## Why is this bad?\nNegated `==` operators are less readable than `!=` operators. When testing\nfor non-equality, it is more common to use `!=` than `==`.\n\n## Example\n```python\nnot a == b\n```\n\nUse instead:\n```python\na != b\n```\n\n## Fix safety\nThe fix is marked as unsafe, as it might change the behaviour\nif `a` and/or `b` overrides `__eq__`/`__ne__`\nin such a manner that they don't return booleans.\n\n## References\n- [Python documentation: Comparisons](https://docs.python.org/3/reference/expressions.html#comparisons)\n",
|
|
390
|
+
"ruff/SIM202": "## What it does\nChecks for negated `!=` operators.\n\n## Why is this bad?\nNegated `!=` operators are less readable than `==` operators, as they avoid a\ndouble negation.\n\n## Example\n```python\nnot a != b\n```\n\nUse instead:\n```python\na == b\n```\n\n## Fix safety\nThe fix is marked as unsafe, as it might change the behaviour\nif `a` and/or `b` overrides `__ne__`/`__eq__`\nin such a manner that they don't return booleans.\n\n## References\n- [Python documentation: Comparisons](https://docs.python.org/3/reference/expressions.html#comparisons)\n",
|
|
391
|
+
"ruff/SIM208": "## What it does\nChecks for double negations (i.e., multiple `not` operators).\n\n## Why is this bad?\nA double negation is redundant and less readable than omitting the `not`\noperators entirely.\n\n## Example\n```python\nnot (not a)\n```\n\nUse instead:\n```python\na\n```\n\n## References\n- [Python documentation: Comparisons](https://docs.python.org/3/reference/expressions.html#comparisons)\n",
|
|
392
|
+
"ruff/SIM210": "## What it does\nChecks for `if` expressions that can be replaced with `bool()` calls.\n\n## Why is this bad?\n`if` expressions that evaluate to `True` for a truthy condition an `False`\nfor a falsey condition can be replaced with `bool()` calls, which are more\nconcise and readable.\n\n## Example\n```python\nTrue if a else False\n```\n\nUse instead:\n```python\nbool(a)\n```\n\n## Fix safety\n\nThis fix is marked as unsafe because it may change the program\u2019s behavior if the condition does not\nreturn a proper Boolean. While the fix will try to wrap non-boolean values in a call to bool,\ncustom implementations of comparison functions like `__eq__` can avoid the bool call and still\nlead to altered behavior. Moreover, the fix may remove comments.\n\n## References\n- [Python documentation: Truth Value Testing](https://docs.python.org/3/library/stdtypes.html#truth-value-testing)\n",
|
|
393
|
+
"ruff/SIM211": "## What it does\nChecks for `if` expressions that can be replaced by negating a given\ncondition.\n\n## Why is this bad?\n`if` expressions that evaluate to `False` for a truthy condition and `True`\nfor a falsey condition can be replaced with `not` operators, which are more\nconcise and readable.\n\n## Example\n```python\nFalse if a else True\n```\n\nUse instead:\n```python\nnot a\n```\n\n## References\n- [Python documentation: Truth Value Testing](https://docs.python.org/3/library/stdtypes.html#truth-value-testing)\n",
|
|
394
|
+
"ruff/SIM212": "## What it does\nChecks for `if` expressions that check against a negated condition.\n\n## Why is this bad?\n`if` expressions that check against a negated condition are more difficult\nto read than `if` expressions that check against the condition directly.\n\n## Example\n```python\nb if not a else a\n```\n\nUse instead:\n```python\na if a else b\n```\n\n## References\n- [Python documentation: Truth Value Testing](https://docs.python.org/3/library/stdtypes.html#truth-value-testing)\n",
|
|
395
|
+
"ruff/SIM220": "## What it does\nChecks for `and` expressions that include both an expression and its\nnegation.\n\n## Why is this bad?\nAn `and` expression that includes both an expression and its negation will\nalways evaluate to `False`.\n\n## Example\n```python\nx and not x\n```\n\n## References\n- [Python documentation: Boolean operations](https://docs.python.org/3/reference/expressions.html#boolean-operations)\n",
|
|
396
|
+
"ruff/SIM221": "## What it does\nChecks for `or` expressions that include both an expression and its\nnegation.\n\n## Why is this bad?\nAn `or` expression that includes both an expression and its negation will\nalways evaluate to `True`.\n\n## Example\n```python\nx or not x\n```\n\n## References\n- [Python documentation: Boolean operations](https://docs.python.org/3/reference/expressions.html#boolean-operations)\n",
|
|
397
|
+
"ruff/SIM222": "## What it does\nChecks for `or` expressions that contain truthy values.\n\n## Why is this bad?\nIf the expression is used as a condition, it can be replaced in-full with\n`True`.\n\nIn other cases, the expression can be short-circuited to the first truthy\nvalue.\n\nBy using `True` (or the first truthy value), the code is more concise\nand easier to understand, since it no longer contains redundant conditions.\n\n## Example\n```python\nif x or [1] or y:\n pass\n\na = x or [1] or y\n```\n\nUse instead:\n```python\nif True:\n pass\n\na = x or [1]\n```\n",
|
|
398
|
+
"ruff/SIM223": "## What it does\nChecks for `and` expressions that contain falsey values.\n\n## Why is this bad?\nIf the expression is used as a condition, it can be replaced in-full with\n`False`.\n\nIn other cases, the expression can be short-circuited to the first falsey\nvalue.\n\nBy using `False` (or the first falsey value), the code is more concise\nand easier to understand, since it no longer contains redundant conditions.\n\n## Example\n```python\nif x and [] and y:\n pass\n\na = x and [] and y\n```\n\nUse instead:\n```python\nif False:\n pass\n\na = x and []\n```\n",
|
|
399
|
+
"ruff/SIM300": "## What it does\nChecks for conditions that position a constant on the left-hand side of the\ncomparison operator, rather than the right-hand side.\n\n## Why is this bad?\nThese conditions (sometimes referred to as \"Yoda conditions\") are less\nreadable than conditions that place the variable on the left-hand side of\nthe comparison operator.\n\nIn some languages, Yoda conditions are used to prevent accidental\nassignment in conditions (i.e., accidental uses of the `=` operator,\ninstead of the `==` operator). However, Python does not allow assignments\nin conditions unless using the `:=` operator, so Yoda conditions provide\nno benefit in this regard.\n\n## Example\n```python\nif \"Foo\" == foo:\n ...\n```\n\nUse instead:\n```python\nif foo == \"Foo\":\n ...\n```\n\n## References\n- [Python documentation: Comparisons](https://docs.python.org/3/reference/expressions.html#comparisons)\n- [Python documentation: Assignment statements](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements)\n",
|
|
400
|
+
"ruff/SIM401": "## What it does\nChecks for `if` statements that can be replaced with `dict.get` calls.\n\n## Why is this bad?\n`dict.get()` calls can be used to replace `if` statements that assign a\nvalue to a variable in both branches, falling back to a default value if\nthe key is not found. When possible, using `dict.get` is more concise and\nmore idiomatic.\n\nUnder [preview mode](https://docs.astral.sh/ruff/preview), this rule will\nalso suggest replacing `if`-`else` _expressions_ with `dict.get` calls.\n\n## Example\n```python\nfoo = {}\nif \"bar\" in foo:\n value = foo[\"bar\"]\nelse:\n value = 0\n```\n\nUse instead:\n```python\nfoo = {}\nvalue = foo.get(\"bar\", 0)\n```\n\nIf preview mode is enabled:\n```python\nvalue = foo[\"bar\"] if \"bar\" in foo else 0\n```\n\nUse instead:\n```python\nvalue = foo.get(\"bar\", 0)\n```\n\n## Options\n\nThe rule will avoid flagging cases where using the resulting `dict.get` call would exceed the\nconfigured line length, as determined by these options:\n\n- `lint.pycodestyle.max-line-length`\n- `indent-width`\n\n## References\n- [Python documentation: Mapping Types](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict)\n",
|
|
401
|
+
"ruff/SIM905": "## What it does\nChecks for static `str.split` calls that can be replaced with list literals.\n\n## Why is this bad?\nList literals are more readable and do not require the overhead of calling `str.split`.\n\n## Example\n```python\n\"a,b,c,d\".split(\",\")\n```\n\nUse instead:\n```python\n[\"a\", \"b\", \"c\", \"d\"]\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe for implicit string concatenations with comments interleaved\nbetween segments, as comments may be removed.\n\nFor example, the fix would be marked as unsafe in the following case:\n```python\n(\n \"a\" # comment\n \",\" # comment\n \"b\" # comment\n).split(\",\")\n```\n\nas this is converted to `[\"a\", \"b\"]` without any of the comments.\n\n## References\n- [Python documentation: `str.split`](https://docs.python.org/3/library/stdtypes.html#str.split)\n",
|
|
402
|
+
"ruff/SIM910": "## What it does\nChecks for `dict.get()` calls that pass `None` as the default value.\n\n## Why is this bad?\n`None` is the default value for `dict.get()`, so it is redundant to pass it\nexplicitly.\n\n## Example\n```python\nages = {\"Tom\": 23, \"Maria\": 23, \"Dog\": 11}\nage = ages.get(\"Cat\", None)\n```\n\nUse instead:\n```python\nages = {\"Tom\": 23, \"Maria\": 23, \"Dog\": 11}\nage = ages.get(\"Cat\")\n```\n\n## Fix safety\nThis rule's fix is marked as safe, unless the expression contains comments.\n\n## References\n- [Python documentation: `dict.get`](https://docs.python.org/3/library/stdtypes.html#dict.get)\n",
|
|
403
|
+
"ruff/SIM911": "## What it does\nChecks for use of `zip()` to iterate over keys and values of a dictionary at once.\n\n## Why is this bad?\nThe `dict` type provides an `.items()` method which is faster and more readable.\n\n## Example\n```python\nflag_stars = {\"USA\": 50, \"Slovenia\": 3, \"Panama\": 2, \"Australia\": 6}\n\nfor country, stars in zip(flag_stars.keys(), flag_stars.values()):\n print(f\"{country}'s flag has {stars} stars.\")\n```\n\nUse instead:\n```python\nflag_stars = {\"USA\": 50, \"Slovenia\": 3, \"Panama\": 2, \"Australia\": 6}\n\nfor country, stars in flag_stars.items():\n print(f\"{country}'s flag has {stars} stars.\")\n```\n\n## Fix safety\nThis rule's fix is marked as safe, unless the expression contains comments.\n\n## References\n- [Python documentation: `dict.items`](https://docs.python.org/3/library/stdtypes.html#dict.items)\n",
|
|
404
|
+
"ruff/SLOT000": "## What it does\nChecks for subclasses of `str` that lack a `__slots__` definition.\n\n## Why is this bad?\nIn Python, the `__slots__` attribute allows you to explicitly define the\nattributes (instance variables) that a class can have. By default, Python\nuses a dictionary to store an object's attributes, which incurs some memory\noverhead. However, when `__slots__` is defined, Python uses a more compact\ninternal structure to store the object's attributes, resulting in memory\nsavings.\n\nSubclasses of `str` inherit all the attributes and methods of the built-in\n`str` class. Since strings are typically immutable, they don't require\nadditional attributes beyond what the `str` class provides. Defining\n`__slots__` for subclasses of `str` prevents the creation of a dictionary\nfor each instance, reducing memory consumption.\n\n## Example\n```python\nclass Foo(str):\n pass\n```\n\nUse instead:\n```python\nclass Foo(str):\n __slots__ = ()\n```\n\n## References\n- [Python documentation: `__slots__`](https://docs.python.org/3/reference/datamodel.html#slots)\n",
|
|
405
|
+
"ruff/SLOT001": "## What it does\nChecks for subclasses of `tuple` that lack a `__slots__` definition.\n\n## Why is this bad?\nIn Python, the `__slots__` attribute allows you to explicitly define the\nattributes (instance variables) that a class can have. By default, Python\nuses a dictionary to store an object's attributes, which incurs some memory\noverhead. However, when `__slots__` is defined, Python uses a more compact\ninternal structure to store the object's attributes, resulting in memory\nsavings.\n\nSubclasses of `tuple` inherit all the attributes and methods of the\nbuilt-in `tuple` class. Since tuples are typically immutable, they don't\nrequire additional attributes beyond what the `tuple` class provides.\nDefining `__slots__` for subclasses of `tuple` prevents the creation of a\ndictionary for each instance, reducing memory consumption.\n\n## Example\n```python\nclass Foo(tuple):\n pass\n```\n\nUse instead:\n```python\nclass Foo(tuple):\n __slots__ = ()\n```\n\n## References\n- [Python documentation: `__slots__`](https://docs.python.org/3/reference/datamodel.html#slots)\n",
|
|
406
|
+
"ruff/SLOT002": "## What it does\nChecks for subclasses of `collections.namedtuple` or `typing.NamedTuple`\nthat lack a `__slots__` definition.\n\n## Why is this bad?\nIn Python, the `__slots__` attribute allows you to explicitly define the\nattributes (instance variables) that a class can have. By default, Python\nuses a dictionary to store an object's attributes, which incurs some memory\noverhead. However, when `__slots__` is defined, Python uses a more compact\ninternal structure to store the object's attributes, resulting in memory\nsavings.\n\nSubclasses of `namedtuple` inherit all the attributes and methods of the\nbuilt-in `namedtuple` class. Since tuples are typically immutable, they\ndon't require additional attributes beyond what the `namedtuple` class\nprovides. Defining `__slots__` for subclasses of `namedtuple` prevents the\ncreation of a dictionary for each instance, reducing memory consumption.\n\n## Example\n```python\nfrom collections import namedtuple\n\n\nclass Foo(namedtuple(\"foo\", [\"str\", \"int\"])):\n pass\n```\n\nUse instead:\n```python\nfrom collections import namedtuple\n\n\nclass Foo(namedtuple(\"foo\", [\"str\", \"int\"])):\n __slots__ = ()\n```\n\n## References\n- [Python documentation: `__slots__`](https://docs.python.org/3/reference/datamodel.html#slots)\n",
|
|
407
|
+
"ruff/TID251": "## What it does\nChecks for banned imports.\n\n## Why is this bad?\nProjects may want to ensure that specific modules or module members are\nnot imported or accessed.\n\nSecurity or other company policies may be a reason to impose\nrestrictions on importing external Python libraries. In some cases,\nprojects may adopt conventions around the use of certain modules or\nmodule members that are not enforceable by the language itself.\n\nThis rule enforces certain import conventions project-wide automatically.\n\n## Options\n- `lint.flake8-tidy-imports.banned-api`\n- `lint.flake8-tidy-imports.extend-banned-api`\n",
|
|
408
|
+
"ruff/TID252": "## What it does\nChecks for relative imports.\n\n## Why is this bad?\nAbsolute imports, or relative imports from siblings, are recommended by [PEP 8]:\n\n> Absolute imports are recommended, as they are usually more readable and tend to be better behaved...\n> ```python\n> import mypkg.sibling\n> from mypkg import sibling\n> from mypkg.sibling import example\n> ```\n> However, explicit relative imports are an acceptable alternative to absolute imports,\n> especially when dealing with complex package layouts where using absolute imports would be\n> unnecessarily verbose:\n> ```python\n> from . import sibling\n> from .sibling import example\n> ```\n\n## Example\n```python\nfrom .. import foo\n```\n\nUse instead:\n```python\nfrom mypkg import foo\n```\n\n## Options\n- `lint.flake8-tidy-imports.ban-relative-imports`\n\n## Fix safety\nWhen available, this rule's fix is always marked as unsafe because Ruff\ninfers the absolute import path from the file's location and configured\npackage roots, while Python resolves relative imports from the module's\nruntime package. If those differ, the rewritten import can fail or resolve\nto a different module. The fix may also remove comments attached to the\nimport statement.\n\n[PEP 8]: https://peps.python.org/pep-0008/#imports\n",
|
|
409
|
+
"ruff/TID253": "## What it does\nChecks for module-level imports that should instead be imported lazily\n(e.g., within a function definition, or an `if TYPE_CHECKING:` block, or\nsome other nested context).\n\n## Why is this bad?\nSome modules are expensive to import. For example, importing `torch` or\n`tensorflow` can introduce a noticeable delay in the startup time of a\nPython program.\n\nIn such cases, you may want to enforce that the module is imported lazily\nas needed, rather than at the top of the file. This could involve inlining\nthe import into the function that uses it, rather than importing it\nunconditionally, to ensure that the module is only imported when necessary.\n\n## Example\n```python\nimport tensorflow as tf\n\n\ndef show_version():\n print(tf.__version__)\n```\n\nUse instead:\n```python\ndef show_version():\n import tensorflow as tf\n\n print(tf.__version__)\n```\n\n## Options\n- `lint.flake8-tidy-imports.banned-module-level-imports`\n",
|
|
410
|
+
"ruff/TID254": "## What it does\nEnforces the configured lazy-import policy in contexts where `lazy import`\nis legal.\n\nThis rule is not enforced in stub files.\n\n## Why is this bad?\nPython 3.15 adds support for `lazy import` and `lazy from ... import ...`,\nwhich defer the actual import work until the imported name is first used.\n\nDepending on the policy, some modules should be imported lazily to defer\nimport work until the name is first used, while others should remain eager\nto preserve import-time side effects.\n\nThe rule also recognizes imports made lazy by a literal `__lazy_modules__`\ndeclaration, including when the target version is older than Python 3.15.\nThis declaration allows a module to use lazy imports on Python 3.15 and\nlater while retaining eager imports on older versions. Dynamic assignments\nto `__lazy_modules__` (e.g. `__lazy_modules__ = non_literal()`) are ignored,\nas their effects cannot be determined statically.\n\nThis rule ignores contexts in which `lazy import` is invalid, such as\nfunctions, classes, `try`/`except` blocks, `__future__` imports, and\n`from ... import *` statements.\n\n## Example\n```python\nimport typing\n```\n\nUse instead:\n```python\nlazy import typing\n```\n\n## Fix availability\n\nThe fix is only available for statements that import a single name, since\nchanging `lazy` on a multi-member import could violate another name's policy.\n\nThe fix is also unavailable for imports marked lazy by a `__lazy_modules__`\ndeclaration.\n\n## Fix safety\n\nThis rule's fix is marked as unsafe because changing when a module is\nimported can affect runtime behavior, including import-time side effects.\n\n## Options\n- `lint.flake8-tidy-imports.require-lazy`\n- `lint.flake8-tidy-imports.ban-lazy`\n",
|
|
411
|
+
"ruff/TID255": "## What it does\nChecks for lazy imports that are resolved immediately at module load time.\n\n## Why is this bad?\nPython 3.15 adds support for `lazy import` and `lazy from ... import ...`,\nwhich defer the actual import work until the imported name is first used.\n\nWhen a lazily imported name is used immediately at module load time, the\nimport is resolved eagerly, defeating the purpose of marking the import as\nlazy. This is commonly caused by using a lazily imported module in a module\nglobal or in a top-level class definition.\n\nThe rule also recognizes imports made lazy by a literal `__lazy_modules__`\ndeclaration, even when the target version is older than Python 3.15.\nSuch imports remain eager on older Python versions. Dynamic assignments\nto `__lazy_modules__` (e.g. `__lazy_modules__ = non_literal()`) are ignored,\nas their effects cannot be determined statically.\n\n## Example\n```python\nlazy import foo\n\n\nclass Bar(foo.Foo): ...\n```\n\nUse instead:\n```python\nimport foo\n\n\nclass Bar(foo.Foo): ...\n```\n\n## Known problems\nRuff does not detect all cases where decorators evaluate annotations. For\nexample, `@dataclasses.dataclass` can immediately resolve lazy imports used in\nfield annotations without triggering this rule.\n\n## Fix availability\nThe fix is only available when the lazy import statement imports a single\nmember, since removing `lazy` from a multi-member import would make every\nimported member eager, including names that may not be resolved immediately.\nFixes are unavailable for imports governed by a `__lazy_modules__` declaration.\n\n## Fix safety\nThis rule's fix is marked as unsafe because converting a lazy import to an\neager import changes when the imported module is executed, which can change\nruntime behavior if the module has import-time side effects.\n\n## Options\n\nThe rule ignores imports required to be lazy by the following setting:\n\n- [`lint.flake8-tidy-imports.require-lazy`]\n",
|
|
412
|
+
"ruff/TD001": "## What it does\nChecks that a TODO comment is labelled with \"TODO\".\n\n## Why is this bad?\nAmbiguous tags reduce code visibility and can lead to dangling TODOs.\nFor example, if a comment is tagged with \"FIXME\" rather than \"TODO\", it may\nbe overlooked by future readers.\n\nNote that this rule will only flag \"FIXME\" and \"XXX\" tags as incorrect.\n\n## Example\n```python\n# FIXME(ruff): this should get fixed!\n```\n\nUse instead:\n```python\n# TODO(ruff): this is now fixed!\n```\n",
|
|
413
|
+
"ruff/TD002": "## What it does\nChecks that a TODO comment includes an author.\n\n## Why is this bad?\nIncluding an author on a TODO provides future readers with context around\nthe issue. While the TODO author is not always considered responsible for\nfixing the issue, they are typically the individual with the most context.\n\n## Example\n```python\n# TODO: should assign an author here\n```\n\nUse instead\n```python\n# TODO(charlie): now an author is assigned\n```\n",
|
|
414
|
+
"ruff/TD003": "## What it does\nChecks that a TODO comment is associated with a link to a relevant issue\nor ticket.\n\n## Why is this bad?\nIncluding an issue link near a TODO makes it easier for resolvers\nto get context around the issue.\n\n## Example\n```python\n# TODO: this link has no issue\n```\n\nUse one of these instead:\n```python\n# TODO(charlie): this comment has an issue link\n# https://github.com/astral-sh/ruff/issues/3870\n\n# TODO(charlie): this comment has a 3-digit issue code\n# 003\n\n# TODO(charlie): https://github.com/astral-sh/ruff/issues/3870\n# this comment has an issue link\n\n# TODO(charlie): #003 this comment has a 3-digit issue code\n# with leading character `#`\n\n# TODO(charlie): this comment has an issue code (matches the regex `[A-Z]+\\-?\\d+`)\n# SIXCHR-003\n```\n",
|
|
415
|
+
"ruff/TD004": "## What it does\nChecks that a \"TODO\" tag is followed by a colon.\n\n## Why is this bad?\n\"TODO\" tags are typically followed by a parenthesized author name, a colon,\na space, and a description of the issue, in that order.\n\nDeviating from this pattern can lead to inconsistent and non-idiomatic\ncomments.\n\n## Example\n```python\n# TODO(charlie) fix this colon\n```\n\nUsed instead:\n```python\n# TODO(charlie): colon fixed\n```\n",
|
|
416
|
+
"ruff/TD005": "## What it does\nChecks that a \"TODO\" tag contains a description of the issue following the\ntag itself.\n\n## Why is this bad?\nTODO comments should include a description of the issue to provide context\nfor future readers.\n\n## Example\n```python\n# TODO(charlie)\n```\n\nUse instead:\n```python\n# TODO(charlie): fix some issue\n```\n",
|
|
417
|
+
"ruff/TD006": "## What it does\nChecks that a \"TODO\" tag is properly capitalized (i.e., that the tag is\nuppercase).\n\n## Why is this bad?\nCapitalizing the \"TODO\" in a TODO comment is a convention that makes it\neasier for future readers to identify TODOs.\n\n## Example\n```python\n# todo(charlie): capitalize this\n```\n\nUse instead:\n```python\n# TODO(charlie): this is capitalized\n```\n",
|
|
418
|
+
"ruff/TD007": "## What it does\nChecks that the colon after a \"TODO\" tag is followed by a space.\n\n## Why is this bad?\n\"TODO\" tags are typically followed by a parenthesized author name, a colon,\na space, and a description of the issue, in that order.\n\nDeviating from this pattern can lead to inconsistent and non-idiomatic\ncomments.\n\n## Example\n```python\n# TODO(charlie):fix this\n```\n\nUse instead:\n```python\n# TODO(charlie): fix this\n```\n",
|
|
419
|
+
"ruff/TC001": "## What it does\nChecks for first-party imports that are only used for type annotations, but\naren't imported lazily or defined in a type-checking block.\n\n## Why is this bad?\nImports that are only used for type annotations add a performance overhead\nat runtime. For first-party imports, they can also contribute to import\ncycles. If an import is _only_ used in typing-only contexts, it can instead\nbe imported conditionally under an `if TYPE_CHECKING:` block to minimize\nruntime overhead.\n\nIf [`lint.flake8-type-checking.quote-annotations`] is set to `true`,\nannotations will be wrapped in quotes if doing so would enable the\ncorresponding import to be moved into an `if TYPE_CHECKING:` block.\n\nIf a class _requires_ that type annotations be available at runtime (as is\nthe case for Pydantic, SQLAlchemy, and other libraries), consider using\nthe [`lint.flake8-type-checking.runtime-evaluated-base-classes`] and\n[`lint.flake8-type-checking.runtime-evaluated-decorators`] settings to mark them\nas such.\n\nIf [`lint.future-annotations`] is set to `true`, `from __future__ import\nannotations` will be added if doing so would enable an import to be\nmoved into an `if TYPE_CHECKING:` block. This takes precedence over the\n[`lint.flake8-type-checking.quote-annotations`] setting described above if\nboth settings are enabled.\n\nOn Python 3.15 and later, lazy imports are also exempt, including imports\nmade lazy by a literal `__lazy_modules__` declaration. The fix prefers adding\n`lazy` to single-name import statements where the syntax is legal and\n[`lint.flake8-tidy-imports.ban-lazy`] allows it. This defers the import while\nkeeping the name available for runtime annotation inspection.\n\n## Example\n```python\nfrom __future__ import annotations\n\nfrom . import local_module\n\n\ndef func(sized: local_module.Container) -> int:\n return len(sized)\n```\n\nUse instead:\n```python\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from . import local_module\n\n\ndef func(sized: local_module.Container) -> int:\n return len(sized)\n```\n\nOn Python 3.15 and later, using a lazy import is also an option:\n```python\nlazy from . import local_module\n\n\ndef func(sized: local_module.Container) -> int:\n return len(sized)\n```\n\n## Fix safety\nThis rule's fixes are unsafe because changing when a module is imported can\naffect runtime behavior, including import-time side effects.\n\n## Options\n- `lint.flake8-tidy-imports.ban-lazy`\n- `lint.flake8-type-checking.quote-annotations`\n- `lint.flake8-type-checking.runtime-evaluated-base-classes`\n- `lint.flake8-type-checking.runtime-evaluated-decorators`\n- `lint.flake8-type-checking.strict`\n- `lint.typing-modules`\n- `lint.future-annotations`\n\n## References\n- [PEP 563: Runtime annotation resolution and `TYPE_CHECKING`](https://peps.python.org/pep-0563/#runtime-annotation-resolution-and-type-checking)\n",
|
|
420
|
+
"ruff/TC002": "## What it does\nChecks for third-party imports that are only used for type annotations, but\naren't imported lazily or defined in a type-checking block.\n\n## Why is this bad?\nImports that are only used for type annotations add a performance overhead\nat runtime. If an import is _only_ used in typing-only contexts, it can\ninstead be imported conditionally under an `if TYPE_CHECKING:` block to\nminimize runtime overhead.\n\nIf [`lint.flake8-type-checking.quote-annotations`] is set to `true`,\nannotations will be wrapped in quotes if doing so would enable the\ncorresponding import to be moved into an `if TYPE_CHECKING:` block.\n\nIf a class _requires_ that type annotations be available at runtime (as is\nthe case for Pydantic, SQLAlchemy, and other libraries), consider using\nthe [`lint.flake8-type-checking.runtime-evaluated-base-classes`] and\n[`lint.flake8-type-checking.runtime-evaluated-decorators`] settings to mark them\nas such.\n\nIf [`lint.future-annotations`] is set to `true`, `from __future__ import\nannotations` will be added if doing so would enable an import to be\nmoved into an `if TYPE_CHECKING:` block. This takes precedence over the\n[`lint.flake8-type-checking.quote-annotations`] setting described above if\nboth settings are enabled.\n\nOn Python 3.15 and later, lazy imports are also exempt, including imports\nmade lazy by a literal `__lazy_modules__` declaration. The fix prefers adding\n`lazy` to single-name import statements where the syntax is legal and\n[`lint.flake8-tidy-imports.ban-lazy`] allows it. This defers the import while\nkeeping the name available for runtime annotation inspection.\n\n## Example\n```python\nfrom __future__ import annotations\n\nimport pandas as pd\n\n\ndef func(df: pd.DataFrame) -> int:\n return len(df)\n```\n\nUse instead:\n```python\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n import pandas as pd\n\n\ndef func(df: pd.DataFrame) -> int:\n return len(df)\n```\n\nOn Python 3.15 and later, using a lazy import is also an option:\n```python\nlazy import pandas as pd\n\n\ndef func(df: pd.DataFrame) -> int:\n return len(df)\n```\n\n## Fix safety\nThis rule's fixes are unsafe because changing when a module is imported can\naffect runtime behavior, including import-time side effects.\n\n## Options\n- `lint.flake8-tidy-imports.ban-lazy`\n- `lint.flake8-type-checking.quote-annotations`\n- `lint.flake8-type-checking.runtime-evaluated-base-classes`\n- `lint.flake8-type-checking.runtime-evaluated-decorators`\n- `lint.flake8-type-checking.strict`\n- `lint.typing-modules`\n- `lint.future-annotations`\n\n## References\n- [PEP 563: Runtime annotation resolution and `TYPE_CHECKING`](https://peps.python.org/pep-0563/#runtime-annotation-resolution-and-type-checking)\n",
|
|
421
|
+
"ruff/TC003": "## What it does\nChecks for standard library imports that are only used for type\nannotations, but aren't imported lazily or defined in a type-checking block.\n\n## Why is this bad?\nImports that are only used for type annotations add a performance overhead\nat runtime. If an import is _only_ used in typing-only contexts, it can\ninstead be imported conditionally under an `if TYPE_CHECKING:` block to\nminimize runtime overhead.\n\nIf [`lint.flake8-type-checking.quote-annotations`] is set to `true`,\nannotations will be wrapped in quotes if doing so would enable the\ncorresponding import to be moved into an `if TYPE_CHECKING:` block.\n\nIf a class _requires_ that type annotations be available at runtime (as is\nthe case for Pydantic, SQLAlchemy, and other libraries), consider using\nthe [`lint.flake8-type-checking.runtime-evaluated-base-classes`] and\n[`lint.flake8-type-checking.runtime-evaluated-decorators`] settings to mark them\nas such.\n\nIf [`lint.future-annotations`] is set to `true`, `from __future__ import\nannotations` will be added if doing so would enable an import to be\nmoved into an `if TYPE_CHECKING:` block. This takes precedence over the\n[`lint.flake8-type-checking.quote-annotations`] setting described above if\nboth settings are enabled.\n\nOn Python 3.15 and later, lazy imports are also exempt, including imports\nmade lazy by a literal `__lazy_modules__` declaration. The fix prefers adding\n`lazy` to single-name import statements where the syntax is legal and\n[`lint.flake8-tidy-imports.ban-lazy`] allows it. This defers the import while\nkeeping the name available for runtime annotation inspection.\n\n## Example\n```python\nfrom __future__ import annotations\n\nfrom pathlib import Path\n\n\ndef func(path: Path) -> str:\n return str(path)\n```\n\nUse instead:\n```python\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from pathlib import Path\n\n\ndef func(path: Path) -> str:\n return str(path)\n```\n\nOn Python 3.15 and later, using a lazy import is also an option:\n```python\nlazy from pathlib import Path\n\n\ndef func(path: Path) -> str:\n return str(path)\n```\n\n## Fix safety\nThis rule's fixes are unsafe because changing when a module is imported can\naffect runtime behavior, including import-time side effects.\n\n## Options\n- `lint.flake8-tidy-imports.ban-lazy`\n- `lint.flake8-type-checking.quote-annotations`\n- `lint.flake8-type-checking.runtime-evaluated-base-classes`\n- `lint.flake8-type-checking.runtime-evaluated-decorators`\n- `lint.flake8-type-checking.strict`\n- `lint.typing-modules`\n- `lint.future-annotations`\n\n## References\n- [PEP 563: Runtime annotation resolution and `TYPE_CHECKING`](https://peps.python.org/pep-0563/#runtime-annotation-resolution-and-type-checking)\n",
|
|
422
|
+
"ruff/TC004": "## What it does\nChecks for imports that are required at runtime but are only defined in\ntype-checking blocks.\n\n## Why is this bad?\nThe type-checking block is not executed at runtime, so if the only definition\nof a symbol is in a type-checking block, it will not be available at runtime.\n\nIf [`lint.flake8-type-checking.quote-annotations`] is set to `true`,\nannotations will be wrapped in quotes if doing so would enable the\ncorresponding import to remain in the type-checking block.\n\n## Example\n```python\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n import foo\n\n\ndef bar() -> None:\n foo.bar() # raises NameError: name 'foo' is not defined\n```\n\nUse instead:\n```python\nimport foo\n\n\ndef bar() -> None:\n foo.bar()\n```\n\n## Options\n- `lint.flake8-type-checking.quote-annotations`\n\n## References\n- [PEP 563: Runtime annotation resolution and `TYPE_CHECKING`](https://peps.python.org/pep-0563/#runtime-annotation-resolution-and-type-checking)\n",
|
|
423
|
+
"ruff/TC005": "## What it does\nChecks for an empty type-checking block.\n\n## Why is this bad?\nThe type-checking block does not do anything and should be removed to avoid\nconfusion.\n\n## Example\n```python\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n pass\n\nprint(\"Hello, world!\")\n```\n\nUse instead:\n```python\nprint(\"Hello, world!\")\n```\n\n## References\n- [PEP 563: Runtime annotation resolution and `TYPE_CHECKING`](https://peps.python.org/pep-0563/#runtime-annotation-resolution-and-type-checking)\n",
|
|
424
|
+
"ruff/TC006": "## What it does\nChecks for unquoted type expressions in `typing.cast()` calls.\n\n## Why is this bad?\nThis rule helps enforce a consistent style across your codebase.\n\nIt's often necessary to quote the first argument passed to `cast()`,\nas type expressions can involve forward references, or references\nto symbols which are only imported in `typing.TYPE_CHECKING` blocks.\nThis can lead to a visual inconsistency across different `cast()` calls,\nwhere some type expressions are quoted but others are not. By enabling\nthis rule, you ensure that all type expressions passed to `cast()` are\nquoted, enforcing stylistic consistency across all of your `cast()` calls.\n\nIn some cases where `cast()` is used in a hot loop, this rule may also\nhelp avoid overhead from repeatedly evaluating complex type expressions at\nruntime.\n\n## Example\n```python\nfrom typing import cast\n\nx = cast(dict[str, int], foo)\n```\n\nUse instead:\n```python\nfrom typing import cast\n\nx = cast(\"dict[str, int]\", foo)\n```\n\n## Fix safety\nThis fix is safe as long as the type expression doesn't span multiple\nlines and includes comments on any of the lines apart from the last one.\n",
|
|
425
|
+
"ruff/TC007": "## What it does\nChecks if [PEP 613] explicit type aliases contain references to\nsymbols that are not available at runtime.\n\n## Why is this bad?\nReferencing type-checking only symbols results in a `NameError` at runtime.\n\n## Example\n```python\nfrom typing import TYPE_CHECKING, TypeAlias\n\nif TYPE_CHECKING:\n from foo import Foo\nOptFoo: TypeAlias = Foo | None\n```\n\nUse instead:\n```python\nfrom typing import TYPE_CHECKING, TypeAlias\n\nif TYPE_CHECKING:\n from foo import Foo\nOptFoo: TypeAlias = \"Foo | None\"\n```\n\n## Fix safety\nThis rule's fix is currently always marked as unsafe, since runtime\ntyping libraries may try to access/resolve the type alias in a way\nthat we can't statically determine during analysis and relies on the\ntype alias not containing any forward references.\n\n## References\n- [PEP 613 \u2013 Explicit Type Aliases](https://peps.python.org/pep-0613/)\n\n[PEP 613]: https://peps.python.org/pep-0613/\n",
|
|
426
|
+
"ruff/TC008": "## What it does\nChecks for unnecessary quotes in [PEP 613] explicit type aliases\nand [PEP 695] type statements.\n\n## Why is this bad?\nUnnecessary string forward references can lead to additional overhead\nin runtime libraries making use of type hints. They can also have bad\ninteractions with other runtime uses like [PEP 604] type unions.\n\nPEP-613 type aliases are only flagged by the rule if Ruff can have high\nconfidence that the quotes are unnecessary. Specifically, any PEP-613\ntype alias where the type expression on the right-hand side contains\nsubscripts or attribute accesses will not be flagged. This is because\ntype aliases can reference types that are, for example, generic in stub\nfiles but not at runtime. That can mean that a type checker expects the\nreferenced type to be subscripted with type arguments despite the fact\nthat doing so would fail at runtime if the type alias value was not\nquoted. Similarly, a type alias might need to reference a module-level\nattribute that exists in a stub file but not at runtime, meaning that\nthe type alias value would need to be quoted to avoid a runtime error.\n\n## Example\nGiven:\n```python\nfrom typing import TypeAlias\n\nOptInt: TypeAlias = \"int | None\"\n```\n\nUse instead:\n```python\nfrom typing import TypeAlias\n\nOptInt: TypeAlias = int | None\n```\n\nGiven:\n```python\ntype OptInt = \"int | None\"\n```\n\nUse instead:\n```python\ntype OptInt = int | None\n```\n\n## Fix safety\nThis rule's fix is marked as safe, unless the type annotation contains comments.\n\n## See also\nThis rule only applies to type aliases in non-stub files. For removing quotes in other\ncontexts or in stub files, see:\n\n- [`quoted-annotation-in-stub`][PYI020]: A rule that\n removes all quoted annotations from stub files\n- [`quoted-annotation`][UP037]: A rule that removes unnecessary quotes\n from *annotations* in runtime files.\n\n## References\n- [PEP 613 \u2013 Explicit Type Aliases](https://peps.python.org/pep-0613/)\n- [PEP 695: Generic Type Alias](https://peps.python.org/pep-0695/#generic-type-alias)\n- [PEP 604 \u2013 Allow writing union types as `X | Y`](https://peps.python.org/pep-0604/)\n\n[PEP 604]: https://peps.python.org/pep-0604/\n[PEP 613]: https://peps.python.org/pep-0613/\n[PEP 695]: https://peps.python.org/pep-0695/#generic-type-alias\n[PYI020]: https://docs.astral.sh/ruff/rules/quoted-annotation-in-stub/\n[UP037]: https://docs.astral.sh/ruff/rules/quoted-annotation/\n",
|
|
427
|
+
"ruff/TC010": "## What it does\nChecks for the presence of string literals in `X | Y`-style union types.\n\n## Why is this bad?\n[PEP 604] introduced a new syntax for union type annotations based on the\n`|` operator.\n\nWhile Python's type annotations can typically be wrapped in strings to\navoid runtime evaluation, the use of a string member within an `X | Y`-style\nunion type will cause a runtime error.\n\nInstead, remove the quotes, wrap the _entire_ union in quotes, or use\n`from __future__ import annotations` to disable runtime evaluation of\nannotations entirely.\n\n## Example\n```python\nvar: \"Foo\" | None\n\n\nclass Foo: ...\n```\n\nUse instead:\n```python\nfrom __future__ import annotations\n\nvar: Foo | None\n\n\nclass Foo: ...\n```\n\nOr, extend the quotes to include the entire union:\n```python\nvar: \"Foo | None\"\n\n\nclass Foo: ...\n```\n\n## References\n- [PEP 563 - Postponed Evaluation of Annotations](https://peps.python.org/pep-0563/)\n- [PEP 604 \u2013 Allow writing union types as `X | Y`](https://peps.python.org/pep-0604/)\n\n[PEP 604]: https://peps.python.org/pep-0604/\n",
|
|
428
|
+
"ruff/ARG001": "## What it does\nChecks for the presence of unused arguments in function definitions.\n\n## Why is this bad?\nAn argument that is defined but not used is likely a mistake, and should\nbe removed to avoid confusion.\n\nIf a variable is intentionally defined-but-not-used, it should be\nprefixed with an underscore, or some other value that adheres to the\n[`lint.dummy-variable-rgx`] pattern.\n\n## Example\n```python\ndef foo(bar, baz):\n return bar * 2\n```\n\nUse instead:\n```python\ndef foo(bar):\n return bar * 2\n```\n\n## Options\n- `lint.dummy-variable-rgx`\n",
|
|
429
|
+
"ruff/ARG002": "## What it does\nChecks for the presence of unused arguments in instance method definitions.\n\n## Why is this bad?\nAn argument that is defined but not used is likely a mistake, and should\nbe removed to avoid confusion.\n\nIf a variable is intentionally defined-but-not-used, it should be\nprefixed with an underscore, or some other value that adheres to the\n[`lint.dummy-variable-rgx`] pattern.\n\nThis rule exempts methods decorated with [`@typing.override`][override].\nRemoving a parameter from a subclass method (or changing a parameter's\nname) may cause type checkers to complain about a violation of the Liskov\nSubstitution Principle if it means that the method now incompatibly\noverrides a method defined on a superclass. Explicitly decorating an\noverriding method with `@override` signals to Ruff that the method is\nintended to override a superclass method and that a type checker will\nenforce that it does so; Ruff therefore knows that it should not enforce\nrules about unused arguments on such methods.\n\n## Example\n```python\nclass Class:\n def foo(self, arg1, arg2):\n print(arg1)\n```\n\nUse instead:\n```python\nclass Class:\n def foo(self, arg1):\n print(arg1)\n```\n\n## Options\n- `lint.dummy-variable-rgx`\n\n[override]: https://docs.python.org/3/library/typing.html#typing.override\n",
|
|
430
|
+
"ruff/ARG003": "## What it does\nChecks for the presence of unused arguments in class method definitions.\n\n## Why is this bad?\nAn argument that is defined but not used is likely a mistake, and should\nbe removed to avoid confusion.\n\nIf a variable is intentionally defined-but-not-used, it should be\nprefixed with an underscore, or some other value that adheres to the\n[`lint.dummy-variable-rgx`] pattern.\n\nThis rule exempts methods decorated with [`@typing.override`][override].\nRemoving a parameter from a subclass method (or changing a parameter's\nname) may cause type checkers to complain about a violation of the Liskov\nSubstitution Principle if it means that the method now incompatibly\noverrides a method defined on a superclass. Explicitly decorating an\noverriding method with `@override` signals to Ruff that the method is\nintended to override a superclass method and that a type checker will\nenforce that it does so; Ruff therefore knows that it should not enforce\nrules about unused arguments on such methods.\n\n## Example\n```python\nclass Class:\n @classmethod\n def foo(cls, arg1, arg2):\n print(arg1)\n```\n\nUse instead:\n```python\nclass Class:\n @classmethod\n def foo(cls, arg1):\n print(arg1)\n```\n\n## Options\n- `lint.dummy-variable-rgx`\n\n[override]: https://docs.python.org/3/library/typing.html#typing.override\n",
|
|
431
|
+
"ruff/ARG004": "## What it does\nChecks for the presence of unused arguments in static method definitions.\n\n## Why is this bad?\nAn argument that is defined but not used is likely a mistake, and should\nbe removed to avoid confusion.\n\nIf a variable is intentionally defined-but-not-used, it should be\nprefixed with an underscore, or some other value that adheres to the\n[`lint.dummy-variable-rgx`] pattern.\n\nThis rule exempts methods decorated with [`@typing.override`][override].\nRemoving a parameter from a subclass method (or changing a parameter's\nname) may cause type checkers to complain about a violation of the Liskov\nSubstitution Principle if it means that the method now incompatibly\noverrides a method defined on a superclass. Explicitly decorating an\noverriding method with `@override` signals to Ruff that the method is\nintended to override a superclass method, and that a type checker will\nenforce that it does so; Ruff therefore knows that it should not enforce\nrules about unused arguments on such methods.\n\n## Example\n```python\nclass Class:\n @staticmethod\n def foo(arg1, arg2):\n print(arg1)\n```\n\nUse instead:\n```python\nclass Class:\n @staticmethod\n def foo(arg1):\n print(arg1)\n```\n\n## Options\n- `lint.dummy-variable-rgx`\n\n[override]: https://docs.python.org/3/library/typing.html#typing.override\n",
|
|
432
|
+
"ruff/ARG005": "## What it does\nChecks for the presence of unused arguments in lambda expression\ndefinitions.\n\n## Why is this bad?\nAn argument that is defined but not used is likely a mistake, and should\nbe removed to avoid confusion.\n\nIf a variable is intentionally defined-but-not-used, it should be\nprefixed with an underscore, or some other value that adheres to the\n[`lint.dummy-variable-rgx`] pattern.\n\n## Example\n```python\nmy_list = [1, 2, 3, 4, 5]\nsquares = map(lambda x, y: x**2, my_list)\n```\n\nUse instead:\n```python\nmy_list = [1, 2, 3, 4, 5]\nsquares = map(lambda x: x**2, my_list)\n```\n\n## Options\n- `lint.dummy-variable-rgx`\n",
|
|
433
|
+
"ruff/PTH100": "## What it does\nChecks for uses of `os.path.abspath`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os.path`. When possible, using `Path` object\nmethods such as `Path.resolve()` can improve readability over the `os.path`\nmodule's counterparts (e.g., `os.path.abspath()`).\n\n## Examples\n```python\nimport os\n\nfile_path = os.path.abspath(\"../path/to/file\")\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nfile_path = Path(\"../path/to/file\").resolve()\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is always marked as unsafe because `Path.resolve()` resolves symlinks, while\n`os.path.abspath()` does not. If resolving symlinks is important, you may need to use\n`Path.absolute()`. However, `Path.absolute()` also does not remove any `..` components in a\npath, unlike `os.path.abspath()` and `Path.resolve()`, so if that specific combination of\nbehaviors is required, there's no existing `pathlib` alternative. See CPython issue\n[#69200](https://github.com/python/cpython/issues/69200).\n\nAdditionally, the fix is marked as unsafe because `os.path.abspath()` returns `str` or `bytes` (`AnyStr`),\nwhile `Path.resolve()` returns a `Path` object. This change in return type can break code that uses\nthe return value.\n\n## References\n- [Python documentation: `Path.resolve`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.resolve)\n- [Python documentation: `os.path.abspath`](https://docs.python.org/3/library/os.path.html#os.path.abspath)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
434
|
+
"ruff/PTH101": "## What it does\nChecks for uses of `os.chmod`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os`. When possible, using `Path` object\nmethods such as `Path.chmod()` can improve readability over the `os`\nmodule's counterparts (e.g., `os.chmod()`).\n\n## Examples\n```python\nimport os\n\nos.chmod(\"file.py\", 0o444)\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(\"file.py\").chmod(0o444)\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\n\n## References\n- [Python documentation: `Path.chmod`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.chmod)\n- [Python documentation: `os.chmod`](https://docs.python.org/3/library/os.html#os.chmod)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
435
|
+
"ruff/PTH102": "## What it does\nChecks for uses of `os.mkdir`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os`. When possible, using `Path` object\nmethods such as `Path.mkdir()` can improve readability over the `os`\nmodule's counterparts (e.g., `os.mkdir()`).\n\n## Examples\n```python\nimport os\n\nos.mkdir(\"./directory/\")\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(\"./directory/\").mkdir()\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\n\n## References\n- [Python documentation: `Path.mkdir`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.mkdir)\n- [Python documentation: `os.mkdir`](https://docs.python.org/3/library/os.html#os.mkdir)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
436
|
+
"ruff/PTH103": "## What it does\nChecks for uses of `os.makedirs`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os`. When possible, using `Path` object\nmethods such as `Path.mkdir(parents=True)` can improve readability over the\n`os` module's counterparts (e.g., `os.makedirs()`.\n\n## Examples\n```python\nimport os\n\nos.makedirs(\"./nested/directory/\")\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(\"./nested/directory/\").mkdir(parents=True)\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\n\n## References\n- [Python documentation: `Path.mkdir`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.mkdir)\n- [Python documentation: `os.makedirs`](https://docs.python.org/3/library/os.html#os.makedirs)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
437
|
+
"ruff/PTH104": "## What it does\nChecks for uses of `os.rename`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os`. When possible, using `Path` object\nmethods such as `Path.rename()` can improve readability over the `os`\nmodule's counterparts (e.g., `os.rename()`).\n\n## Examples\n```python\nimport os\n\nos.rename(\"old.py\", \"new.py\")\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(\"old.py\").rename(\"new.py\")\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\nAdditionally, the fix is marked as unsafe when the return value is used because the type changes\nfrom `None` to a `Path` object.\n\n## References\n- [Python documentation: `Path.rename`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.rename)\n- [Python documentation: `os.rename`](https://docs.python.org/3/library/os.html#os.rename)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
438
|
+
"ruff/PTH105": "## What it does\nChecks for uses of `os.replace`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os`. When possible, using `Path` object\nmethods such as `Path.replace()` can improve readability over the `os`\nmodule's counterparts (e.g., `os.replace()`).\n\nNote that `os` functions may be preferable if performance is a concern,\ne.g., in hot loops.\n\n## Examples\n```python\nimport os\n\nos.replace(\"old.py\", \"new.py\")\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(\"old.py\").replace(\"new.py\")\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\nAdditionally, the fix is marked as unsafe when the return value is used because the type changes\nfrom `None` to a `Path` object.\n\n## References\n- [Python documentation: `Path.replace`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.replace)\n- [Python documentation: `os.replace`](https://docs.python.org/3/library/os.html#os.replace)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
439
|
+
"ruff/PTH106": "## What it does\nChecks for uses of `os.rmdir`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os`. When possible, using `Path` object\nmethods such as `Path.rmdir()` can improve readability over the `os`\nmodule's counterparts (e.g., `os.rmdir()`).\n\n## Examples\n```python\nimport os\n\nos.rmdir(\"folder/\")\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(\"folder/\").rmdir()\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\n\n## References\n- [Python documentation: `Path.rmdir`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.rmdir)\n- [Python documentation: `os.rmdir`](https://docs.python.org/3/library/os.html#os.rmdir)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
440
|
+
"ruff/PTH107": "## What it does\nChecks for uses of `os.remove`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os`. When possible, using `Path` object\nmethods such as `Path.unlink()` can improve readability over the `os`\nmodule's counterparts (e.g., `os.remove()`).\n\n## Examples\n```python\nimport os\n\nos.remove(\"file.py\")\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(\"file.py\").unlink()\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\n\n## References\n- [Python documentation: `Path.unlink`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.unlink)\n- [Python documentation: `os.remove`](https://docs.python.org/3/library/os.html#os.remove)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
441
|
+
"ruff/PTH108": "## What it does\nChecks for uses of `os.unlink`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os`. When possible, using `Path` object\nmethods such as `Path.unlink()` can improve readability over the `os`\nmodule's counterparts (e.g., `os.unlink()`).\n\n## Examples\n```python\nimport os\n\nos.unlink(\"file.py\")\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(\"file.py\").unlink()\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\n\n## References\n- [Python documentation: `Path.unlink`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.unlink)\n- [Python documentation: `os.unlink`](https://docs.python.org/3/library/os.html#os.unlink)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
442
|
+
"ruff/PTH109": "## What it does\nChecks for uses of `os.getcwd` and `os.getcwdb`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os`. When possible, using `Path` object\nmethods such as `Path.cwd()` can improve readability over the `os`\nmodule's counterparts (e.g., `os.getcwd()`).\n\n## Examples\n```python\nimport os\n\ncwd = os.getcwd()\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\ncwd = Path.cwd()\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\nAdditionally, the fix is marked as unsafe when the return value is used because the type changes\nfrom `str` or `bytes` to a `Path` object.\n\n## References\n- [Python documentation: `Path.cwd`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.cwd)\n- [Python documentation: `os.getcwd`](https://docs.python.org/3/library/os.html#os.getcwd)\n- [Python documentation: `os.getcwdb`](https://docs.python.org/3/library/os.html#os.getcwdb)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
443
|
+
"ruff/PTH110": "## What it does\nChecks for uses of `os.path.exists`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os.path`. When possible, using `Path` object\nmethods such as `Path.exists()` can improve readability over the `os.path`\nmodule's counterparts (e.g., `os.path.exists()`).\n\n## Examples\n```python\nimport os\n\nos.path.exists(\"file.py\")\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(\"file.py\").exists()\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\n\n## References\n- [Python documentation: `Path.exists`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.exists)\n- [Python documentation: `os.path.exists`](https://docs.python.org/3/library/os.path.html#os.path.exists)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
444
|
+
"ruff/PTH111": "## What it does\nChecks for uses of `os.path.expanduser`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os.path`. When possible, using `Path` object\nmethods such as `Path.expanduser()` can improve readability over the `os.path`\nmodule's counterparts (e.g., as `os.path.expanduser()`).\n\n## Examples\n```python\nimport os\n\nos.path.expanduser(\"~/films/Monty Python\")\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(\"~/films/Monty Python\").expanduser()\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is always marked as unsafe because the behaviors of\n`os.path.expanduser` and `Path.expanduser` differ when a user's home\ndirectory can't be resolved: `os.path.expanduser` returns the\ninput unchanged, while `Path.expanduser` raises `RuntimeError`.\n\nAdditionally, the fix is marked as unsafe because `os.path.expanduser()` returns `str` or `bytes` (`AnyStr`),\nwhile `Path.expanduser()` returns a `Path` object. This change in return type can break code that uses\nthe return value.\n\n## References\n- [Python documentation: `Path.expanduser`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.expanduser)\n- [Python documentation: `os.path.expanduser`](https://docs.python.org/3/library/os.path.html#os.path.expanduser)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
445
|
+
"ruff/PTH112": "## What it does\nChecks for uses of `os.path.isdir`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os.path`. When possible, using `Path` object\nmethods such as `Path.is_dir()` can improve readability over the `os.path`\nmodule's counterparts (e.g., `os.path.isdir()`).\n\n## Examples\n```python\nimport os\n\nos.path.isdir(\"docs\")\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(\"docs\").is_dir()\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\n\n## References\n- [Python documentation: `Path.is_dir`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.is_dir)\n- [Python documentation: `os.path.isdir`](https://docs.python.org/3/library/os.path.html#os.path.isdir)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
446
|
+
"ruff/PTH113": "## What it does\nChecks for uses of `os.path.isfile`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os.path`. When possible, using `Path` object\nmethods such as `Path.is_file()` can improve readability over the `os.path`\nmodule's counterparts (e.g., `os.path.isfile()`).\n\n## Examples\n```python\nimport os\n\nos.path.isfile(\"docs\")\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(\"docs\").is_file()\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\n\n## References\n- [Python documentation: `Path.is_file`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.is_file)\n- [Python documentation: `os.path.isfile`](https://docs.python.org/3/library/os.path.html#os.path.isfile)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
447
|
+
"ruff/PTH114": "## What it does\nChecks for uses of `os.path.islink`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os.path`. When possible, using `Path` object\nmethods such as `Path.is_symlink()` can improve readability over the `os.path`\nmodule's counterparts (e.g., `os.path.islink()`).\n\n## Examples\n```python\nimport os\n\nos.path.islink(\"docs\")\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(\"docs\").is_symlink()\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\n\n## References\n- [Python documentation: `Path.is_symlink`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.is_symlink)\n- [Python documentation: `os.path.islink`](https://docs.python.org/3/library/os.path.html#os.path.islink)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
448
|
+
"ruff/PTH115": "## What it does\nChecks for uses of `os.readlink`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os`. When possible, using `Path` object\nmethods such as `Path.readlink()` can improve readability over the `os`\nmodule's counterparts (e.g., `os.readlink()`).\n\n## Examples\n```python\nimport os\n\nos.readlink(file_name)\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(file_name).readlink()\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\nAdditionally, the fix is marked as unsafe when the return value is used because the type changes\nfrom `str` or `bytes` (`AnyStr`) to a `Path` object.\n\n## References\n- [Python documentation: `Path.readlink`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.readline)\n- [Python documentation: `os.readlink`](https://docs.python.org/3/library/os.html#os.readlink)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
449
|
+
"ruff/PTH116": "## What it does\nChecks for uses of `os.stat`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os`. When possible, using `Path` object\nmethods such as `Path.stat()` can improve readability over the `os`\nmodule's counterparts (e.g., `os.path.stat()`).\n\n## Examples\n```python\nimport os\nfrom pwd import getpwuid\nfrom grp import getgrgid\n\nstat = os.stat(file_name)\nowner_name = getpwuid(stat.st_uid).pw_name\ngroup_name = getgrgid(stat.st_gid).gr_name\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nfile_path = Path(file_name)\nstat = file_path.stat()\nowner_name = file_path.owner()\ngroup_name = file_path.group()\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is always marked as unsafe because `pathlib.Path` and `os.stat` differ in their\nhandling of `bytes` paths and file descriptors.\n\n## References\n- [Python documentation: `Path.stat`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.stat)\n- [Python documentation: `Path.group`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.group)\n- [Python documentation: `Path.owner`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.owner)\n- [Python documentation: `os.stat`](https://docs.python.org/3/library/os.html#os.stat)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
450
|
+
"ruff/PTH117": "## What it does\nChecks for uses of `os.path.isabs`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os.path`. When possible, using `Path` object\nmethods such as `Path.is_absolute()` can improve readability over the `os.path`\nmodule's counterparts (e.g., as `os.path.isabs()`).\n\n## Examples\n```python\nimport os\n\nif os.path.isabs(file_name):\n print(\"Absolute path!\")\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nif Path(file_name).is_absolute():\n print(\"Absolute path!\")\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## References\n- [Python documentation: `PurePath.is_absolute`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.is_absolute)\n- [Python documentation: `os.path.isabs`](https://docs.python.org/3/library/os.path.html#os.path.isabs)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
451
|
+
"ruff/PTH118": "## What it does\nChecks for uses of `os.path.join`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os.path`. When possible, using `Path` object\nmethods such as `Path.joinpath()` or the `/` operator can improve\nreadability over the `os.path` module's counterparts (e.g., `os.path.join()`).\n\n## Examples\n```python\nimport os\n\nos.path.join(os.path.join(ROOT_PATH, \"folder\"), \"file.py\")\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(ROOT_PATH) / \"folder\" / \"file.py\"\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## References\n- [Python documentation: `PurePath.joinpath`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.joinpath)\n- [Python documentation: `os.path.join`](https://docs.python.org/3/library/os.path.html#os.path.join)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
452
|
+
"ruff/PTH119": "## What it does\nChecks for uses of `os.path.basename`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os.path`. When possible, using `Path` object\nmethods such as `Path.name` can improve readability over the `os.path`\nmodule's counterparts (e.g., `os.path.basename()`).\n\n## Examples\n```python\nimport os\n\nos.path.basename(__file__)\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(__file__).name\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is always marked as unsafe because the replacement is not always semantically\nequivalent to the original code. In particular, `pathlib` performs path normalization,\nwhich can alter the result compared to `os.path.basename`. For example, this normalization:\n\n- Collapses consecutive slashes (e.g., `\"a//b\"` \u2192 `\"a/b\"`).\n- Removes trailing slashes (e.g., `\"a/b/\"` \u2192 `\"a/b\"`).\n- Eliminates `\".\"` (e.g., `\"a/./b\"` \u2192 `\"a/b\"`).\n\nAs a result, code relying on the exact string returned by `os.path.basename`\nmay behave differently after the fix.\n\n## References\n- [Python documentation: `PurePath.name`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.name)\n- [Python documentation: `os.path.basename`](https://docs.python.org/3/library/os.path.html#os.path.basename)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
453
|
+
"ruff/PTH120": "## What it does\nChecks for uses of `os.path.dirname`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os.path`. When possible, using `Path` object\nmethods such as `Path.parent` can improve readability over the `os.path`\nmodule's counterparts (e.g., `os.path.dirname()`).\n\n## Examples\n```python\nimport os\n\nos.path.dirname(__file__)\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(__file__).parent\n```\n\n## Fix Safety\nThis rule's fix is always marked as unsafe because the replacement is not always semantically\nequivalent to the original code. In particular, `pathlib` performs path normalization,\nwhich can alter the result compared to `os.path.dirname`. For example, this normalization:\n\n- Collapses consecutive slashes (e.g., `\"a//b\"` \u2192 `\"a/b\"`).\n- Removes trailing slashes (e.g., `\"a/b/\"` \u2192 `\"a/b\"`).\n- Eliminates `\".\"` (e.g., `\"a/./b\"` \u2192 `\"a/b\"`).\n\nAs a result, code relying on the exact string returned by `os.path.dirname`\nmay behave differently after the fix.\n\nAdditionally, the fix is marked as unsafe because `os.path.dirname()` returns `str` or `bytes` (`AnyStr`),\nwhile `Path.parent` returns a `Path` object. This change in return type can break code that uses\nthe return value.\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## References\n- [Python documentation: `PurePath.parent`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.parent)\n- [Python documentation: `os.path.dirname`](https://docs.python.org/3/library/os.path.html#os.path.dirname)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
454
|
+
"ruff/PTH121": "## What it does\nChecks for uses of `os.path.samefile`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os.path`. When possible, using `Path` object\nmethods such as `Path.samefile()` can improve readability over the `os.path`\nmodule's counterparts (e.g., `os.path.samefile()`).\n\n## Examples\n```python\nimport os\n\nos.path.samefile(\"f1.py\", \"f2.py\")\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(\"f1.py\").samefile(\"f2.py\")\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\n\n## References\n- [Python documentation: `Path.samefile`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.samefile)\n- [Python documentation: `os.path.samefile`](https://docs.python.org/3/library/os.path.html#os.path.samefile)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
455
|
+
"ruff/PTH122": "## What it does\nChecks for uses of `os.path.splitext`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os.path`. When possible, using `Path` object\nmethods such as `Path.suffix` and `Path.stem` can improve readability over\nthe `os.path` module's counterparts (e.g., `os.path.splitext()`).\n\n`os.path.splitext()` specifically returns a tuple of the file root and\nextension (e.g., given `splitext('/foo/bar.py')`, `os.path.splitext()`\nreturns `(\"foo/bar\", \".py\")`. These outputs can be reconstructed through a\ncombination of `Path.suffix` (`\".py\"`), `Path.stem` (`\"bar\"`), and\n`Path.parent` (`\"foo\"`).\n\n## Examples\n```python\nimport os\n\n(root, ext) = os.path.splitext(\"foo/bar.py\")\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\npath = Path(\"foo/bar.py\")\nroot = path.parent / path.stem\next = path.suffix\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## References\n- [Python documentation: `Path.suffix`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.suffix)\n- [Python documentation: `Path.suffixes`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.suffixes)\n- [Python documentation: `os.path.splitext`](https://docs.python.org/3/library/os.path.html#os.path.splitext)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
456
|
+
"ruff/PTH123": "## What it does\nChecks for uses of the `open()` builtin.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation. When possible,\nusing `Path` object methods such as `Path.open()` can improve readability\nover the `open` builtin.\n\n## Examples\n```python\nwith open(\"f1.py\", \"wb\") as fp:\n ...\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nwith Path(\"f1.py\").open(\"wb\") as fp:\n ...\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than working directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\n\n## References\n- [Python documentation: `Path.open`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.open)\n- [Python documentation: `open`](https://docs.python.org/3/library/functions.html#open)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
457
|
+
"ruff/PTH124": "## What it does\nChecks for uses of the `py.path` library.\n\n## Why is this bad?\nThe `py.path` library is in maintenance mode. Instead, prefer the standard\nlibrary's `pathlib` module, or third-party modules like `path` (formerly\n`py.path`).\n\n## Examples\n```python\nimport py.path\n\np = py.path.local(\"/foo/bar\").join(\"baz/qux\")\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\np = Path(\"/foo/bar\") / \"bar\" / \"qux\"\n```\n\n## References\n- [Python documentation: `Pathlib`](https://docs.python.org/3/library/pathlib.html)\n- [Path repository](https://github.com/jaraco/path)\n",
|
|
458
|
+
"ruff/PTH201": "## What it does\nChecks for `pathlib.Path` objects that are initialized with the current\ndirectory.\n\n## Why is this bad?\nThe `Path()` constructor defaults to the current directory, so passing it\nin explicitly (as `\".\"`) is unnecessary.\n\n## Example\n```python\nfrom pathlib import Path\n\n_ = Path(\".\")\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\n_ = Path()\n```\n\n## Fix safety\nThis fix is marked unsafe if there are comments inside the parentheses, as applying\nthe fix will delete them.\n\n## References\n- [Python documentation: `Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)\n",
|
|
459
|
+
"ruff/PTH202": "## What it does\nChecks for uses of `os.path.getsize`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os.path`.\n\nWhen possible, using `Path` object methods such as `Path.stat()` can\nimprove readability over the `os.path` module's counterparts (e.g.,\n`os.path.getsize()`).\n\n## Example\n```python\nimport os\n\nos.path.getsize(__file__)\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(__file__).stat().st_size\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\n\n## References\n- [Python documentation: `Path.stat`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.stat)\n- [Python documentation: `os.path.getsize`](https://docs.python.org/3/library/os.path.html#os.path.getsize)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
460
|
+
"ruff/PTH203": "## What it does\nChecks for uses of `os.path.getatime`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os.path`.\n\nWhen possible, using `Path` object methods such as `Path.stat()` can\nimprove readability over the `os.path` module's counterparts (e.g.,\n`os.path.getatime()`).\n\n## Example\n```python\nimport os\n\nos.path.getatime(__file__)\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(__file__).stat().st_atime\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\n\n## References\n- [Python documentation: `Path.stat`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.stat)\n- [Python documentation: `os.path.getatime`](https://docs.python.org/3/library/os.path.html#os.path.getatime)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
461
|
+
"ruff/PTH204": "## What it does\nChecks for uses of `os.path.getmtime`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os.path`.\n\nWhen possible, using `Path` object methods such as `Path.stat()` can\nimprove readability over the `os.path` module's counterparts (e.g.,\n`os.path.getmtime()`).\n\n## Example\n```python\nimport os\n\nos.path.getmtime(__file__)\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(__file__).stat().st_mtime\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\n\n## References\n- [Python documentation: `Path.stat`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.stat)\n- [Python documentation: `os.path.getmtime`](https://docs.python.org/3/library/os.path.html#os.path.getmtime)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
462
|
+
"ruff/PTH205": "## What it does\nChecks for uses of `os.path.getctime`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os.path`.\n\nWhen possible, using `Path` object methods such as `Path.stat()` can\nimprove readability over the `os.path` module's counterparts (e.g.,\n`os.path.getctime()`).\n\n## Example\n```python\nimport os\n\nos.path.getctime(__file__)\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(__file__).stat().st_ctime\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\n\n## References\n- [Python documentation: `Path.stat`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.stat)\n- [Python documentation: `os.path.getctime`](https://docs.python.org/3/library/os.path.html#os.path.getctime)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
463
|
+
"ruff/PTH206": "## What it does\nChecks for uses of `.split(os.sep)`\n\n## Why is this bad?\nThe `pathlib` module in the standard library should be used for path\nmanipulation. It provides a high-level API with the functionality\nneeded for common operations on `Path` objects.\n\n## Example\nIf not all parts of the path are needed, then the `name` and `parent`\nattributes of the `Path` object should be used. Otherwise, the `parts`\nattribute can be used as shown in the last example.\n```python\nimport os\n\n\"path/to/file_name.txt\".split(os.sep)[-1]\n\n\"path/to/file_name.txt\".split(os.sep)[-2]\n\n# Iterating over the path parts\nif any(part in blocklist for part in \"my/file/path\".split(os.sep)):\n ...\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(\"path/to/file_name.txt\").name\n\nPath(\"path/to/file_name.txt\").parent.name\n\n# Iterating over the path parts\nif any(part in blocklist for part in Path(\"my/file/path\").parts):\n ...\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than working directly with strings,\nespecially on older versions of Python.\n\n## References\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
464
|
+
"ruff/PTH207": "## What it does\nChecks for the use of `glob.glob()` and `glob.iglob()`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os` and `glob`.\n\nWhen possible, using `Path` object methods such as `Path.glob()` can\nimprove readability over their low-level counterparts (e.g.,\n`glob.glob()`).\n\nNote that `glob.glob()` and `Path.glob()` are not exact equivalents:\n\n| | `glob`-module functions | `Path.glob()` |\n|-------------------|------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------|\n| Hidden files | Hidden files are excluded by default. On Python 3.11+, the `include_hidden` keyword can be used to include hidden directories. | Includes hidden files by default. |\n| Eagerness | `glob.iglob()` returns a lazy iterator. Under the hood, `glob.glob()` simply converts the iterator to a list. | `Path.glob()` returns a lazy iterator. |\n| Working directory | `glob.glob()` and `glob.iglob()` take a `root_dir` keyword to set the current working directory. | `Path.rglob()` can be used to return the relative path. |\n| Globstar (`**`) | The `recursive` flag must be set to `True` for the `**` pattern to match any files and zero or more directories, subdirectories, and symbolic links. | The `**` pattern in `Path.glob()` means \"this directory and all subdirectories, recursively\". In other words, it enables recursive globbing. |\n\n## Example\n```python\nimport glob\nimport os\n\nglob.glob(os.path.join(\"my_path\", \"requirements*.txt\"))\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(\"my_path\").glob(\"requirements*.txt\")\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## References\n- [Python documentation: `Path.glob`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.glob)\n- [Python documentation: `Path.rglob`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.rglob)\n- [Python documentation: `glob.glob`](https://docs.python.org/3/library/glob.html#glob.glob)\n- [Python documentation: `glob.iglob`](https://docs.python.org/3/library/glob.html#glob.iglob)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
465
|
+
"ruff/PTH208": "## What it does\nChecks for uses of `os.listdir`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os`. When possible, using `pathlib`'s\n`Path.iterdir()` can improve readability over `os.listdir()`.\n\n## Example\n\n```python\np = \".\"\nfor d in os.listdir(p):\n ...\n\nif os.listdir(p):\n ...\n\nif \"file\" in os.listdir(p):\n ...\n```\n\nUse instead:\n\n```python\np = Path(\".\")\nfor d in p.iterdir():\n ...\n\nif any(p.iterdir()):\n ...\n\nif (p / \"file\").exists():\n ...\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## References\n- [Python documentation: `Path.iterdir`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.iterdir)\n- [Python documentation: `os.listdir`](https://docs.python.org/3/library/os.html#os.listdir)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
466
|
+
"ruff/PTH210": "## What it does\nChecks for `pathlib.Path.with_suffix()` calls where\nthe given suffix does not have a leading dot\nor the given suffix is a single dot `\".\"` and the\nPython version is less than 3.14.\n\n## Why is this bad?\n`Path.with_suffix()` will raise an error at runtime\nif the given suffix is not prefixed with a dot\nor, in versions prior to Python 3.14, if it is a single dot `\".\"`.\n\n## Example\n\n```python\nfrom pathlib import Path\n\npath = Path()\n\npath.with_suffix(\"py\")\n```\n\nUse instead:\n\n```python\nfrom pathlib import Path\n\npath = Path()\n\npath.with_suffix(\".py\")\n```\n\n## Known problems\nThis rule is likely to have false negatives, as Ruff can only emit the\nlint if it can say for sure that a binding refers to a `Path` object at\nruntime. Due to type inference limitations, Ruff is currently only\nconfident about this if it can see that the binding originates from a\nfunction parameter annotated with `Path` or from a direct assignment to a\n`Path()` constructor call.\n\n## Fix safety\nThe fix for this rule adds a leading period to the string passed\nto the `with_suffix()` call. This fix is marked as unsafe, as it\nchanges runtime behaviour: the call would previously always have\nraised an exception, but no longer will.\n\nMoreover, it's impossible to determine if this is the correct fix\nfor a given situation (it's possible that the string was correct\nbut was being passed to the wrong method entirely, for example).\n\nNo fix is offered if the suffix `\".\"` is given, since the intent is unclear.\n",
|
|
467
|
+
"ruff/PTH211": "## What it does\nChecks for uses of `os.symlink`.\n\n## Why is this bad?\n`pathlib` offers a high-level API for path manipulation, as compared to\nthe lower-level API offered by `os.symlink`.\n\n## Example\n```python\nimport os\n\nos.symlink(\"usr/bin/python\", \"tmp/python\", target_is_directory=False)\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(\"tmp/python\").symlink_to(\"usr/bin/python\")\n```\n\n## Known issues\nWhile using `pathlib` can improve the readability and type safety of your code,\nit can be less performant than the lower-level alternatives that work directly with strings,\nespecially on older versions of Python.\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\n\n## References\n- [Python documentation: `Path.symlink_to`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.symlink_to)\n- [PEP 428 \u2013 The pathlib module \u2013 object-oriented filesystem paths](https://peps.python.org/pep-0428/)\n- [Correspondence between `os` and `pathlib`](https://docs.python.org/3/library/pathlib.html#corresponding-tools)\n- [Why you should be using pathlib](https://treyhunner.com/2018/12/why-you-should-be-using-pathlib/)\n- [No really, pathlib is great](https://treyhunner.com/2019/01/no-really-pathlib-is-great/)\n",
|
|
468
|
+
"ruff/FLY002": "## What it does\nChecks for `str.join` calls that can be replaced with f-strings.\n\n## Why is this bad?\nf-strings are more readable and generally preferred over `str.join` calls.\n\n## Example\n```python\n\" \".join((foo, bar))\n```\n\nUse instead:\n```python\nf\"{foo} {bar}\"\n```\n\n## Fix safety\nThe fix is always marked unsafe because the evaluation of the f-string\nexpressions will default to calling the `__format__` method of each\nobject, whereas `str.join` expects each object to be an instance of\n`str` and uses the corresponding string. Therefore it is possible for\nthe values of the resulting strings to differ, or for one expression\nto raise an exception while the other does not.\n\n## References\n- [Python documentation: f-strings](https://docs.python.org/3/reference/lexical_analysis.html#f-strings)\n",
|
|
469
|
+
"ruff/I001": "## What it does\nDe-duplicates, groups, and sorts imports based on the provided `isort` settings.\n\n## Why is this bad?\nConsistency is good. Use a common convention for imports to make your code\nmore readable and idiomatic.\n\n## Example\n```python\nimport pandas\nimport numpy as np\n```\n\nUse instead:\n```python\nimport numpy as np\nimport pandas\n```\n\n",
|
|
470
|
+
"ruff/I002": "## What it does\nAdds any required imports, as specified by the user, to the top of the\nfile.\n\n## Why is this bad?\nIn some projects, certain imports are required to be present in all\nfiles. For example, some projects assume that\n`from __future__ import annotations` is enabled,\nand thus require that import to be\npresent in all files. Omitting a \"required\" import (as specified by\nthe user) can cause errors or unexpected behavior.\n\n## Example\n```python\nimport typing\n```\n\nUse instead:\n```python\nfrom __future__ import annotations\n\nimport typing\n```\n\n## Options\n- `lint.isort.required-imports`\n",
|
|
471
|
+
"ruff/C901": "## What it does\nChecks for functions with a high `McCabe` complexity.\n\n## Why is this bad?\nThe `McCabe` complexity of a function is a measure of the complexity of\nthe control flow graph of the function. It is calculated by adding\none to the number of decision points in the function. A decision\npoint is a place in the code where the program has a choice of two\nor more paths to follow.\n\nFunctions with a high complexity are hard to understand and maintain.\n\n## Example\n```python\ndef normalize_status(status):\n if status == \"new\":\n return \"queued\"\n if status == \"queued\":\n return \"running\"\n if status == \"running\":\n return \"done\"\n if status == \"failed\":\n return \"retry\"\n if status == \"cancelled\":\n return \"closed\"\n return \"unknown\"\n```\n\nUse instead:\n\n```python\nSTATUS_TRANSITIONS = {\n \"new\": \"queued\",\n \"queued\": \"running\",\n \"running\": \"done\",\n \"failed\": \"retry\",\n \"cancelled\": \"closed\",\n}\n\n\ndef normalize_status(status):\n return STATUS_TRANSITIONS.get(status, \"unknown\")\n```\n\nNote that this example assumes a `lint.mccabe.max-complexity` of 5 or less to trigger a\ndiagnostic because the initial code only has a complexity of 6.\n\n## Options\n- `lint.mccabe.max-complexity`\n",
|
|
472
|
+
"ruff/NPY001": "## What it does\nChecks for deprecated NumPy type aliases.\n\n## Why is this bad?\nNumPy's `np.int` has long been an alias of the builtin `int`; the same\nis true of `np.float` and others. These aliases exist primarily\nfor historic reasons, and have been a cause of frequent confusion\nfor newcomers.\n\nThese aliases were deprecated in 1.20, and removed in 1.24.\nNote, however, that `np.bool` and `np.long` were reintroduced in 2.0 with\ndifferent semantics, and are thus omitted from this rule.\n\n## Example\n```python\nimport numpy as np\n\nnp.int\n```\n\nUse instead:\n```python\nint\n```\n",
|
|
473
|
+
"ruff/NPY002": "## What it does\nChecks for the use of legacy `np.random` function calls.\n\n## Why is this bad?\nAccording to the NumPy documentation's [Legacy Random Generation]:\n\n> The `RandomState` provides access to legacy generators... This class\n> should only be used if it is essential to have randoms that are\n> identical to what would have been produced by previous versions of\n> NumPy.\n\nThe members exposed directly on the `random` module are convenience\nfunctions that alias to methods on a global singleton `RandomState`\ninstance. NumPy recommends using a dedicated `Generator` instance\nrather than the random variate generation methods exposed directly on\nthe `random` module, as the new `Generator` is both faster and has\nbetter statistical properties.\n\nSee the documentation on [Random Sampling] and [NEP 19] for further\ndetails.\n\n## Example\n```python\nimport numpy as np\n\nnp.random.seed(1337)\nnp.random.normal()\n```\n\nUse instead:\n```python\nrng = np.random.default_rng(1337)\nrng.normal()\n```\n\n[Legacy Random Generation]: https://numpy.org/doc/stable/reference/random/legacy.html#legacy\n[Random Sampling]: https://numpy.org/doc/stable/reference/random/index.html#random-quick-start\n[NEP 19]: https://numpy.org/neps/nep-0019-rng-policy.html\n",
|
|
474
|
+
"ruff/NPY003": "## What it does\nChecks for uses of deprecated NumPy functions.\n\n## Why is this bad?\nWhen NumPy functions are deprecated, they are usually replaced with\nnewer, more efficient versions, or with functions that are more\nconsistent with the rest of the NumPy API.\n\nPrefer newer APIs over deprecated ones.\n\n## Example\n```python\nimport numpy as np\n\nnp.alltrue([True, False])\n```\n\nUse instead:\n```python\nimport numpy as np\n\nnp.all([True, False])\n```\n",
|
|
475
|
+
"ruff/NPY201": "## What it does\nChecks for uses of NumPy functions and constants that were removed from\nthe main namespace in NumPy 2.0.\n\n## Why is this bad?\nNumPy 2.0 includes an overhaul of NumPy's Python API, intended to remove\nredundant aliases and routines, and establish unambiguous mechanisms for\naccessing constants, dtypes, and functions.\n\nAs part of this overhaul, a variety of deprecated NumPy functions and\nconstants were removed from the main namespace.\n\nThe majority of these functions and constants can be automatically replaced\nby other members of the NumPy API or by equivalents from the Python\nstandard library. With the exception of renaming `numpy.byte_bounds` to\n`numpy.lib.array_utils.byte_bounds`, all such replacements are backwards\ncompatible with earlier versions of NumPy.\n\nThis rule flags all uses of removed members, along with automatic fixes for\nany backwards-compatible replacements.\n\n## Example\n```python\nimport numpy as np\n\narr1 = [np.Infinity, np.NaN, np.nan, np.PINF, np.inf]\narr2 = [np.float_(1.5), np.float64(5.1)]\nnp.round_(arr2)\n```\n\nUse instead:\n```python\nimport numpy as np\n\narr1 = [np.inf, np.nan, np.nan, np.inf, np.inf]\narr2 = [np.float64(1.5), np.float64(5.1)]\nnp.round(arr2)\n```\n",
|
|
476
|
+
"ruff/N801": "## What it does\nChecks for class names that do not follow the `CamelCase` convention.\n\n## Why is this bad?\n[PEP 8] recommends the use of the `CapWords` (or `CamelCase`) convention\nfor class names:\n\n> Class names should normally use the `CapWords` convention.\n>\n> The naming convention for functions may be used instead in cases where the interface is\n> documented and used primarily as a callable.\n>\n> Note that there is a separate convention for builtin names: most builtin names are single\n> words (or two words run together), with the `CapWords` convention used only for exception\n> names and builtin constants.\n\n## Example\n```python\nclass my_class:\n pass\n```\n\nUse instead:\n```python\nclass MyClass:\n pass\n```\n\n## Options\n- `lint.pep8-naming.ignore-names`\n- `lint.pep8-naming.extend-ignore-names`\n\n[PEP 8]: https://peps.python.org/pep-0008/#class-names\n",
|
|
477
|
+
"ruff/N802": "## What it does\nChecks for functions names that do not follow the `snake_case` naming\nconvention.\n\n## Why is this bad?\n[PEP 8] recommends that function names follow `snake_case`:\n\n> Function names should be lowercase, with words separated by underscores as necessary to\n> improve readability. mixedCase is allowed only in contexts where that\u2019s already the\n> prevailing style (e.g. threading.py), to retain backwards compatibility.\n\nNames can be excluded from this rule using the [`lint.pep8-naming.ignore-names`]\nor [`lint.pep8-naming.extend-ignore-names`] configuration options. For example,\nto ignore all functions starting with `test_` from this rule, set the\n[`lint.pep8-naming.extend-ignore-names`] option to `[\"test_*\"]`.\n\nThis rule exempts methods decorated with [`@typing.override`][override].\nExplicitly decorating a method with `@override` signals to Ruff that the method is intended\nto override a superclass method, and that a type checker will enforce that it does so. Ruff\ntherefore knows that it should not enforce naming conventions on such methods.\n\n## Example\n```python\ndef myFunction():\n pass\n```\n\nUse instead:\n```python\ndef my_function():\n pass\n```\n\n## Options\n- `lint.pep8-naming.ignore-names`\n- `lint.pep8-naming.extend-ignore-names`\n\n[PEP 8]: https://peps.python.org/pep-0008/#function-and-variable-names\n[override]: https://docs.python.org/3/library/typing.html#typing.override\n",
|
|
478
|
+
"ruff/N803": "## What it does\nChecks for argument names that do not follow the `snake_case` convention.\n\n## Why is this bad?\n[PEP 8] recommends that function names should be lower case and separated\nby underscores (also known as `snake_case`).\n\n> Function names should be lowercase, with words separated by underscores\n> as necessary to improve readability.\n>\n> Variable names follow the same convention as function names.\n>\n> mixedCase is allowed only in contexts where that\u2019s already the\n> prevailing style (e.g. threading.py), to retain backwards compatibility.\n\nMethods decorated with [`@typing.override`][override] are ignored.\n\n## Example\n```python\ndef my_function(A, myArg):\n pass\n```\n\nUse instead:\n```python\ndef my_function(a, my_arg):\n pass\n```\n\n## Options\n- `lint.pep8-naming.ignore-names`\n- `lint.pep8-naming.extend-ignore-names`\n\n[PEP 8]: https://peps.python.org/pep-0008/#function-and-method-arguments\n[preview]: https://docs.astral.sh/ruff/preview/\n\n[override]: https://docs.python.org/3/library/typing.html#typing.override\n",
|
|
479
|
+
"ruff/N804": "## What it does\nChecks for class methods that use a name other than `cls` for their\nfirst argument.\n\nThe method `__new__` is exempted from this\ncheck and the corresponding violation is caught by\n[`bad-staticmethod-argument`][PLW0211].\n\n## Why is this bad?\n[PEP 8] recommends the use of `cls` as the first argument for all class\nmethods:\n\n> Always use `cls` for the first argument to class methods.\n>\n> If a function argument\u2019s name clashes with a reserved keyword, it is generally better to\n> append a single trailing underscore rather than use an abbreviation or spelling corruption.\n> Thus `class_` is better than `clss`. (Perhaps better is to avoid such clashes by using a synonym.)\n\nNames can be excluded from this rule using the [`lint.pep8-naming.ignore-names`]\nor [`lint.pep8-naming.extend-ignore-names`] configuration options. For example,\nto allow the use of `klass` as the first argument to class methods, set\nthe [`lint.pep8-naming.extend-ignore-names`] option to `[\"klass\"]`.\n\n## Example\n\n```python\nclass Example:\n @classmethod\n def function(self, data): ...\n```\n\nUse instead:\n\n```python\nclass Example:\n @classmethod\n def function(cls, data): ...\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as renaming a method parameter\ncan change the behavior of the program.\n\n## Options\n- `lint.pep8-naming.classmethod-decorators`\n- `lint.pep8-naming.staticmethod-decorators`\n- `lint.pep8-naming.ignore-names`\n- `lint.pep8-naming.extend-ignore-names`\n\n[PEP 8]: https://peps.python.org/pep-0008/#function-and-method-arguments\n[PLW0211]: https://docs.astral.sh/ruff/rules/bad-staticmethod-argument/\n",
|
|
480
|
+
"ruff/N805": "## What it does\nChecks for instance methods that use a name other than `self` for their\nfirst argument.\n\n## Why is this bad?\n[PEP 8] recommends the use of `self` as first argument for all instance\nmethods:\n\n> Always use self for the first argument to instance methods.\n>\n> If a function argument\u2019s name clashes with a reserved keyword, it is generally better to\n> append a single trailing underscore rather than use an abbreviation or spelling corruption.\n> Thus `class_` is better than `clss`. (Perhaps better is to avoid such clashes by using a synonym.)\n\nNames can be excluded from this rule using the [`lint.pep8-naming.ignore-names`]\nor [`lint.pep8-naming.extend-ignore-names`] configuration options. For example,\nto allow the use of `this` as the first argument to instance methods, set\nthe [`lint.pep8-naming.extend-ignore-names`] option to `[\"this\"]`.\n\n## Example\n\n```python\nclass Example:\n def function(cls, data): ...\n```\n\nUse instead:\n\n```python\nclass Example:\n def function(self, data): ...\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as renaming a method parameter\ncan change the behavior of the program.\n\n## Options\n- `lint.pep8-naming.classmethod-decorators`\n- `lint.pep8-naming.staticmethod-decorators`\n- `lint.pep8-naming.ignore-names`\n- `lint.pep8-naming.extend-ignore-names`\n\n[PEP 8]: https://peps.python.org/pep-0008/#function-and-method-arguments\n",
|
|
481
|
+
"ruff/N806": "## What it does\nChecks for the use of non-lowercase variable names in functions.\n\n## Why is this bad?\n[PEP 8] recommends that all function variables use lowercase names:\n\n> Function names should be lowercase, with words separated by underscores as necessary to\n> improve readability. Variable names follow the same convention as function names. mixedCase\n> is allowed only in contexts where that's already the prevailing style (e.g. threading.py),\n> to retain backwards compatibility.\n\n## Example\n```python\ndef my_function(a):\n B = a + 3\n return B\n```\n\nUse instead:\n```python\ndef my_function(a):\n b = a + 3\n return b\n```\n\n## Options\n- `lint.pep8-naming.ignore-names`\n- `lint.pep8-naming.extend-ignore-names`\n\n[PEP 8]: https://peps.python.org/pep-0008/#function-and-variable-names\n",
|
|
482
|
+
"ruff/N807": "## What it does\nChecks for functions with \"dunder\" names (that is, names with two\nleading and trailing underscores) that are not documented.\n\n## Why is this bad?\n[PEP 8] recommends that only documented \"dunder\" methods are used:\n\n> ...\"magic\" objects or attributes that live in user-controlled\n> namespaces. E.g. `__init__`, `__import__` or `__file__`. Never invent\n> such names; only use them as documented.\n\n## Example\n```python\ndef __my_function__():\n pass\n```\n\nUse instead:\n```python\ndef my_function():\n pass\n```\n\n## Options\n- `lint.pep8-naming.ignore-names`\n- `lint.pep8-naming.extend-ignore-names`\n\n[PEP 8]: https://peps.python.org/pep-0008/\n",
|
|
483
|
+
"ruff/N811": "## What it does\nChecks for constant imports that are aliased to non-constant-style\nnames.\n\n## Why is this bad?\n[PEP 8] recommends naming conventions for classes, functions,\nconstants, and more. The use of inconsistent naming styles between\nimport and alias names may lead readers to expect an import to be of\nanother type (e.g., confuse a Python class with a constant).\n\nImport aliases should thus follow the same naming style as the member\nbeing imported.\n\n## Example\n```python\nfrom example import CONSTANT_VALUE as ConstantValue\n```\n\nUse instead:\n```python\nfrom example import CONSTANT_VALUE\n```\n\n## Note\nIdentifiers consisting of a single uppercase character are ambiguous under\nthe rules of [PEP 8], which specifies `CamelCase` for classes and\n`ALL_CAPS_SNAKE_CASE` for constants. Without a second character, it is not\npossible to reliably guess whether the identifier is intended to be part\nof a `CamelCase` string for a class or an `ALL_CAPS_SNAKE_CASE` string for\na constant, since both conventions will produce the same output when given\na single input character. Therefore, this lint rule does not apply to cases\nwhere the imported identifier consists of a single uppercase character.\n\nA common example of a single uppercase character being used for a class\nname can be found in Django's `django.db.models.Q` class.\n\n## Options\n- `lint.pep8-naming.ignore-names`\n- `lint.pep8-naming.extend-ignore-names`\n\n[PEP 8]: https://peps.python.org/pep-0008/\n",
|
|
484
|
+
"ruff/N812": "## What it does\nChecks for lowercase imports that are aliased to non-lowercase names.\n\n## Why is this bad?\n[PEP 8] recommends naming conventions for classes, functions,\nconstants, and more. The use of inconsistent naming styles between\nimport and alias names may lead readers to expect an import to be of\nanother type (e.g., confuse a Python class with a constant).\n\nImport aliases should thus follow the same naming style as the member\nbeing imported.\n\n## Example\n```python\nfrom example import myclassname as MyClassName\n```\n\nUse instead:\n```python\nfrom example import myclassname\n```\n\n## Options\n- `lint.pep8-naming.ignore-names`\n- `lint.pep8-naming.extend-ignore-names`\n\n[PEP 8]: https://peps.python.org/pep-0008/\n",
|
|
485
|
+
"ruff/N813": "## What it does\nChecks for `CamelCase` imports that are aliased to lowercase names.\n\n## Why is this bad?\n[PEP 8] recommends naming conventions for classes, functions,\nconstants, and more. The use of inconsistent naming styles between\nimport and alias names may lead readers to expect an import to be of\nanother type (e.g., confuse a Python class with a constant).\n\nImport aliases should thus follow the same naming style as the member\nbeing imported.\n\n## Example\n```python\nfrom example import MyClassName as myclassname\n```\n\nUse instead:\n```python\nfrom example import MyClassName\n```\n\n## Options\n- `lint.pep8-naming.ignore-names`\n- `lint.pep8-naming.extend-ignore-names`\n\n[PEP 8]: https://peps.python.org/pep-0008/\n",
|
|
486
|
+
"ruff/N814": "## What it does\nChecks for `CamelCase` imports that are aliased to constant-style names.\n\n## Why is this bad?\n[PEP 8] recommends naming conventions for classes, functions,\nconstants, and more. The use of inconsistent naming styles between\nimport and alias names may lead readers to expect an import to be of\nanother type (e.g., confuse a Python class with a constant).\n\nImport aliases should thus follow the same naming style as the member\nbeing imported.\n\n## Example\n```python\nfrom example import MyClassName as MY_CLASS_NAME\n```\n\nUse instead:\n```python\nfrom example import MyClassName\n```\n\n## Note\nIdentifiers consisting of a single uppercase character are ambiguous under\nthe rules of [PEP 8], which specifies `CamelCase` for classes and\n`ALL_CAPS_SNAKE_CASE` for constants. Without a second character, it is not\npossible to reliably guess whether the identifier is intended to be part\nof a `CamelCase` string for a class or an `ALL_CAPS_SNAKE_CASE` string for\na constant, since both conventions will produce the same output when given\na single input character. Therefore, this lint rule does not apply to cases\nwhere the alias for the imported identifier consists of a single uppercase\ncharacter.\n\nA common example of a single uppercase character being used for a class\nname can be found in Django's `django.db.models.Q` class.\n\n## Options\n- `lint.pep8-naming.ignore-names`\n- `lint.pep8-naming.extend-ignore-names`\n\n[PEP 8]: https://peps.python.org/pep-0008/\n",
|
|
487
|
+
"ruff/N815": "## What it does\nChecks for class variable names that follow the `mixedCase` convention.\n\n## Why is this bad?\n[PEP 8] recommends that variable names should be lower case and separated\nby underscores (also known as `snake_case`).\n\n> Function names should be lowercase, with words separated by underscores\n> as necessary to improve readability.\n>\n> Variable names follow the same convention as function names.\n>\n> mixedCase is allowed only in contexts where that\u2019s already the\n> prevailing style (e.g. threading.py), to retain backwards compatibility.\n\n## Example\n```python\nclass MyClass:\n myVariable = \"hello\"\n another_variable = \"world\"\n```\n\nUse instead:\n```python\nclass MyClass:\n my_variable = \"hello\"\n another_variable = \"world\"\n```\n\n## Options\n- `lint.pep8-naming.ignore-names`\n- `lint.pep8-naming.extend-ignore-names`\n\n[PEP 8]: https://peps.python.org/pep-0008/#function-and-method-arguments\n",
|
|
488
|
+
"ruff/N816": "## What it does\nChecks for global variable names that follow the `mixedCase` convention.\n\n## Why is this bad?\n[PEP 8] recommends that global variable names should be lower case and\nseparated by underscores (also known as `snake_case`).\n\n> ### Global Variable Names\n> (Let\u2019s hope that these variables are meant for use inside one module\n> only.) The conventions are about the same as those for functions.\n>\n> Modules that are designed for use via `from M import *` should use the\n> `__all__` mechanism to prevent exporting globals, or use the older\n> convention of prefixing such globals with an underscore (which you might\n> want to do to indicate these globals are \u201cmodule non-public\u201d).\n>\n> ### Function and Variable Names\n> Function names should be lowercase, with words separated by underscores\n> as necessary to improve readability.\n>\n> Variable names follow the same convention as function names.\n>\n> mixedCase is allowed only in contexts where that\u2019s already the prevailing\n> style (e.g. threading.py), to retain backwards compatibility.\n\n## Example\n```python\nmyVariable = \"hello\"\nanother_variable = \"world\"\nyet_anotherVariable = \"foo\"\n```\n\nUse instead:\n```python\nmy_variable = \"hello\"\nanother_variable = \"world\"\nyet_another_variable = \"foo\"\n```\n\n## Options\n- `lint.pep8-naming.ignore-names`\n- `lint.pep8-naming.extend-ignore-names`\n\n[PEP 8]: https://peps.python.org/pep-0008/#global-variable-names\n",
|
|
489
|
+
"ruff/N817": "## What it does\nChecks for `CamelCase` imports that are aliased as acronyms.\n\n## Why is this bad?\n[PEP 8] recommends naming conventions for classes, functions,\nconstants, and more. The use of inconsistent naming styles between\nimport and alias names may lead readers to expect an import to be of\nanother type (e.g., confuse a Python class with a constant).\n\nImport aliases should thus follow the same naming style as the member\nbeing imported.\n\nNote that this rule is distinct from `camelcase-imported-as-constant`\nto accommodate selective enforcement.\n\nAlso note that import aliases following an import convention according to the\n[`lint.flake8-import-conventions.aliases`] option are allowed.\n\n## Example\n```python\nfrom example import MyClassName as MCN\n```\n\nUse instead:\n```python\nfrom example import MyClassName\n```\n\n## Options\n- `lint.flake8-import-conventions.aliases`\n- `lint.pep8-naming.ignore-names`\n- `lint.pep8-naming.extend-ignore-names`\n\n[PEP 8]: https://peps.python.org/pep-0008/\n",
|
|
490
|
+
"ruff/N818": "## What it does\nChecks for custom exception definitions that omit the `Error` suffix.\n\n## Why is this bad?\nThe `Error` suffix is recommended by [PEP 8]:\n\n> Because exceptions should be classes, the class naming convention\n> applies here. However, you should use the suffix `\"Error\"` on your\n> exception names (if the exception actually is an error).\n\n## Example\n\n```python\nclass Validation(Exception): ...\n```\n\nUse instead:\n\n```python\nclass ValidationError(Exception): ...\n```\n\n## Options\n- `lint.pep8-naming.ignore-names`\n- `lint.pep8-naming.extend-ignore-names`\n\n[PEP 8]: https://peps.python.org/pep-0008/#exception-names\n",
|
|
491
|
+
"ruff/N999": "## What it does\nChecks for module names that do not follow the `snake_case` naming\nconvention or are otherwise invalid.\n\n## Why is this bad?\n[PEP 8] recommends the use of the `snake_case` naming convention for\nmodule names:\n\n> Modules should have short, all-lowercase names. Underscores can be used in the\n> module name if it improves readability. Python packages should also have short,\n> all-lowercase names, although the use of underscores is discouraged.\n>\n> When an extension module written in C or C++ has an accompanying Python module that\n> provides a higher level (e.g. more object-oriented) interface, the C/C++ module has\n> a leading underscore (e.g. `_socket`).\n\nFurther, in order for Python modules to be importable, they must be valid\nidentifiers. As such, they cannot start with a digit, or collide with hard\nkeywords, like `import` or `class`.\n\n## Example\n- Instead of `example-module-name` or `example module name`, use `example_module_name`.\n- Instead of `ExampleModule`, use `example_module`.\n\n## Options\n\n- `lint.pep8-naming.ignore-names`\n\n[PEP 8]: https://peps.python.org/pep-0008/#package-and-module-names\n",
|
|
492
|
+
"ruff/PD002": "## What it does\nChecks for `inplace=True` usages in `pandas` function and method\ncalls.\n\n## Why is this bad?\nUsing `inplace=True` encourages mutation rather than immutable data,\nwhich is harder to reason about and may cause bugs. It also removes the\nability to use the method chaining style for `pandas` operations.\n\nFurther, in many cases, `inplace=True` does not provide a performance\nbenefit, as `pandas` will often copy `DataFrames` in the background.\n\n## Example\n```python\nimport pandas as pd\n\nstudents = pd.read_csv(\"students.csv\")\nstudents.sort_values(\"name\", inplace=True)\n```\n\nUse instead:\n```python\nimport pandas as pd\n\nstudents = pd.read_csv(\"students.csv\").sort_values(\"name\")\n```\n\n## References\n- [_Why You Should Probably Never Use pandas `inplace=True`_](https://towardsdatascience.com/why-you-should-probably-never-use-pandas-inplace-true-9f9f211849e4)\n",
|
|
493
|
+
"ruff/PD003": "## What it does\nChecks for uses of `.isnull` on Pandas objects.\n\n## Why is this bad?\nIn the Pandas API, `.isna` and `.isnull` are equivalent. For consistency,\nprefer `.isna` over `.isnull`.\n\nAs a name, `.isna` more accurately reflects the behavior of the method,\nsince these methods check for `NaN` and `NaT` values in addition to `None`\nvalues.\n\n## Example\n```python\nimport pandas as pd\n\nanimals_df = pd.read_csv(\"animals.csv\")\npd.isnull(animals_df)\n```\n\nUse instead:\n```python\nimport pandas as pd\n\nanimals_df = pd.read_csv(\"animals.csv\")\npd.isna(animals_df)\n```\n\n## References\n- [Pandas documentation: `isnull`](https://pandas.pydata.org/docs/reference/api/pandas.isnull.html#pandas.isnull)\n- [Pandas documentation: `isna`](https://pandas.pydata.org/docs/reference/api/pandas.isna.html#pandas.isna)\n",
|
|
494
|
+
"ruff/PD004": "## What it does\nChecks for uses of `.notnull` on Pandas objects.\n\n## Why is this bad?\nIn the Pandas API, `.notna` and `.notnull` are equivalent. For consistency,\nprefer `.notna` over `.notnull`.\n\nAs a name, `.notna` more accurately reflects the behavior of the method,\nsince these methods check for `NaN` and `NaT` values in addition to `None`\nvalues.\n\n## Example\n```python\nimport pandas as pd\n\nanimals_df = pd.read_csv(\"animals.csv\")\npd.notnull(animals_df)\n```\n\nUse instead:\n```python\nimport pandas as pd\n\nanimals_df = pd.read_csv(\"animals.csv\")\npd.notna(animals_df)\n```\n\n## References\n- [Pandas documentation: `notnull`](https://pandas.pydata.org/docs/reference/api/pandas.notnull.html#pandas.notnull)\n- [Pandas documentation: `notna`](https://pandas.pydata.org/docs/reference/api/pandas.notna.html#pandas.notna)\n",
|
|
495
|
+
"ruff/PD007": "## What it does\nChecks for uses of `.ix` on Pandas objects.\n\n## Why is this bad?\nThe `.ix` method is deprecated as its behavior is ambiguous. Specifically,\nit's often unclear whether `.ix` is indexing by label or by ordinal position.\n\nInstead, prefer the `.loc` method for label-based indexing, and `.iloc` for\nordinal indexing.\n\n## Example\n```python\nimport pandas as pd\n\nstudents_df = pd.read_csv(\"students.csv\")\nstudents_df.ix[0] # 0th row or row with label 0?\n```\n\nUse instead:\n```python\nimport pandas as pd\n\nstudents_df = pd.read_csv(\"students.csv\")\nstudents_df.iloc[0] # 0th row.\n```\n\n## References\n- [Pandas release notes: Deprecate `.ix`](https://pandas.pydata.org/pandas-docs/version/0.20/whatsnew.html#deprecate-ix)\n- [Pandas documentation: `loc`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html)\n- [Pandas documentation: `iloc`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iloc.html)\n",
|
|
496
|
+
"ruff/PD008": "## What it does\nChecks for uses of `.at` on Pandas objects.\n\n## Why is this bad?\nThe `.at` method selects a single value from a `DataFrame` or Series based on\na label index, and is slightly faster than using `.loc`. However, `.loc` is\nmore idiomatic and versatile, as it can be used to select multiple values at\nonce.\n\nIf performance is an important consideration, convert the object to a NumPy\narray, which will provide a much greater performance boost than using `.at`\nover `.loc`.\n\n## Example\n```python\nimport pandas as pd\n\nstudents_df = pd.read_csv(\"students.csv\")\nstudents_df.at[\"Maria\"]\n```\n\nUse instead:\n```python\nimport pandas as pd\n\nstudents_df = pd.read_csv(\"students.csv\")\nstudents_df.loc[\"Maria\"]\n```\n\n## References\n- [Pandas documentation: `loc`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html)\n- [Pandas documentation: `at`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.at.html)\n",
|
|
497
|
+
"ruff/PD009": "## What it does\nChecks for uses of `.iat` on Pandas objects.\n\n## Why is this bad?\nThe `.iat` method selects a single value from a `DataFrame` or Series based\non an ordinal index, and is slightly faster than using `.iloc`. However,\n`.iloc` is more idiomatic and versatile, as it can be used to select\nmultiple values at once.\n\nIf performance is an important consideration, convert the object to a NumPy\narray, which will provide a much greater performance boost than using `.iat`\nover `.iloc`.\n\n## Example\n```python\nimport pandas as pd\n\nstudents_df = pd.read_csv(\"students.csv\")\nstudents_df.iat[0]\n```\n\nUse instead:\n```python\nimport pandas as pd\n\nstudents_df = pd.read_csv(\"students.csv\")\nstudents_df.iloc[0]\n```\n\nOr, using NumPy:\n```python\nimport numpy as np\nimport pandas as pd\n\nstudents_df = pd.read_csv(\"students.csv\")\nstudents_df.to_numpy()[0]\n```\n\n## References\n- [Pandas documentation: `iloc`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iloc.html)\n- [Pandas documentation: `iat`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iat.html)\n",
|
|
498
|
+
"ruff/PD010": "## What it does\nChecks for uses of `.pivot` or `.unstack` on Pandas objects.\n\n## Why is this bad?\nPrefer `.pivot_table` to `.pivot` or `.unstack`. `.pivot_table` is more general\nand can be used to implement the same behavior as `.pivot` and `.unstack`.\n\n## Example\n```python\nimport pandas as pd\n\ndf = pd.read_csv(\"cities.csv\")\ndf.pivot(index=\"city\", columns=\"year\", values=\"population\")\n```\n\nUse instead:\n```python\nimport pandas as pd\n\ndf = pd.read_csv(\"cities.csv\")\ndf.pivot_table(index=\"city\", columns=\"year\", values=\"population\")\n```\n\n## References\n- [Pandas documentation: Reshaping and pivot tables](https://pandas.pydata.org/docs/user_guide/reshaping.html)\n- [Pandas documentation: `pivot_table`](https://pandas.pydata.org/docs/reference/api/pandas.pivot_table.html#pandas.pivot_table)\n",
|
|
499
|
+
"ruff/PD011": "## What it does\nChecks for uses of `.values` on Pandas Series and Index objects.\n\n## Why is this bad?\nThe `.values` attribute is ambiguous as its return type is unclear. As\nsuch, it is no longer recommended by the Pandas documentation.\n\nInstead, use `.to_numpy()` to return a NumPy array, or `.array` to return a\nPandas `ExtensionArray`.\n\n## Example\n```python\nimport pandas as pd\n\nanimals = pd.read_csv(\"animals.csv\").values # Ambiguous.\n```\n\nUse instead:\n```python\nimport pandas as pd\n\nanimals = pd.read_csv(\"animals.csv\").to_numpy() # Explicit.\n```\n\n## References\n- [Pandas documentation: Accessing the values in a Series or Index](https://pandas.pydata.org/pandas-docs/stable/whatsnew/v0.24.0.html#accessing-the-values-in-a-series-or-index)\n",
|
|
500
|
+
"ruff/PD012": "## What it does\nChecks for uses of `pd.read_table` to read CSV files.\n\n## Why is this bad?\nIn the Pandas API, `pd.read_csv` and `pd.read_table` are equivalent apart\nfrom their default separator: `pd.read_csv` defaults to a comma (`,`),\nwhile `pd.read_table` defaults to a tab (`\\t`) as the default separator.\n\nPrefer `pd.read_csv` over `pd.read_table` when reading comma-separated\ndata (like CSV files), as it is more idiomatic.\n\n## Example\n```python\nimport pandas as pd\n\ncities_df = pd.read_table(\"cities.csv\", sep=\",\")\n```\n\nUse instead:\n```python\nimport pandas as pd\n\ncities_df = pd.read_csv(\"cities.csv\")\n```\n\n## References\n- [Pandas documentation: `read_csv`](https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html#pandas.read_csv)\n- [Pandas documentation: `read_table`](https://pandas.pydata.org/docs/reference/api/pandas.read_table.html#pandas.read_table)\n",
|
|
501
|
+
"ruff/PD013": "## What it does\nChecks for uses of `.stack` on Pandas objects.\n\n## Why is this bad?\nPrefer `.melt` to `.stack`, which has the same functionality but with\nsupport for direct column renaming and no dependence on `MultiIndex`.\n\n## Example\n```python\nimport pandas as pd\n\ncities_df = pd.read_csv(\"cities.csv\")\ncities_df.set_index(\"city\").stack()\n```\n\nUse instead:\n```python\nimport pandas as pd\n\ncities_df = pd.read_csv(\"cities.csv\")\ncities_df.melt(id_vars=\"city\")\n```\n\n## References\n- [Pandas documentation: `melt`](https://pandas.pydata.org/docs/reference/api/pandas.melt.html)\n- [Pandas documentation: `stack`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.stack.html)\n",
|
|
502
|
+
"ruff/PD015": "## What it does\nChecks for uses of `pd.merge` on Pandas objects.\n\n## Why is this bad?\nIn Pandas, the `.merge` method (exposed on, e.g., `DataFrame` objects) and\nthe `pd.merge` function (exposed on the Pandas module) are equivalent.\n\nFor consistency, prefer calling `.merge` on an object over calling\n`pd.merge` on the Pandas module, as the former is more idiomatic.\n\nFurther, `pd.merge` is not a method, but a function, which prohibits it\nfrom being used in method chains, a common pattern in Pandas code.\n\n## Example\n```python\nimport pandas as pd\n\ncats_df = pd.read_csv(\"cats.csv\")\ndogs_df = pd.read_csv(\"dogs.csv\")\nrabbits_df = pd.read_csv(\"rabbits.csv\")\npets_df = pd.merge(pd.merge(cats_df, dogs_df), rabbits_df) # Hard to read.\n```\n\nUse instead:\n```python\nimport pandas as pd\n\ncats_df = pd.read_csv(\"cats.csv\")\ndogs_df = pd.read_csv(\"dogs.csv\")\nrabbits_df = pd.read_csv(\"rabbits.csv\")\npets_df = cats_df.merge(dogs_df).merge(rabbits_df)\n```\n\n## References\n- [Pandas documentation: `merge`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html#pandas.DataFrame.merge)\n- [Pandas documentation: `pd.merge`](https://pandas.pydata.org/docs/reference/api/pandas.merge.html#pandas.merge)\n",
|
|
503
|
+
"ruff/PD101": "## What it does\nCheck for uses of `.nunique()` to check if a Pandas Series is constant\n(i.e., contains only one unique value).\n\n## Why is this bad?\n`.nunique()` is computationally inefficient for checking if a Series is\nconstant.\n\nConsider, for example, a Series of length `n` that consists of increasing\ninteger values (e.g., 1, 2, 3, 4). The `.nunique()` method will iterate\nover the entire Series to count the number of unique values. But in this\ncase, we can detect that the Series is non-constant after visiting the\nfirst two values, which are non-equal.\n\nIn general, `.nunique()` requires iterating over the entire Series, while a\nmore efficient approach allows short-circuiting the operation as soon as a\nnon-equal value is found.\n\nInstead of calling `.nunique()`, convert the Series to a NumPy array, and\ncheck if all values in the array are equal to the first observed value.\n\n## Example\n```python\nimport pandas as pd\n\ndata = pd.Series(range(1000))\nif data.nunique() <= 1:\n print(\"Series is constant\")\n```\n\nUse instead:\n```python\nimport pandas as pd\n\ndata = pd.Series(range(1000))\narray = data.to_numpy()\nif array.shape[0] == 0 or (array[0] == array).all():\n print(\"Series is constant\")\n```\n\n## References\n- [Pandas Cookbook: \"Constant Series\"](https://pandas.pydata.org/docs/user_guide/cookbook.html#constant-series)\n- [Pandas documentation: `nunique`](https://pandas.pydata.org/docs/reference/api/pandas.Series.nunique.html)\n",
|
|
504
|
+
"ruff/PD901": "## Removed\n\nThis rule has been removed as it's highly opinionated and overly strict in most cases.\n\n## What it does\nChecks for assignments to the variable `df`.\n\n## Why is this bad?\nAlthough `df` is a common variable name for a Pandas `DataFrame`, it's not a\ngreat variable name for production code, as it's non-descriptive and\nprone to name conflicts.\n\nInstead, use a more descriptive variable name.\n\n## Example\n```python\nimport pandas as pd\n\ndf = pd.read_csv(\"animals.csv\")\n```\n\nUse instead:\n```python\nimport pandas as pd\n\nanimals = pd.read_csv(\"animals.csv\")\n```\n",
|
|
505
|
+
"ruff/PERF101": "## What it does\nChecks for explicit casts to `list` on for-loop iterables.\n\n## Why is this bad?\nUsing a `list()` call to eagerly iterate over an already-iterable type\n(like a tuple, list, or set) is inefficient, as it forces Python to create\na new list unnecessarily.\n\nRemoving the `list()` call will not change the behavior of the code, but\nmay improve performance.\n\nNote that, as with all `perflint` rules, this is only intended as a\nmicro-optimization, and will have a negligible impact on performance in\nmost cases.\n\n## Example\n```python\nitems = (1, 2, 3)\nfor i in list(items):\n print(i)\n```\n\nUse instead:\n```python\nitems = (1, 2, 3)\nfor i in items:\n print(i)\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe if there's comments in the\n`list()` call, as comments may be removed.\n\nFor example, the fix would be marked as unsafe in the following case:\n```python\nitems = (1, 2, 3)\nfor i in list( # comment\n items\n):\n print(i)\n```\n",
|
|
506
|
+
"ruff/PERF102": "## What it does\nChecks for uses of `dict.items()` that discard either the key or the value\nwhen iterating over the dictionary.\n\n## Why is this bad?\nIf you only need the keys or values of a dictionary, you should use\n`dict.keys()` or `dict.values()` respectively, instead of `dict.items()`.\nThese specialized methods are more efficient than `dict.items()`, as they\navoid allocating tuples for every item in the dictionary. They also\ncommunicate the intent of the code more clearly.\n\nNote that, as with all `perflint` rules, this is only intended as a\nmicro-optimization, and will have a negligible impact on performance in\nmost cases.\n\n## Example\n```python\nobj = {\"a\": 1, \"b\": 2}\nfor key, value in obj.items():\n print(value)\n```\n\nUse instead:\n```python\nobj = {\"a\": 1, \"b\": 2}\nfor value in obj.values():\n print(value)\n```\n\n## Fix safety\nThe fix does not perform any type analysis and, as such, may suggest an\nincorrect fix if the object in question does not duck-type as a mapping\n(e.g., if it is missing a `.keys()` or `.values()` method, or if those\nmethods behave differently than they do on standard mapping types).\n",
|
|
507
|
+
"ruff/PERF203": "## What it does\nChecks for uses of except handling via `try`-`except` within `for` and\n`while` loops.\n\n## Why is this bad?\nException handling via `try`-`except` blocks incurs some performance\noverhead, regardless of whether an exception is raised.\n\nTo optimize your code, two techniques are possible:\n1. Refactor your code to put the entire loop into the `try`-`except` block,\n rather than wrapping each iteration in a separate `try`-`except` block.\n2. Use \"Look Before You Leap\" idioms that attempt to avoid exceptions\n being raised in the first place, avoiding the need to use `try`-`except`\n blocks in the first place.\n\nThis rule is only enforced for Python versions prior to 3.11, which\nintroduced \"zero-cost\" exception handling. However, note that even on\nPython 3.11 and newer, refactoring your code to avoid exception handling in\ntight loops can provide a significant speedup in some cases, as zero-cost\nexception handling is only zero-cost in the \"happy path\" where no exception\nis raised in the `try`-`except` block.\n\nAs with all `perflint` rules, this is only intended as a\nmicro-optimization. In many cases, it will have a negligible impact on\nperformance.\n\n## Example\n```python\nstring_numbers: list[str] = [\"1\", \"2\", \"three\", \"4\", \"5\"]\n\n# `try`/`except` that could be moved out of the loop:\nint_numbers: list[int] = []\nfor num in string_numbers:\n try:\n int_numbers.append(int(num))\n except ValueError as e:\n print(f\"Couldn't convert to integer: {e}\")\n break\n\n# `try`/`except` used when \"look before you leap\" idioms could be used:\nnumber_names: dict[int, str] = {1: \"one\", 3: \"three\", 4: \"four\"}\nfor number in range(5):\n try:\n name = number_names[number]\n except KeyError:\n continue\n else:\n print(f\"The name of {number} is {name}\")\n```\n\nUse instead:\n```python\nstring_numbers: list[str] = [\"1\", \"2\", \"three\", \"4\", \"5\"]\n\nint_numbers: list[int] = []\ntry:\n for num in string_numbers:\n int_numbers.append(int(num))\nexcept ValueError as e:\n print(f\"Couldn't convert to integer: {e}\")\n\nnumber_names: dict[int, str] = {1: \"one\", 3: \"three\", 4: \"four\"}\nfor number in range(5):\n name = number_names.get(number)\n if name is not None:\n print(f\"The name of {number} is {name}\")\n```\n\n## Options\n- `target-version`\n",
|
|
508
|
+
"ruff/PERF401": "## What it does\nChecks for `for` loops that can be replaced by a list comprehension.\n\n## Why is this bad?\nWhen creating a transformed list from an existing list using a for-loop,\nprefer a list comprehension. List comprehensions are more readable and\nmore performant.\n\nUsing the below as an example, the list comprehension is ~10% faster on\nPython 3.11, and ~25% faster on Python 3.10.\n\nNote that, as with all `perflint` rules, this is only intended as a\nmicro-optimization, and will have a negligible impact on performance in\nmost cases.\n\n## Example\n```python\noriginal = list(range(10000))\nfiltered = []\nfor i in original:\n if i % 2:\n filtered.append(i)\n```\n\nUse instead:\n```python\noriginal = list(range(10000))\nfiltered = [x for x in original if x % 2]\n```\n\nIf you're appending to an existing list, use the `extend` method instead:\n```python\noriginal = list(range(10000))\nfiltered.extend(x for x in original if x % 2)\n```\n",
|
|
509
|
+
"ruff/PERF402": "## What it does\nChecks for `for` loops that append every item of an iterable to a list,\nwhich can be replaced with a call to `list`.\n\n## Why is this bad?\nWhen populating a list from an iterable with a `for` loop, prefer `list`\ninstead. The `list` call is more readable and more performant. For an\nexisting list, you can also use `list.copy` instead of `list`.\n\nUsing the below as an example, the `list`-based copy is ~2x faster on\nPython 3.11.\n\nNote that, as with all `perflint` rules, this is only intended as a\nmicro-optimization, and will have a negligible impact on performance in\nmost cases.\n\n## Example\n```python\noriginal = list(range(10000))\nfiltered = []\nfor i in original:\n filtered.append(i)\n```\n\nUse instead:\n```python\noriginal = list(range(10000))\nfiltered = list(original)\n```\n",
|
|
510
|
+
"ruff/PERF403": "## What it does\nChecks for `for` loops that can be replaced by a dictionary comprehension.\n\n## Why is this bad?\nWhen creating or extending a dictionary in a for-loop, prefer a dictionary\ncomprehension. Comprehensions are more readable and more performant.\n\nFor example, when comparing `{x: x for x in list(range(1000))}` to the `for`\nloop version, the comprehension is ~10% faster on Python 3.11.\n\nNote that, as with all `perflint` rules, this is only intended as a\nmicro-optimization, and will have a negligible impact on performance in\nmost cases.\n\n## Example\n```python\npairs = ((\"a\", 1), (\"b\", 2))\nresult = {}\nfor x, y in pairs:\n if y % 2:\n result[x] = y\n```\n\nUse instead:\n```python\npairs = ((\"a\", 1), (\"b\", 2))\nresult = {x: y for x, y in pairs if y % 2}\n```\n\nIf you're appending to an existing dictionary, use the `update` method instead:\n```python\npairs = ((\"a\", 1), (\"b\", 2))\nresult.update({x: y for x, y in pairs if y % 2})\n```\n",
|
|
511
|
+
"ruff/E101": "## What it does\nChecks for mixed tabs and spaces in indentation.\n\n## Why is this bad?\nNever mix tabs and spaces.\n\nThe most popular way of indenting Python is with spaces only. The\nsecond-most popular way is with tabs only. Code indented with a\nmixture of tabs and spaces should be converted to using spaces\nexclusively.\n\n## Example\n```python\nif a == 0:\\n a = 1\\n\\tb = 1\n```\n\nUse instead:\n```python\nif a == 0:\\n a = 1\\n b = 1\n```\n",
|
|
512
|
+
"ruff/E111": "## What it does\nChecks for indentation with a non-multiple of 4 spaces.\n\n## Why is this bad?\nAccording to [PEP 8], 4 spaces per indentation level should be preferred.\n\n## Example\n```python\nif True:\n a = 1\n```\n\nUse instead:\n```python\nif True:\n a = 1\n```\n\n## Formatter compatibility\nWe recommend against using this rule alongside the [formatter]. The\nformatter enforces consistent indentation, making the rule redundant.\n\nThe rule is also incompatible with the [formatter] when using\n`indent-width` with a value other than `4`.\n\n## Options\n- `indent-width`\n\n[PEP 8]: https://peps.python.org/pep-0008/#indentation\n[formatter]:https://docs.astral.sh/ruff/formatter/\n",
|
|
513
|
+
"ruff/E112": "## What it does\nChecks for indented blocks that are lacking indentation.\n\n## Why is this bad?\nAll indented blocks should be indented; otherwise, they are not valid\nPython syntax.\n\n## Example\n```python\nfor item in items:\npass\n```\n\nUse instead:\n```python\nfor item in items:\n pass\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#indentation\n",
|
|
514
|
+
"ruff/E113": "## What it does\nChecks for unexpected indentation.\n\n## Why is this bad?\nIndentation outside of a code block is not valid Python syntax.\n\n## Example\n```python\na = 1\n b = 2\n```\n\nUse instead:\n```python\na = 1\nb = 2\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#indentation\n",
|
|
515
|
+
"ruff/E114": "## What it does\nChecks for indentation of comments with a non-multiple of 4 spaces.\n\n## Why is this bad?\nAccording to [PEP 8], 4 spaces per indentation level should be preferred.\n\n## Example\n```python\nif True:\n # a = 1\n ...\n```\n\nUse instead:\n```python\nif True:\n # a = 1\n ...\n```\n\n## Formatter compatibility\nWe recommend against using this rule alongside the [formatter]. The\nformatter enforces consistent indentation, making the rule redundant.\n\nThe rule is also incompatible with the [formatter] when using\n`indent-width` with a value other than `4`.\n\n## Options\n- `indent-width`\n\n[PEP 8]: https://peps.python.org/pep-0008/#indentation\n[formatter]:https://docs.astral.sh/ruff/formatter/\n",
|
|
516
|
+
"ruff/E115": "## What it does\nChecks for comments in a code blocks that are lacking indentation.\n\n## Why is this bad?\nComments within an indented block should themselves be indented, to\nindicate that they are part of the block.\n\n## Example\n```python\nfor item in items:\n# Hi\n pass\n```\n\nUse instead:\n```python\nfor item in items:\n # Hi\n pass\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#indentation\n",
|
|
517
|
+
"ruff/E116": "## What it does\nChecks for unexpected indentation of comment.\n\n## Why is this bad?\nComments should match the indentation of the containing code block.\n\n## Example\n```python\na = 1\n # b = 2\n```\n\nUse instead:\n```python\na = 1\n# b = 2\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#indentation\n",
|
|
518
|
+
"ruff/E117": "## What it does\nChecks for over-indented code.\n\n## Why is this bad?\nAccording to [PEP 8], 4 spaces per indentation level should be preferred. Increased\nindentation can lead to inconsistent formatting, which can hurt\nreadability.\n\n## Example\n```python\nfor item in items:\n pass\n```\n\nUse instead:\n```python\nfor item in items:\n pass\n```\n\n## Formatter compatibility\nWe recommend against using this rule alongside the [formatter]. The\nformatter enforces consistent indentation, making the rule redundant.\n\n[PEP 8]: https://peps.python.org/pep-0008/#indentation\n[formatter]:https://docs.astral.sh/ruff/formatter/\n",
|
|
519
|
+
"ruff/E201": "## What it does\nChecks for the use of extraneous whitespace after \"(\", \"[\" or \"{\".\n\n## Why is this bad?\n[PEP 8] recommends the omission of whitespace in the following cases:\n- \"Immediately inside parentheses, brackets or braces.\"\n- \"Immediately before a comma, semicolon, or colon.\"\n\n## Example\n```python\nspam( ham[1], {eggs: 2})\nspam(ham[ 1], {eggs: 2})\nspam(ham[1], { eggs: 2})\n```\n\nUse instead:\n```python\nspam(ham[1], {eggs: 2})\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#pet-peeves\n",
|
|
520
|
+
"ruff/E202": "## What it does\nChecks for the use of extraneous whitespace before \")\", \"]\" or \"}\".\n\n## Why is this bad?\n[PEP 8] recommends the omission of whitespace in the following cases:\n- \"Immediately inside parentheses, brackets or braces.\"\n- \"Immediately before a comma, semicolon, or colon.\"\n\n## Example\n```python\nspam(ham[1], {eggs: 2} )\nspam(ham[1 ], {eggs: 2})\nspam(ham[1], {eggs: 2 })\n```\n\nUse instead:\n```python\nspam(ham[1], {eggs: 2})\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#pet-peeves\n",
|
|
521
|
+
"ruff/E203": "## What it does\nChecks for the use of extraneous whitespace before \",\", \";\" or \":\".\n\n## Why is this bad?\n[PEP 8] recommends the omission of whitespace in the following cases:\n- \"Immediately inside parentheses, brackets or braces.\"\n- \"Immediately before a comma, semicolon, or colon.\"\n\n## Example\n```python\nif x == 4: print(x, y); x, y = y , x\n```\n\nUse instead:\n```python\nif x == 4: print(x, y); x, y = y, x\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#pet-peeves\n",
|
|
522
|
+
"ruff/E204": "## What it does\nChecks for trailing whitespace after a decorator's opening `@`.\n\n## Why is this bad?\nIncluding whitespace after the `@` symbol is not compliant with\n[PEP 8].\n\n## Example\n\n```python\n@ decorator\ndef func():\n pass\n```\n\nUse instead:\n```python\n@decorator\ndef func():\n pass\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#maximum-line-length\n",
|
|
523
|
+
"ruff/E211": "## What it does\nChecks for extraneous whitespace immediately preceding an open parenthesis\nor bracket.\n\n## Why is this bad?\nAccording to [PEP 8], open parentheses and brackets should not be preceded\nby any trailing whitespace.\n\n## Example\n```python\nspam (1)\n```\n\nUse instead:\n```python\nspam(1)\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#pet-peeves\n",
|
|
524
|
+
"ruff/E221": "## What it does\nChecks for extraneous whitespace before an operator.\n\n## Why is this bad?\nAccording to [PEP 8], operators should be surrounded by at most a single space on either\nside.\n\n## Example\n```python\na = 4 + 5\n```\n\nUse instead:\n```python\na = 4 + 5\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#whitespace-in-expressions-and-statements\n",
|
|
525
|
+
"ruff/E222": "## What it does\nChecks for extraneous whitespace after an operator.\n\n## Why is this bad?\nAccording to [PEP 8], operators should be surrounded by at most a single space on either\nside.\n\n## Example\n```python\na = 4 + 5\n```\n\nUse instead:\n```python\na = 4 + 5\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#whitespace-in-expressions-and-statements\n",
|
|
526
|
+
"ruff/E223": "## What it does\nChecks for extraneous tabs before an operator.\n\n## Why is this bad?\nAccording to [PEP 8], operators should be surrounded by at most a single space on either\nside.\n\n## Example\n```python\na = 4\\t+ 5\n```\n\nUse instead:\n```python\na = 4 + 5\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#whitespace-in-expressions-and-statements\n",
|
|
527
|
+
"ruff/E224": "## What it does\nChecks for extraneous tabs after an operator.\n\n## Why is this bad?\nAccording to [PEP 8], operators should be surrounded by at most a single space on either\nside.\n\n## Example\n```python\na = 4 +\\t5\n```\n\nUse instead:\n```python\na = 4 + 5\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#whitespace-in-expressions-and-statements\n",
|
|
528
|
+
"ruff/E225": "## What it does\nChecks for missing whitespace around all operators.\n\n## Why is this bad?\nAccording to [PEP 8], there should be one space before and after all\nassignment (`=`), augmented assignment (`+=`, `-=`, etc.), comparison,\nand Booleans operators.\n\n## Example\n```python\nif number==42:\n print('you have found the meaning of life')\n```\n\nUse instead:\n```python\nif number == 42:\n print('you have found the meaning of life')\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#pet-peeves\n",
|
|
529
|
+
"ruff/E226": "## What it does\nChecks for missing whitespace arithmetic operators.\n\n## Why is this bad?\n[PEP 8] recommends never using more than one space, and always having the\nsame amount of whitespace on both sides of a binary operator.\n\nFor consistency, this rule enforces one space before and after an\narithmetic operator (`+`, `-`, `/`, and `*`).\n\n(Note that [PEP 8] suggests only adding whitespace around the operator with\nthe lowest precedence, but that authors should \"use [their] own judgment\".)\n\n## Example\n```python\nnumber = 40+2\n```\n\nUse instead:\n```python\nnumber = 40 + 2\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#other-recommendations\n",
|
|
530
|
+
"ruff/E227": "## What it does\nChecks for missing whitespace around bitwise and shift operators.\n\n## Why is this bad?\n[PEP 8] recommends never using more than one space, and always having the\nsame amount of whitespace on both sides of a binary operator.\n\nFor consistency, this rule enforces one space before and after bitwise and\nshift operators (`<<`, `>>`, `&`, `|`, `^`).\n\n(Note that [PEP 8] suggests only adding whitespace around the operator with\nthe lowest precedence, but that authors should \"use [their] own judgment\".)\n\n## Example\n```python\nx = 128<<1\n```\n\nUse instead:\n```python\nx = 128 << 1\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#other-recommendations\n",
|
|
531
|
+
"ruff/E228": "## What it does\nChecks for missing whitespace around the modulo operator.\n\n## Why is this bad?\n[PEP 8] recommends never using more than one space, and always having the\nsame amount of whitespace on both sides of a binary operator.\n\nFor consistency, this rule enforces one space before and after a modulo\noperator (`%`).\n\n(Note that [PEP 8] suggests only adding whitespace around the operator with\nthe lowest precedence, but that authors should \"use [their] own judgment\".)\n\n## Example\n```python\nremainder = 10%2\n```\n\nUse instead:\n```python\nremainder = 10 % 2\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#other-recommendations\n",
|
|
532
|
+
"ruff/E231": "## What it does\nChecks for missing whitespace after `,`, `;`, and `:`.\n\n## Why is this bad?\nMissing whitespace after `,`, `;`, and `:` makes the code harder to read.\n\n## Example\n```python\na = (1,2)\n```\n\nUse instead:\n```python\na = (1, 2)\n```\n",
|
|
533
|
+
"ruff/E241": "## What it does\nChecks for extraneous whitespace after a comma.\n\n## Why is this bad?\nConsistency is good. This rule helps ensure you have a consistent\nformatting style across your project.\n\n## Example\n```python\na = 4, 5\n```\n\nUse instead:\n```python\na = 4, 5\n```\n",
|
|
534
|
+
"ruff/E242": "## What it does\nChecks for extraneous tabs after a comma.\n\n## Why is this bad?\nCommas should be followed by one space, never tabs.\n\n## Example\n```python\na = 4,\\t5\n```\n\nUse instead:\n```python\na = 4, 5\n```\n\n",
|
|
535
|
+
"ruff/E251": "## What it does\nChecks for missing whitespace around the equals sign in an unannotated\nfunction keyword parameter.\n\n## Why is this bad?\nAccording to [PEP 8], there should be no spaces around the equals sign in a\nkeyword parameter, if it is unannotated:\n\n> Don\u2019t use spaces around the = sign when used to indicate a keyword\n> argument, or when used to indicate a default value for an unannotated\n> function parameter.\n\n## Example\n```python\ndef add(a = 0) -> int:\n return a + 1\n```\n\nUse instead:\n```python\ndef add(a=0) -> int:\n return a + 1\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#whitespace-in-expressions-and-statements\n",
|
|
536
|
+
"ruff/E252": "## What it does\nChecks for missing whitespace around the equals sign in an annotated\nfunction keyword parameter.\n\n## Why is this bad?\nAccording to [PEP 8], the spaces around the equals sign in a keyword\nparameter should only be omitted when the parameter is unannotated:\n\n> Don\u2019t use spaces around the = sign when used to indicate a keyword\n> argument, or when used to indicate a default value for an unannotated\n> function parameter.\n\n## Example\n```python\ndef add(a: int=0) -> int:\n return a + 1\n```\n\nUse instead:\n```python\ndef add(a: int = 0) -> int:\n return a + 1\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#whitespace-in-expressions-and-statements\n",
|
|
537
|
+
"ruff/E261": "## What it does\nChecks if inline comments are separated by at least two spaces.\n\n## Why is this bad?\nAn inline comment is a comment on the same line as a statement.\n\nPer [PEP 8], inline comments should be separated by at least two spaces from\nthe preceding statement.\n\n## Example\n```python\nx = x + 1 # Increment x\n```\n\nUse instead:\n```python\nx = x + 1 # Increment x\nx = x + 1 # Increment x\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#comments\n",
|
|
538
|
+
"ruff/E262": "## What it does\nChecks if one space is used after inline comments.\n\n## Why is this bad?\nAn inline comment is a comment on the same line as a statement.\n\nPer [PEP 8], inline comments should start with a # and a single space.\n\n## Example\n```python\nx = x + 1 #Increment x\nx = x + 1 # Increment x\nx = x + 1 # \\xa0Increment x\n```\n\nUse instead:\n```python\nx = x + 1 # Increment x\nx = x + 1 # Increment x\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#comments\n",
|
|
539
|
+
"ruff/E265": "## What it does\nChecks for block comments that lack a single space after the leading `#` character.\n\n## Why is this bad?\nPer [PEP 8], \"Block comments generally consist of one or more paragraphs built\nout of complete sentences, with each sentence ending in a period.\"\n\nBlock comments should start with a `#` followed by a single space.\n\nShebangs (lines starting with `#!`, at the top of a file) are exempt from this\nrule.\n\n## Example\n```python\n#Block comment\n```\n\nUse instead:\n```python\n# Block comment\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#comments\n",
|
|
540
|
+
"ruff/E266": "## What it does\nChecks for block comments that start with multiple leading `#` characters.\n\n## Why is this bad?\nPer [PEP 8], \"Block comments generally consist of one or more paragraphs built\nout of complete sentences, with each sentence ending in a period.\"\n\nEach line of a block comment should start with a `#` followed by a single space.\n\nShebangs (lines starting with `#!`, at the top of a file) are exempt from this\nrule.\n\n## Example\n```python\n### Block comment\n```\n\nUse instead:\n```python\n# Block comment\n```\n\nAlternatively, this rule makes an exception for comments that consist\nsolely of `#` characters, as in:\n\n```python\n##############\n# Block header\n##############\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#comments\n",
|
|
541
|
+
"ruff/E271": "## What it does\nChecks for extraneous whitespace after keywords.\n\n## Why is this bad?\n\n\n## Example\n```python\nTrue and False\n```\n\nUse instead:\n```python\nTrue and False\n```\n",
|
|
542
|
+
"ruff/E272": "## What it does\nChecks for extraneous whitespace before keywords.\n\n## Why is this bad?\n\n\n## Example\n```python\nx and y\n```\n\nUse instead:\n```python\nx and y\n```\n",
|
|
543
|
+
"ruff/E273": "## What it does\nChecks for extraneous tabs after keywords.\n\n## Why is this bad?\n\n\n## Example\n```python\nTrue and\\tFalse\n```\n\nUse instead:\n```python\nTrue and False\n```\n",
|
|
544
|
+
"ruff/E274": "## What it does\nChecks for extraneous tabs before keywords.\n\n## Why is this bad?\n\n\n## Example\n```python\nTrue\\tand False\n```\n\nUse instead:\n```python\nTrue and False\n```\n",
|
|
545
|
+
"ruff/E275": "## What it does\nChecks for missing whitespace after keywords.\n\n## Why is this bad?\nMissing whitespace after keywords makes the code harder to read.\n\n## Example\n```python\nif(True):\n pass\n```\n\nUse instead:\n```python\nif (True):\n pass\n```\n\n## References\n- [Python documentation: Keywords](https://docs.python.org/3/reference/lexical_analysis.html#keywords)\n",
|
|
546
|
+
"ruff/E301": "## What it does\nChecks for missing blank lines between methods of a class.\n\n## Why is this bad?\nPEP 8 recommends exactly one blank line between methods of a class.\n\n## Example\n```python\nclass MyClass(object):\n def func1():\n pass\n def func2():\n pass\n```\n\nUse instead:\n```python\nclass MyClass(object):\n def func1():\n pass\n\n def func2():\n pass\n```\n\n## Typing stub files (`.pyi`)\nThe typing style guide recommends to not use blank lines between methods except to group\nthem. That's why this rule is not enabled in typing stub files.\n\n## References\n- [PEP 8: Blank Lines](https://peps.python.org/pep-0008/#blank-lines)\n- [Flake 8 rule](https://www.flake8rules.com/rules/E301.html)\n- [Typing Style Guide](https://typing.python.org/en/latest/guides/writing_stubs.html#blank-lines)\n",
|
|
547
|
+
"ruff/E302": "## What it does\nChecks for missing blank lines between top level functions and classes.\n\n## Why is this bad?\nPEP 8 recommends exactly two blank lines between top level functions and classes.\n\nThe rule respects the [`lint.isort.lines-after-imports`] setting when\ndetermining the required number of blank lines between top-level `import`\nstatements and function or class definitions for compatibility with isort.\n\n## Example\n```python\ndef func1():\n pass\ndef func2():\n pass\n```\n\nUse instead:\n```python\ndef func1():\n pass\n\n\ndef func2():\n pass\n```\n\n## Typing stub files (`.pyi`)\nThe typing style guide recommends to not use blank lines between classes and functions except to group\nthem. That's why this rule is not enabled in typing stub files.\n\n## Options\n- `lint.isort.lines-after-imports`\n\n## References\n- [PEP 8: Blank Lines](https://peps.python.org/pep-0008/#blank-lines)\n- [Flake 8 rule](https://www.flake8rules.com/rules/E302.html)\n- [Typing Style Guide](https://typing.python.org/en/latest/guides/writing_stubs.html#blank-lines)\n",
|
|
548
|
+
"ruff/E303": "## What it does\nChecks for extraneous blank lines.\n\n## Why is this bad?\nPEP 8 recommends using blank lines as follows:\n- No more than two blank lines between top-level statements.\n- No more than one blank line between non-top-level statements.\n\n## Example\n```python\ndef func1():\n pass\n\n\n\ndef func2():\n pass\n```\n\nUse instead:\n```python\ndef func1():\n pass\n\n\ndef func2():\n pass\n```\n\n## Typing stub files (`.pyi`)\nThe rule allows at most one blank line in typing stub files in accordance to the typing style guide recommendation.\n\nNote: The rule respects the following `isort` settings when determining the maximum number of blank lines allowed between two statements:\n\n* [`lint.isort.lines-after-imports`]: For top-level statements directly following an import statement.\n* [`lint.isort.lines-between-types`]: For `import` statements directly following a `from ... import ...` statement or vice versa.\n\n## Options\n- `lint.isort.lines-after-imports`\n- `lint.isort.lines-between-types`\n\n## References\n- [PEP 8: Blank Lines](https://peps.python.org/pep-0008/#blank-lines)\n- [Flake 8 rule](https://www.flake8rules.com/rules/E303.html)\n- [Typing Style Guide](https://typing.python.org/en/latest/guides/writing_stubs.html#blank-lines)\n",
|
|
549
|
+
"ruff/E304": "## What it does\nChecks for extraneous blank line(s) after function decorators.\n\n## Why is this bad?\nThere should be no blank lines between a decorator and the object it is decorating.\n\n## Example\n```python\nclass User(object):\n\n @property\n\n def name(self):\n pass\n```\n\nUse instead:\n```python\nclass User(object):\n\n @property\n def name(self):\n pass\n```\n\n## References\n- [PEP 8: Blank Lines](https://peps.python.org/pep-0008/#blank-lines)\n- [Flake 8 rule](https://www.flake8rules.com/rules/E304.html)\n",
|
|
550
|
+
"ruff/E305": "## What it does\nChecks for missing blank lines after the end of function or class.\n\n## Why is this bad?\nPEP 8 recommends using blank lines as follows:\n- Two blank lines are expected between functions and classes\n- One blank line is expected between methods of a class.\n\n## Example\n```python\nclass User(object):\n pass\nuser = User()\n```\n\nUse instead:\n```python\nclass User(object):\n pass\n\n\nuser = User()\n```\n\n## Typing stub files (`.pyi`)\nThe typing style guide recommends to not use blank lines between statements except to group\nthem. That's why this rule is not enabled in typing stub files.\n\n## References\n- [PEP 8: Blank Lines](https://peps.python.org/pep-0008/#blank-lines)\n- [Flake 8 rule](https://www.flake8rules.com/rules/E305.html)\n- [Typing Style Guide](https://typing.python.org/en/latest/guides/writing_stubs.html#blank-lines)\n",
|
|
551
|
+
"ruff/E306": "## What it does\nChecks for 1 blank line between nested function or class definitions.\n\n## Why is this bad?\nPEP 8 recommends using blank lines as follows:\n- Two blank lines are expected between functions and classes\n- One blank line is expected between methods of a class.\n\n## Example\n```python\ndef outer():\n def inner():\n pass\n def inner2():\n pass\n```\n\nUse instead:\n```python\ndef outer():\n def inner():\n pass\n\n def inner2():\n pass\n```\n\n## Typing stub files (`.pyi`)\nThe typing style guide recommends to not use blank lines between classes and functions except to group\nthem. That's why this rule is not enabled in typing stub files.\n\n## References\n- [PEP 8: Blank Lines](https://peps.python.org/pep-0008/#blank-lines)\n- [Flake 8 rule](https://www.flake8rules.com/rules/E306.html)\n- [Typing Style Guide](https://typing.python.org/en/latest/guides/writing_stubs.html#blank-lines)\n",
|
|
552
|
+
"ruff/E401": "## What it does\nCheck for multiple imports on one line.\n\n## Why is this bad?\nAccording to [PEP 8], \"imports should usually be on separate lines.\"\n\n## Example\n```python\nimport sys, os\n```\n\nUse instead:\n```python\nimport os\nimport sys\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#imports\n",
|
|
553
|
+
"ruff/E402": "## What it does\nChecks for imports that are not at the top of the file.\n\n## Why is this bad?\nAccording to [PEP 8], \"imports are always put at the top of the file, just after any\nmodule comments and docstrings, and before module globals and constants.\"\n\nThis rule makes an exception for both `sys.path` modifications (allowing for\n`sys.path.insert`, `sys.path.append`, etc.) and `os.environ` modifications\nbetween imports.\n\n## Example\n```python\n\"One string\"\n\"Two string\"\na = 1\nimport os\nfrom sys import x\n```\n\nUse instead:\n```python\nimport os\nfrom sys import x\n\n\"One string\"\n\"Two string\"\na = 1\n```\n\n## Notebook behavior\nFor Jupyter notebooks, this rule checks for imports that are not at the top of a *cell*.\n\n## Fix safety\nThis rule's fix is marked as unsafe as imports moved to the top of the file\nare placed above existing imports, in reverse order than they were in the\nfile. Re-ordering imports is unsafe as it can change the execution order of\nthe imported code.\n\n[PEP 8]: https://peps.python.org/pep-0008/#imports\n",
|
|
554
|
+
"ruff/E501": "## What it does\nChecks for lines that exceed the specified maximum character length.\n\n## Why is this bad?\nOverlong lines can hurt readability. [PEP 8], for example, recommends\nlimiting lines to 79 characters. By default, this rule enforces a limit\nof 88 characters for compatibility with Black and the Ruff formatter,\nthough that limit is configurable via the [`line-length`] setting.\n\nIn the interest of pragmatism, this rule makes a few exceptions when\ndetermining whether a line is overlong. Namely, it:\n\n1. Ignores lines that consist of a single \"word\" (i.e., without any\n whitespace between its characters).\n2. Ignores lines that end with a URL, as long as the URL starts before\n the line-length threshold.\n3. Ignores line that end with a pragma comment (e.g., `# type: ignore`\n or `# noqa`), as long as the pragma comment starts before the\n line-length threshold. That is, a line will not be flagged as\n overlong if a pragma comment _causes_ it to exceed the line length.\n (This behavior aligns with that of the Ruff formatter.)\n4. Ignores SPDX license identifiers and copyright notices\n (e.g., `# SPDX-License-Identifier: MIT`), which are machine-readable\n and should _not_ wrap over multiple lines.\n\nIf [`lint.pycodestyle.ignore-overlong-task-comments`] is `true`, this rule will\nalso ignore comments that start with any of the specified [`lint.task-tags`]\n(e.g., `# TODO:`).\n\n## Example\n```python\nmy_function(param1, param2, param3, param4, param5, param6, param7, param8, param9, param10)\n```\n\nUse instead:\n```python\nmy_function(\n param1, param2, param3, param4, param5,\n param6, param7, param8, param9, param10\n)\n```\n\n## Error suppression\nHint: when suppressing `E501` errors within multi-line strings (like\ndocstrings), the `noqa` directive should come at the end of the string\n(after the closing triple quote), and will apply to the entire string, like\nso:\n\n```python\n\"\"\"Lorem ipsum dolor sit amet.\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor.\n\"\"\" # noqa: E501\n```\n\n## Options\n- `line-length`\n- `lint.task-tags`\n- `lint.pycodestyle.ignore-overlong-task-comments`\n- `lint.pycodestyle.max-line-length`\n\n[PEP 8]: https://peps.python.org/pep-0008/#maximum-line-length\n",
|
|
555
|
+
"ruff/E502": "## What it does\nChecks for redundant backslashes between brackets.\n\n## Why is this bad?\nExplicit line joins using a backslash are redundant between brackets.\n\n## Example\n```python\nx = (2 + \\\n 2)\n```\n\nUse instead:\n```python\nx = (2 +\n 2)\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#maximum-line-length\n",
|
|
556
|
+
"ruff/E701": "## What it does\nChecks for compound statements (multiple statements on the same line).\n\n## Why is this bad?\nAccording to [PEP 8], \"compound statements are generally discouraged\".\n\n## Example\n```python\nif foo == \"blah\": do_blah_thing()\n```\n\nUse instead:\n```python\nif foo == \"blah\":\n do_blah_thing()\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#other-recommendations\n",
|
|
557
|
+
"ruff/E702": "## What it does\nChecks for multiline statements on one line.\n\n## Why is this bad?\nAccording to [PEP 8], including multi-clause statements on the same line is\ndiscouraged.\n\n## Example\n```python\ndo_one(); do_two(); do_three()\n```\n\nUse instead:\n```python\ndo_one()\ndo_two()\ndo_three()\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#other-recommendations\n",
|
|
558
|
+
"ruff/E703": "## What it does\nChecks for statements that end with an unnecessary semicolon.\n\n## Why is this bad?\nA trailing semicolon is unnecessary and should be removed.\n\n## Example\n```python\ndo_four(); # useless semicolon\n```\n\nUse instead:\n```python\ndo_four()\n```\n",
|
|
559
|
+
"ruff/E711": "## What it does\nChecks for comparisons to `None` which are not using the `is` operator.\n\n## Why is this bad?\nAccording to [PEP 8], \"Comparisons to singletons like None should always be done with\n`is` or `is not`, never the equality operators.\"\n\n## Example\n```python\nif arg != None:\n pass\nif None == arg:\n pass\n```\n\nUse instead:\n```python\nif arg is not None:\n pass\n```\n\n## Fix safety\n\nThis rule's fix is marked as unsafe, as it may alter runtime behavior when\nused with libraries that override the `==`/`__eq__` or `!=`/`__ne__` operators.\nIn these cases, `is`/`is not` may not be equivalent to `==`/`!=`. For more\ninformation, see [this issue].\n\n[PEP 8]: https://peps.python.org/pep-0008/#programming-recommendations\n[this issue]: https://github.com/astral-sh/ruff/issues/4560\n",
|
|
560
|
+
"ruff/E712": "## What it does\nChecks for equality comparisons to boolean literals.\n\n## Why is this bad?\n[PEP 8] recommends against using the equality operators `==` and `!=` to\ncompare values to `True` or `False`.\n\nInstead, use `if cond:` or `if not cond:` to check for truth values.\n\nIf you intend to check if a value is the boolean literal `True` or `False`,\nconsider using `is` or `is not` to check for identity instead.\n\n## Example\n```python\nif foo == True:\n ...\n\nif bar == False:\n ...\n```\n\nUse instead:\n```python\nif foo:\n ...\n\nif not bar:\n ...\n```\n\n## Fix safety\n\nThis rule's fix is marked as unsafe, as it may alter runtime behavior when\nused with libraries that override the `==`/`__eq__` or `!=`/`__ne__` operators.\nIn these cases, `is`/`is not` may not be equivalent to `==`/`!=`. For more\ninformation, see [this issue].\n\n[PEP 8]: https://peps.python.org/pep-0008/#programming-recommendations\n[this issue]: https://github.com/astral-sh/ruff/issues/4560\n",
|
|
561
|
+
"ruff/E713": "## What it does\nChecks for membership tests using `not {element} in {collection}`.\n\n## Why is this bad?\nTesting membership with `{element} not in {collection}` is more readable.\n\n## Example\n```python\nZ = not X in Y\nif not X.B in Y:\n pass\n```\n\nUse instead:\n```python\nZ = X not in Y\nif X.B not in Y:\n pass\n```\n",
|
|
562
|
+
"ruff/E714": "## What it does\nChecks for identity comparisons using `not {foo} is {bar}`.\n\n## Why is this bad?\nAccording to [PEP8], testing for an object's identity with `is not` is more\nreadable.\n\n## Example\n```python\nif not X is Y:\n pass\nZ = not X.B is Y\n```\n\nUse instead:\n```python\nif X is not Y:\n pass\nZ = X.B is not Y\n```\n\n[PEP8]: https://peps.python.org/pep-0008/#programming-recommendations\n",
|
|
563
|
+
"ruff/E721": "## What it does\nChecks for object type comparisons using `==` and other comparison\noperators.\n\n## Why is this bad?\nUnlike a direct type comparison, `isinstance` will also check if an object\nis an instance of a class or a subclass thereof.\n\nIf you want to check for an exact type match, use `is` or `is not`.\n\n## Known problems\nWhen using libraries that override the `==` (`__eq__`) operator (such as NumPy,\nPandas, and SQLAlchemy), this rule may produce false positives, as converting\nfrom `==` to `is` or `is not` will change the behavior of the code.\n\nFor example, the following operations are _not_ equivalent:\n```python\nimport numpy as np\n\nnp.array([True, False]) == False\n# array([False, True])\n\nnp.array([True, False]) is False\n# False\n```\n\n## Example\n```python\nif type(obj) == type(1):\n pass\n\nif type(obj) == int:\n pass\n```\n\nUse instead:\n```python\nif isinstance(obj, int):\n pass\n```\n",
|
|
564
|
+
"ruff/E722": "## What it does\nChecks for bare `except` catches in `try`-`except` statements.\n\n## Why is this bad?\nA bare `except` catches `BaseException` which includes\n`KeyboardInterrupt`, `SystemExit`, `Exception`, and others. Catching\n`BaseException` can make it hard to interrupt the program (e.g., with\nCtrl-C) and can disguise other problems.\n\n## Example\n```python\ntry:\n raise KeyboardInterrupt(\"You probably don't mean to break CTRL-C.\")\nexcept:\n print(\"But a bare `except` will ignore keyboard interrupts.\")\n```\n\nUse instead:\n```python\ntry:\n do_something_that_might_break()\nexcept MoreSpecificException as e:\n handle_error(e)\n```\n\nIf you actually need to catch an unknown error, use `Exception` which will\ncatch regular program errors but not important system exceptions.\n\n```python\ndef run_a_function(some_other_fn):\n try:\n some_other_fn()\n except Exception as e:\n print(f\"How exceptional! {e}\")\n```\n\n## References\n- [Python documentation: Exception hierarchy](https://docs.python.org/3/library/exceptions.html#exception-hierarchy)\n- [Google Python Style Guide: \"Exceptions\"](https://google.github.io/styleguide/pyguide.html#24-exceptions)\n",
|
|
565
|
+
"ruff/E731": "## What it does\nChecks for lambda expressions which are assigned to a variable.\n\n## Why is this bad?\nPer PEP 8, you should \"Always use a def statement instead of an assignment\nstatement that binds a lambda expression directly to an identifier.\"\n\nUsing a `def` statement leads to better tracebacks, and the assignment\nitself negates the primary benefit of using a `lambda` expression (i.e.,\nthat it can be embedded inside another expression).\n\n## Example\n```python\nf = lambda x: 2 * x\n```\n\nUse instead:\n```python\ndef f(x):\n return 2 * x\n```\n\n## Fix safety\nThis fix is marked as unsafe because converting a lambda assignment into a\nfunction definition changes observable properties of the callable.\n\nIn particular, a lambda function has the name `\"<lambda>\"`, while the\ngenerated function uses the name of the assigned variable. Code that relies\non function metadata, such as logging, registration, or introspection, may\ntherefore behave differently after the fix.\n\n[PEP 8]: https://peps.python.org/pep-0008/#programming-recommendations\n",
|
|
566
|
+
"ruff/E741": "## What it does\nChecks for the use of the characters 'l', 'O', or 'I' as variable names.\n\nNote: This rule is automatically disabled for all stub files\n(files with `.pyi` extensions). The rule has little relevance for authors\nof stubs: a well-written stub should aim to faithfully represent the\ninterface of the equivalent .py file as it exists at runtime, including any\nambiguously named variables in the runtime module.\n\n## Why is this bad?\nIn some fonts, these characters are indistinguishable from the\nnumerals one and zero. When tempted to use 'l', use 'L' instead.\n\n## Example\n```python\nl = 0\nO = 123\nI = 42\n```\n\nUse instead:\n```python\nL = 0\no = 123\ni = 42\n```\n",
|
|
567
|
+
"ruff/E742": "## What it does\nChecks for the use of the characters 'l', 'O', or 'I' as class names.\n\n## Why is this bad?\nIn some fonts, these characters are indistinguishable from the\nnumerals one and zero. When tempted to use 'l', use 'L' instead.\n\n## Example\n\n```python\nclass I(object): ...\n```\n\nUse instead:\n\n```python\nclass Integer(object): ...\n```\n",
|
|
568
|
+
"ruff/E743": "## What it does\nChecks for the use of the characters 'l', 'O', or 'I' as function names.\n\n## Why is this bad?\nIn some fonts, these characters are indistinguishable from the\nnumerals one and zero. When tempted to use 'l', use 'L' instead.\n\n## Example\n\n```python\ndef l(x): ...\n```\n\nUse instead:\n\n```python\ndef long_name(x): ...\n```\n",
|
|
569
|
+
"ruff/E902": "## What it does\nThis is not a regular diagnostic; instead, it's raised when a file cannot be read\nfrom disk.\n\n## Why is this bad?\nAn `IOError` indicates an error in the development setup. For example, the user may\nnot have permissions to read a given file, or the filesystem may contain a broken\nsymlink.\n\n## Example\nOn Linux or macOS:\n```shell\n$ echo 'print(\"hello world!\")' > a.py\n$ chmod 000 a.py\n$ ruff a.py\na.py:1:1: E902 Permission denied (os error 13)\nFound 1 error.\n```\n\n## References\n- [UNIX Permissions introduction](https://mason.gmu.edu/~montecin/UNIXpermiss.htm)\n- [Command Line Basics: Symbolic Links](https://www.digitalocean.com/community/tutorials/workflow-symbolic-links)\n",
|
|
570
|
+
"ruff/E999": "## Removed\nThis rule has been removed. Syntax errors will\nalways be shown regardless of whether this rule is selected or not.\n\n## What it does\nChecks for code that contains syntax errors.\n\n## Why is this bad?\nCode with syntax errors cannot be executed. Such errors are likely a\nmistake.\n\n## Example\n```python\nx =\n```\n\nUse instead:\n```python\nx = 1\n```\n\n## References\n- [Python documentation: Syntax Errors](https://docs.python.org/3/tutorial/errors.html#syntax-errors)\n",
|
|
571
|
+
"ruff/W191": "## What it does\nChecks for indentation that uses tabs.\n\n## Why is this bad?\nAccording to [PEP 8], spaces are preferred over tabs (unless used to remain\nconsistent with code that is already indented with tabs).\n\n## Formatter compatibility\nWe recommend against using this rule alongside the [formatter]. The\nformatter enforces consistent indentation, making the rule redundant.\n\nThe rule is also incompatible with the [formatter] when using\n`format.indent-style=\"tab\"`.\n\n[PEP 8]: https://peps.python.org/pep-0008/#tabs-or-spaces\n[formatter]: https://docs.astral.sh/ruff/formatter\n",
|
|
572
|
+
"ruff/W291": "## What it does\nChecks for superfluous trailing whitespace.\n\n## Why is this bad?\nAccording to [PEP 8], \"avoid trailing whitespace anywhere. Because it\u2019s usually\ninvisible, it can be confusing\"\n\n## Example\n```python\nspam(1) \\n#\n```\n\nUse instead:\n```python\nspam(1)\\n#\n```\n\n## Fix safety\n\nThis fix is marked unsafe if the whitespace is inside a multiline string,\nas removing it changes the string's content.\n\n[PEP 8]: https://peps.python.org/pep-0008/#other-recommendations\n",
|
|
573
|
+
"ruff/W292": "## What it does\nChecks for files missing a new line at the end of the file.\n\n## Why is this bad?\nTrailing blank lines in a file are superfluous.\n\nHowever, the last line of the file should end with a newline.\n\n## Example\n```python\nspam(1)\n```\n\nUse instead:\n```python\nspam(1)\\n\n```\n",
|
|
574
|
+
"ruff/W293": "## What it does\nChecks for superfluous whitespace in blank lines.\n\n## Why is this bad?\nAccording to [PEP 8], \"avoid trailing whitespace anywhere. Because it\u2019s usually\ninvisible, it can be confusing\"\n\n## Example\n```python\nclass Foo(object):\\n \\n bang = 12\n```\n\nUse instead:\n```python\nclass Foo(object):\\n\\n bang = 12\n```\n\n## Fix safety\n\nThis fix is marked unsafe if the whitespace is inside a multiline string,\nas removing it changes the string's content.\n\n[PEP 8]: https://peps.python.org/pep-0008/#other-recommendations\n",
|
|
575
|
+
"ruff/W391": "## What it does\nChecks for files with multiple trailing blank lines.\n\nIn the case of notebooks, this check is applied to\neach cell separately.\n\n## Why is this bad?\nTrailing blank lines in a file are superfluous.\n\nHowever, the last line of the file should end with a newline.\n\n## Example\n```python\nspam(1)\\n\\n\\n\n```\n\nUse instead:\n```python\nspam(1)\\n\n```\n",
|
|
576
|
+
"ruff/W505": "## What it does\nChecks for doc lines that exceed the specified maximum character length.\n\n## Why is this bad?\nFor flowing long blocks of text (docstrings or comments), overlong lines\ncan hurt readability. [PEP 8], for example, recommends that such lines be\nlimited to 72 characters, while this rule enforces the limit specified by\nthe [`lint.pycodestyle.max-doc-length`] setting. (If no value is provided, this\nrule will be ignored, even if it's added to your `--select` list.)\n\nIn the context of this rule, a \"doc line\" is defined as a line consisting\nof either a standalone comment or a standalone string, like a docstring.\n\nIn the interest of pragmatism, this rule makes a few exceptions when\ndetermining whether a line is overlong. Namely, it:\n\n1. Ignores lines that consist of a single \"word\" (i.e., without any\n whitespace between its characters).\n2. Ignores lines that end with a URL, as long as the URL starts before\n the line-length threshold.\n3. Ignores line that end with a pragma comment (e.g., `# type: ignore`\n or `# noqa`), as long as the pragma comment starts before the\n line-length threshold. That is, a line will not be flagged as\n overlong if a pragma comment _causes_ it to exceed the line length.\n (This behavior aligns with that of the Ruff formatter.)\n\nIf [`lint.pycodestyle.ignore-overlong-task-comments`] is `true`, this rule will\nalso ignore comments that start with any of the specified [`lint.task-tags`]\n(e.g., `# TODO:`).\n\n## Example\n```python\ndef function(x):\n \"\"\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis auctor purus ut ex fermentum, at maximus est hendrerit.\"\"\"\n```\n\nUse instead:\n```python\ndef function(x):\n \"\"\"\n Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n Duis auctor purus ut ex fermentum, at maximus est hendrerit.\n \"\"\"\n```\n\n## Error suppression\nHint: when suppressing `W505` errors within multi-line strings (like\ndocstrings), the `noqa` directive should come at the end of the string\n(after the closing triple quote), and will apply to the entire string, like\nso:\n\n```python\n\"\"\"Lorem ipsum dolor sit amet.\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor.\n\"\"\" # noqa: W505\n```\n\n## Options\n- `lint.task-tags`\n- `lint.pycodestyle.max-doc-length`\n- `lint.pycodestyle.ignore-overlong-task-comments`\n\n[PEP 8]: https://peps.python.org/pep-0008/#maximum-line-length\n",
|
|
577
|
+
"ruff/W605": "## What it does\nChecks for invalid escape sequences.\n\n## Why is this bad?\nInvalid escape sequences are deprecated in Python 3.6.\n\n## Example\n```python\nregex = \"\\.png$\"\n```\n\nUse instead:\n```python\nregex = r\"\\.png$\"\n```\n\nOr, if the string already contains a valid escape sequence:\n```python\nvalue = \"new line\\nand invalid escape \\_ here\"\n```\n\nUse instead:\n```python\nvalue = \"new line\\nand invalid escape \\\\_ here\"\n```\n\n## References\n- [Python documentation: String and Bytes literals](https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals)\n",
|
|
578
|
+
"ruff/DOC102": "## What it does\nChecks for function docstrings that include parameters which are not\nin the function signature.\n\n## Why is this bad?\nIf a docstring documents a parameter which is not in the function signature,\nit can be misleading to users and/or a sign of incomplete documentation or\nrefactors.\n\n## Example\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Args:\n distance: Distance traveled.\n time: Time spent traveling.\n acceleration: Rate of change of speed.\n\n Returns:\n Speed as distance divided by time.\n \"\"\"\n return distance / time\n```\n\nUse instead:\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Args:\n distance: Distance traveled.\n time: Time spent traveling.\n\n Returns:\n Speed as distance divided by time.\n \"\"\"\n return distance / time\n```\n\n## Options\n\n- `lint.pydoclint.ignore-one-line-docstrings`\n- `lint.pydocstyle.convention`\n",
|
|
579
|
+
"ruff/DOC201": "## What it does\nChecks for functions with `return` statements that do not have \"Returns\"\nsections in their docstrings.\n\n## Why is this bad?\nA missing \"Returns\" section is a sign of incomplete documentation.\n\nThis rule is not enforced for abstract methods or functions that only return\n`None`. It is also ignored for \"stub functions\": functions where the body only\nconsists of `pass`, `...`, `raise NotImplementedError`, or similar.\n\n## Example\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Args:\n distance: Distance traveled.\n time: Time spent traveling.\n \"\"\"\n return distance / time\n```\n\nUse instead:\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Args:\n distance: Distance traveled.\n time: Time spent traveling.\n\n Returns:\n Speed as distance divided by time.\n \"\"\"\n return distance / time\n```\n\n## Options\n\n- `lint.pydoclint.ignore-one-line-docstrings`\n- `lint.pydocstyle.convention`\n- `lint.pydocstyle.property-decorators`\n",
|
|
580
|
+
"ruff/DOC202": "## What it does\nChecks for function docstrings with unnecessary \"Returns\" sections.\n\n## Why is this bad?\nA function without an explicit `return` statement should not have a\n\"Returns\" section in its docstring.\n\nThis rule is not enforced for abstract methods. It is also ignored for\n\"stub functions\": functions where the body only consists of `pass`, `...`,\n`raise NotImplementedError`, or similar.\n\n## Example\n```python\ndef say_hello(n: int) -> None:\n \"\"\"Says hello to the user.\n\n Args:\n n: Number of times to say hello.\n\n Returns:\n Doesn't return anything.\n \"\"\"\n for _ in range(n):\n print(\"Hello!\")\n```\n\nUse instead:\n```python\ndef say_hello(n: int) -> None:\n \"\"\"Says hello to the user.\n\n Args:\n n: Number of times to say hello.\n \"\"\"\n for _ in range(n):\n print(\"Hello!\")\n```\n\n## Options\n\n- `lint.pydoclint.ignore-one-line-docstrings`\n- `lint.pydocstyle.convention`\n",
|
|
581
|
+
"ruff/DOC402": "## What it does\nChecks for functions with `yield` statements that do not have \"Yields\" sections in\ntheir docstrings.\n\n## Why is this bad?\nA missing \"Yields\" section is a sign of incomplete documentation.\n\nThis rule is not enforced for abstract methods or functions that only yield `None`.\nIt is also ignored for \"stub functions\": functions where the body only consists\nof `pass`, `...`, `raise NotImplementedError`, or similar.\n\n## Example\n```python\ndef count_to_n(n: int) -> int:\n \"\"\"Generate integers up to *n*.\n\n Args:\n n: The number at which to stop counting.\n \"\"\"\n for i in range(1, n + 1):\n yield i\n```\n\nUse instead:\n```python\ndef count_to_n(n: int) -> int:\n \"\"\"Generate integers up to *n*.\n\n Args:\n n: The number at which to stop counting.\n\n Yields:\n int: The number we're at in the count.\n \"\"\"\n for i in range(1, n + 1):\n yield i\n```\n\n## Options\n\n- `lint.pydoclint.ignore-one-line-docstrings`\n- `lint.pydocstyle.convention`\n",
|
|
582
|
+
"ruff/DOC403": "## What it does\nChecks for function docstrings with unnecessary \"Yields\" sections.\n\n## Why is this bad?\nA function that doesn't yield anything should not have a \"Yields\" section\nin its docstring.\n\nThis rule is not enforced for abstract methods. It is also ignored for\n\"stub functions\": functions where the body only consists of `pass`, `...`,\n`raise NotImplementedError`, or similar.\n\n## Example\n```python\ndef say_hello(n: int) -> None:\n \"\"\"Says hello to the user.\n\n Args:\n n: Number of times to say hello.\n\n Yields:\n Doesn't yield anything.\n \"\"\"\n for _ in range(n):\n print(\"Hello!\")\n```\n\nUse instead:\n```python\ndef say_hello(n: int) -> None:\n \"\"\"Says hello to the user.\n\n Args:\n n: Number of times to say hello.\n \"\"\"\n for _ in range(n):\n print(\"Hello!\")\n```\n\n## Options\n\n- `lint.pydoclint.ignore-one-line-docstrings`\n- `lint.pydocstyle.convention`\n",
|
|
583
|
+
"ruff/DOC501": "## What it does\nChecks for function docstrings that do not document all explicitly raised\nexceptions.\n\n## Why is this bad?\nA function should document all exceptions that are directly raised in some\ncircumstances. Failing to document an exception that could be raised\ncan be misleading to users and/or a sign of incomplete documentation.\n\nThis rule is not enforced for abstract methods. It is also ignored for\n\"stub functions\": functions where the body only consists of `pass`, `...`,\n`raise NotImplementedError`, or similar.\n\n## Example\n```python\nclass FasterThanLightError(ArithmeticError): ...\n\n\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Args:\n distance: Distance traveled.\n time: Time spent traveling.\n\n Returns:\n Speed as distance divided by time.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\nUse instead:\n```python\nclass FasterThanLightError(ArithmeticError): ...\n\n\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Args:\n distance: Distance traveled.\n time: Time spent traveling.\n\n Returns:\n Speed as distance divided by time.\n\n Raises:\n FasterThanLightError: If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\n## Options\n\n- `lint.pydoclint.ignore-one-line-docstrings`\n- `lint.pydocstyle.convention`\n",
|
|
584
|
+
"ruff/DOC502": "## What it does\nChecks for function docstrings that state that exceptions could be raised\neven though they are not directly raised in the function body.\n\n## Why is this bad?\nSome conventions prefer non-explicit exceptions be omitted from the\ndocstring.\n\nThis rule is not enforced for abstract methods. It is also ignored for\n\"stub functions\": functions where the body only consists of `pass`, `...`,\n`raise NotImplementedError`, or similar.\n\n## Example\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Args:\n distance: Distance traveled.\n time: Time spent traveling.\n\n Returns:\n Speed as distance divided by time.\n\n Raises:\n ZeroDivisionError: Divided by zero.\n \"\"\"\n return distance / time\n```\n\nUse instead:\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Args:\n distance: Distance traveled.\n time: Time spent traveling.\n\n Returns:\n Speed as distance divided by time.\n \"\"\"\n return distance / time\n```\n\n## Known issues\nIt may often be desirable to document *all* exceptions that a function\ncould possibly raise, even those which are not explicitly raised using\n`raise` statements in the function body.\n\n## Options\n\n- `lint.pydoclint.ignore-one-line-docstrings`\n- `lint.pydocstyle.convention`\n",
|
|
585
|
+
"ruff/D100": "## What it does\nChecks for undocumented public module definitions.\n\n## Why is this bad?\nPublic modules should be documented via docstrings to outline their purpose\nand contents.\n\nGenerally, module docstrings should describe the purpose of the module and\nlist the classes, exceptions, functions, and other objects that are exported\nby the module, alongside a one-line summary of each.\n\nIf the module is a script, the docstring should be usable as its \"usage\"\nmessage.\n\nIf the codebase adheres to a standard format for module docstrings, follow\nthat format for consistency.\n\n## Example\n\n```python\nclass FasterThanLightError(ZeroDivisionError): ...\n\n\ndef calculate_speed(distance: float, time: float) -> float: ...\n```\n\nUse instead:\n\n```python\n\"\"\"Utility functions and classes for calculating speed.\n\nThis module provides:\n- FasterThanLightError: exception when FTL speed is calculated;\n- calculate_speed: calculate speed given distance and time.\n\"\"\"\n\n\nclass FasterThanLightError(ZeroDivisionError): ...\n\n\ndef calculate_speed(distance: float, time: float) -> float: ...\n```\n\n## Notebook behavior\nThis rule is ignored for Jupyter Notebooks.\n\n## Options\n\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n",
|
|
586
|
+
"ruff/D101": "## What it does\nChecks for undocumented public class definitions.\n\n## Why is this bad?\nPublic classes should be documented via docstrings to outline their purpose\nand behavior.\n\nGenerally, a class docstring should describe the class's purpose and list\nits public attributes and methods.\n\nIf the codebase adheres to a standard format for class docstrings, follow\nthat format for consistency.\n\n## Example\n```python\nclass Player:\n def __init__(self, name: str, points: int = 0) -> None:\n self.name: str = name\n self.points: int = points\n\n def add_points(self, points: int) -> None:\n self.points += points\n```\n\nUse instead (in the NumPy docstring format):\n```python\nclass Player:\n \"\"\"A player in the game.\n\n Attributes\n ----------\n name : str\n The name of the player.\n points : int\n The number of points the player has.\n\n Methods\n -------\n add_points(points: int) -> None\n Add points to the player's score.\n \"\"\"\n\n def __init__(self, name: str, points: int = 0) -> None:\n self.name: str = name\n self.points: int = points\n\n def add_points(self, points: int) -> None:\n self.points += points\n```\n\nOr (in the Google docstring format):\n```python\nclass Player:\n \"\"\"A player in the game.\n\n Attributes:\n name: The name of the player.\n points: The number of points the player has.\n \"\"\"\n\n def __init__(self, name: str, points: int = 0) -> None:\n self.name: str = name\n self.points: int = points\n\n def add_points(self, points: int) -> None:\n self.points += points\n```\n\n## Options\n\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n",
|
|
587
|
+
"ruff/D102": "## What it does\nChecks for undocumented public method definitions.\n\n## Why is this bad?\nPublic methods should be documented via docstrings to outline their purpose\nand behavior.\n\nGenerally, a method docstring should describe the method's behavior,\narguments, side effects, exceptions, return values, and any other\ninformation that may be relevant to the user.\n\nIf the codebase adheres to a standard format for method docstrings, follow\nthat format for consistency.\n\nThis rule exempts methods decorated with [`@typing.override`][override],\nsince it is a common practice to document a method on a superclass but not\non an overriding method in a subclass.\n\n## Example\n\n```python\nclass Cat(Animal):\n def greet(self, happy: bool = True):\n if happy:\n print(\"Meow!\")\n else:\n raise ValueError(\"Tried to greet an unhappy cat.\")\n```\n\nUse instead (in the NumPy docstring format):\n\n```python\nclass Cat(Animal):\n def greet(self, happy: bool = True):\n \"\"\"Print a greeting from the cat.\n\n Parameters\n ----------\n happy : bool, optional\n Whether the cat is happy, is True by default.\n\n Raises\n ------\n ValueError\n If the cat is not happy.\n \"\"\"\n if happy:\n print(\"Meow!\")\n else:\n raise ValueError(\"Tried to greet an unhappy cat.\")\n```\n\nOr (in the Google docstring format):\n\n```python\nclass Cat(Animal):\n def greet(self, happy: bool = True):\n \"\"\"Print a greeting from the cat.\n\n Args:\n happy: Whether the cat is happy, is True by default.\n\n Raises:\n ValueError: If the cat is not happy.\n \"\"\"\n if happy:\n print(\"Meow!\")\n else:\n raise ValueError(\"Tried to greet an unhappy cat.\")\n```\n\n## Options\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n\n[override]: https://docs.python.org/3/library/typing.html#typing.override\n",
|
|
588
|
+
"ruff/D103": "## What it does\nChecks for undocumented public function definitions.\n\n## Why is this bad?\nPublic functions should be documented via docstrings to outline their\npurpose and behavior.\n\nGenerally, a function docstring should describe the function's behavior,\narguments, side effects, exceptions, return values, and any other\ninformation that may be relevant to the user.\n\nIf the codebase adheres to a standard format for function docstrings, follow\nthat format for consistency.\n\n## Example\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\nUse instead (using the NumPy docstring format):\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Parameters\n ----------\n distance : float\n Distance traveled.\n time : float\n Time spent traveling.\n\n Returns\n -------\n float\n Speed as distance divided by time.\n\n Raises\n ------\n FasterThanLightError\n If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\nOr, using the Google docstring format:\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Args:\n distance: Distance traveled.\n time: Time spent traveling.\n\n Returns:\n Speed as distance divided by time.\n\n Raises:\n FasterThanLightError: If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\n## Options\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Style Python Docstrings](https://google.github.io/styleguide/pyguide.html#s3.8-comments-and-docstrings)\n",
|
|
589
|
+
"ruff/D104": "## What it does\nChecks for undocumented public package definitions.\n\n## Why is this bad?\nPublic packages should be documented via docstrings to outline their\npurpose and contents.\n\nGenerally, package docstrings should list the modules and subpackages that\nare exported by the package.\n\nIf the codebase adheres to a standard format for package docstrings, follow\nthat format for consistency.\n\n## Example\n```python\n__all__ = [\"Player\", \"Game\"]\n```\n\nUse instead:\n```python\n\"\"\"Game and player management package.\n\nThis package provides classes for managing players and games.\n\"\"\"\n\n__all__ = [\"player\", \"game\"]\n```\n\n## Options\n\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Style Python Docstrings](https://google.github.io/styleguide/pyguide.html#s3.8-comments-and-docstrings)\n",
|
|
590
|
+
"ruff/D105": "## What it does\nChecks for undocumented magic method definitions.\n\n## Why is this bad?\nMagic methods (methods with names that start and end with double\nunderscores) are used to implement operator overloading and other special\nbehavior. Such methods should be documented via docstrings to\noutline their behavior.\n\nGenerally, magic method docstrings should describe the method's behavior,\narguments, side effects, exceptions, return values, and any other\ninformation that may be relevant to the user.\n\nIf the codebase adheres to a standard format for method docstrings, follow\nthat format for consistency.\n\n## Example\n```python\nclass Cat(Animal):\n def __str__(self) -> str:\n return f\"Cat: {self.name}\"\n\n\ncat = Cat(\"Dusty\")\nprint(cat) # \"Cat: Dusty\"\n```\n\nUse instead:\n```python\nclass Cat(Animal):\n def __str__(self) -> str:\n \"\"\"Return a string representation of the cat.\"\"\"\n return f\"Cat: {self.name}\"\n\n\ncat = Cat(\"Dusty\")\nprint(cat) # \"Cat: Dusty\"\n```\n\n## Options\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Style Python Docstrings](https://google.github.io/styleguide/pyguide.html#s3.8-comments-and-docstrings)\n",
|
|
591
|
+
"ruff/D106": "## What it does\nChecks for undocumented public class definitions, for nested classes.\n\n## Why is this bad?\nPublic classes should be documented via docstrings to outline their\npurpose and behavior.\n\nNested classes do not inherit the docstring of their enclosing class, so\nthey should have their own docstrings.\n\nIf the codebase adheres to a standard format for class docstrings, follow\nthat format for consistency.\n\n## Example\n\n```python\nclass Foo:\n \"\"\"Class Foo.\"\"\"\n\n class Bar: ...\n\n\nbar = Foo.Bar()\nbar.__doc__ # None\n```\n\nUse instead:\n\n```python\nclass Foo:\n \"\"\"Class Foo.\"\"\"\n\n class Bar:\n \"\"\"Class Bar.\"\"\"\n\n\nbar = Foo.Bar()\nbar.__doc__ # \"Class Bar.\"\n```\n\n## Options\n\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Style Python Docstrings](https://google.github.io/styleguide/pyguide.html#s3.8-comments-and-docstrings)\n",
|
|
592
|
+
"ruff/D107": "## What it does\nChecks for public `__init__` method definitions that are missing\ndocstrings.\n\n## Why is this bad?\nPublic `__init__` methods are used to initialize objects. `__init__`\nmethods should be documented via docstrings to describe the method's\nbehavior, arguments, side effects, exceptions, and any other information\nthat may be relevant to the user.\n\nIf the codebase adheres to a standard format for `__init__` method docstrings,\nfollow that format for consistency.\n\n## Example\n```python\nclass City:\n def __init__(self, name: str, population: int) -> None:\n self.name: str = name\n self.population: int = population\n```\n\nUse instead:\n```python\nclass City:\n def __init__(self, name: str, population: int) -> None:\n \"\"\"Initialize a city with a name and population.\"\"\"\n self.name: str = name\n self.population: int = population\n```\n\n## Options\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Style Python Docstrings](https://google.github.io/styleguide/pyguide.html#s3.8-comments-and-docstrings)\n",
|
|
593
|
+
"ruff/D200": "## What it does\nChecks for single-line docstrings that are broken across multiple lines.\n\n## Why is this bad?\n[PEP 257] recommends that docstrings that _can_ fit on one line should be\nformatted on a single line, for consistency and readability.\n\n## Example\n```python\ndef average(values: list[float]) -> float:\n \"\"\"\n Return the mean of the given values.\n \"\"\"\n```\n\nUse instead:\n```python\ndef average(values: list[float]) -> float:\n \"\"\"Return the mean of the given values.\"\"\"\n```\n\n## Fix safety\nThe fix is marked as unsafe because it could affect tools that parse docstrings,\ndocumentation generators, or custom introspection utilities that rely on\nspecific docstring formatting.\n\n## Options\n\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n\n[PEP 257]: https://peps.python.org/pep-0257/\n",
|
|
594
|
+
"ruff/D201": "## What it does\nChecks for docstrings on functions that are separated by one or more blank\nlines from the function definition.\n\n## Why is this bad?\nRemove any blank lines between the function definition and its docstring,\nfor consistency.\n\n## Example\n```python\ndef average(values: list[float]) -> float:\n\n \"\"\"Return the mean of the given values.\"\"\"\n```\n\nUse instead:\n```python\ndef average(values: list[float]) -> float:\n \"\"\"Return the mean of the given values.\"\"\"\n```\n\n## Options\n\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n",
|
|
595
|
+
"ruff/D202": "## What it does\nChecks for docstrings on functions that are separated by one or more blank\nlines from the function body.\n\n## Why is this bad?\nRemove any blank lines between the function body and the function\ndocstring, for consistency.\n\n## Example\n```python\ndef average(values: list[float]) -> float:\n \"\"\"Return the mean of the given values.\"\"\"\n\n return sum(values) / len(values)\n```\n\nUse instead:\n```python\ndef average(values: list[float]) -> float:\n \"\"\"Return the mean of the given values.\"\"\"\n return sum(values) / len(values)\n```\n\n## Options\n\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n",
|
|
596
|
+
"ruff/D203": "## What it does\nChecks for docstrings on class definitions that are not preceded by a\nblank line.\n\n## Why is this bad?\nUse a blank line to separate the docstring from the class definition, for\nconsistency.\n\nThis rule may not apply to all projects; its applicability is a matter of\nconvention. By default, this rule is disabled when using the `google`,\n`numpy`, and `pep257` conventions.\n\nFor an alternative, see [D211].\n\n## Example\n\n```python\nclass PhotoMetadata:\n \"\"\"Metadata about a photo.\"\"\"\n```\n\nUse instead:\n\n```python\nclass PhotoMetadata:\n\n \"\"\"Metadata about a photo.\"\"\"\n```\n\n## Formatter compatibility\nWe recommend against using this rule alongside the [formatter]. The\nformatter removes blank lines before class docstrings, which conflicts\nwith this rule's requirement to include them.\n\n## Options\n- `lint.pydocstyle.convention`\n\n[D211]: https://docs.astral.sh/ruff/rules/blank-line-before-class\n[formatter]: https://docs.astral.sh/ruff/formatter\n",
|
|
597
|
+
"ruff/D204": "## What it does\nChecks for class methods that are not separated from the class's docstring\nby a blank line.\n\n## Why is this bad?\n[PEP 257] recommends the use of a blank line to separate a class's\ndocstring from its methods.\n\nThis rule may not apply to all projects; its applicability is a matter of\nconvention. By default, this rule is enabled when using the `numpy` and `pep257`\nconventions, and disabled when using the `google` convention.\n\n## Example\n```python\nclass PhotoMetadata:\n \"\"\"Metadata about a photo.\"\"\"\n def __init__(self, file: Path):\n ...\n```\n\nUse instead:\n```python\nclass PhotoMetadata:\n \"\"\"Metadata about a photo.\"\"\"\n\n def __init__(self, file: Path):\n ...\n```\n\n## Options\n- `lint.pydocstyle.convention`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n\n[PEP 257]: https://peps.python.org/pep-0257/\n",
|
|
598
|
+
"ruff/D205": "## What it does\nChecks for docstring summary lines that are not separated from the docstring\ndescription by one blank line.\n\n## Why is this bad?\n[PEP 257] recommends that multi-line docstrings consist of \"a summary line\njust like a one-line docstring, followed by a blank line, followed by a\nmore elaborate description.\"\n\n## Example\n```python\ndef sort_list(l: list[int]) -> list[int]:\n \"\"\"Return a sorted copy of the list.\n Sort the list in ascending order and return a copy of the\n result using the bubble sort algorithm.\n \"\"\"\n```\n\nUse instead:\n```python\ndef sort_list(l: list[int]) -> list[int]:\n \"\"\"Return a sorted copy of the list.\n\n Sort the list in ascending order and return a copy of the\n result using the bubble sort algorithm.\n \"\"\"\n```\n\n## Options\n\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n\n[PEP 257]: https://peps.python.org/pep-0257/\n",
|
|
599
|
+
"ruff/D206": "## What it does\nChecks for docstrings that are indented with tabs.\n\n## Why is this bad?\n[PEP 8] recommends using spaces over tabs for indentation.\n\n## Example\n```python\ndef sort_list(l: list[int]) -> list[int]:\n \"\"\"Return a sorted copy of the list.\n\n\tSort the list in ascending order and return a copy of the result using the bubble\n\tsort algorithm.\n \"\"\"\n```\n\nUse instead:\n```python\ndef sort_list(l: list[int]) -> list[int]:\n \"\"\"Return a sorted copy of the list.\n\n Sort the list in ascending order and return a copy of the result using the bubble\n sort algorithm.\n \"\"\"\n```\n\n## Formatter compatibility\nWe recommend against using this rule alongside the [formatter]. The\nformatter enforces consistent indentation, making the rule redundant.\n\nThe rule is also incompatible with the [formatter] when using\n`format.indent-style=\"tab\"`.\n\n## Options\n\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n\n[PEP 8]: https://peps.python.org/pep-0008/#tabs-or-spaces\n[formatter]: https://docs.astral.sh/ruff/formatter\n",
|
|
600
|
+
"ruff/D207": "## What it does\nChecks for under-indented docstrings.\n\n## Why is this bad?\n[PEP 257] recommends that docstrings be indented to the same level as their\nopening quotes. Avoid under-indenting docstrings, for consistency.\n\n## Example\n```python\ndef sort_list(l: list[int]) -> list[int]:\n \"\"\"Return a sorted copy of the list.\n\nSort the list in ascending order and return a copy of the result using the bubble sort\nalgorithm.\n \"\"\"\n```\n\nUse instead:\n```python\ndef sort_list(l: list[int]) -> list[int]:\n \"\"\"Return a sorted copy of the list.\n\n Sort the list in ascending order and return a copy of the result using the bubble\n sort algorithm.\n \"\"\"\n```\n\n## Formatter compatibility\nWe recommend against using this rule alongside the [formatter]. The\nformatter enforces consistent indentation, making the rule redundant.\n\n## Options\n\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n\n[PEP 257]: https://peps.python.org/pep-0257/\n[formatter]: https://docs.astral.sh/ruff/formatter/\n",
|
|
601
|
+
"ruff/D208": "## What it does\nChecks for over-indented docstrings.\n\n## Why is this bad?\n[PEP 257] recommends that docstrings be indented to the same level as their\nopening quotes. Avoid over-indenting docstrings, for consistency.\n\n## Example\n```python\ndef sort_list(l: list[int]) -> list[int]:\n \"\"\"Return a sorted copy of the list.\n\n Sort the list in ascending order and return a copy of the result using the\n bubble sort algorithm.\n \"\"\"\n```\n\nUse instead:\n```python\ndef sort_list(l: list[int]) -> list[int]:\n \"\"\"Return a sorted copy of the list.\n\n Sort the list in ascending order and return a copy of the result using the bubble\n sort algorithm.\n \"\"\"\n```\n\n## Formatter compatibility\nWe recommend against using this rule alongside the [formatter]. The\nformatter enforces consistent indentation, making the rule redundant.\n\n## Options\n\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n\n[PEP 257]: https://peps.python.org/pep-0257/\n[formatter]:https://docs.astral.sh/ruff/formatter/\n",
|
|
602
|
+
"ruff/D209": "## What it does\nChecks for multi-line docstrings whose closing quotes are not on their\nown line.\n\n## Why is this bad?\n[PEP 257] recommends that the closing quotes of a multi-line docstring be\non their own line, for consistency and compatibility with documentation\ntools that may need to parse the docstring.\n\n## Example\n```python\ndef sort_list(l: List[int]) -> List[int]:\n \"\"\"Return a sorted copy of the list.\n\n Sort the list in ascending order and return a copy of the result using the\n bubble sort algorithm.\"\"\"\n```\n\nUse instead:\n```python\ndef sort_list(l: List[int]) -> List[int]:\n \"\"\"Return a sorted copy of the list.\n\n Sort the list in ascending order and return a copy of the result using the bubble\n sort algorithm.\n \"\"\"\n```\n\n## Options\n\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n\n[PEP 257]: https://peps.python.org/pep-0257/\n",
|
|
603
|
+
"ruff/D210": "## What it does\nChecks for surrounding whitespace in docstrings.\n\n## Why is this bad?\nRemove surrounding whitespace from the docstring, for consistency.\n\n## Example\n```python\ndef factorial(n: int) -> int:\n \"\"\" Return the factorial of n. \"\"\"\n```\n\nUse instead:\n```python\ndef factorial(n: int) -> int:\n \"\"\"Return the factorial of n.\"\"\"\n```\n\n## Options\n\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n",
|
|
604
|
+
"ruff/D211": "## What it does\nChecks for docstrings on class definitions that are preceded by a blank\nline.\n\n## Why is this bad?\nAvoid introducing any blank lines between a class definition and its\ndocstring, for consistency.\n\nThis rule may not apply to all projects; its applicability is a matter of\nconvention. By default, this rule is enabled when using the `google`,\n`numpy`, and `pep257` conventions.\n\nFor an alternative, see [D203].\n\n## Example\n\n```python\nclass PhotoMetadata:\n\n \"\"\"Metadata about a photo.\"\"\"\n```\n\nUse instead:\n\n```python\nclass PhotoMetadata:\n \"\"\"Metadata about a photo.\"\"\"\n```\n\n## Options\n- `lint.pydocstyle.convention`\n\n[D203]: https://docs.astral.sh/ruff/rules/incorrect-blank-line-before-class\n",
|
|
605
|
+
"ruff/D212": "## What it does\nChecks for docstring summary lines that are not positioned on the first\nphysical line of the docstring.\n\n## Why is this bad?\n[PEP 257] recommends that multi-line docstrings consist of \"a summary line\njust like a one-line docstring, followed by a blank line, followed by a\nmore elaborate description.\"\n\nThe summary line should be located on the first physical line of the\ndocstring, immediately after the opening quotes.\n\nThis rule may not apply to all projects; its applicability is a matter of\nconvention. By default, this rule is enabled when using the `google`\nconvention, and disabled when using the `numpy` and `pep257` conventions.\n\nFor an alternative, see [D213].\n\n## Example\n```python\ndef sort_list(l: list[int]) -> list[int]:\n \"\"\"\n Return a sorted copy of the list.\n\n Sort the list in ascending order and return a copy of the result using the\n bubble sort algorithm.\n \"\"\"\n```\n\nUse instead:\n```python\ndef sort_list(l: list[int]) -> list[int]:\n \"\"\"Return a sorted copy of the list.\n\n Sort the list in ascending order and return a copy of the result using the bubble\n sort algorithm.\n \"\"\"\n```\n\n## Options\n- `lint.pydocstyle.convention`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n\n[D213]: https://docs.astral.sh/ruff/rules/multi-line-summary-second-line\n[PEP 257]: https://peps.python.org/pep-0257\n",
|
|
606
|
+
"ruff/D213": "## What it does\nChecks for docstring summary lines that are not positioned on the second\nphysical line of the docstring.\n\n## Why is this bad?\n[PEP 257] recommends that multi-line docstrings consist of \"a summary line\njust like a one-line docstring, followed by a blank line, followed by a\nmore elaborate description.\"\n\nThe summary line should be located on the second physical line of the\ndocstring, immediately after the opening quotes and the blank line.\n\nThis rule may not apply to all projects; its applicability is a matter of\nconvention. By default, this rule is disabled when using the `google`,\n`numpy`, and `pep257` conventions.\n\nFor an alternative, see [D212].\n\n## Example\n```python\ndef sort_list(l: list[int]) -> list[int]:\n \"\"\"Return a sorted copy of the list.\n\n Sort the list in ascending order and return a copy of the result using the\n bubble sort algorithm.\n \"\"\"\n```\n\nUse instead:\n```python\ndef sort_list(l: list[int]) -> list[int]:\n \"\"\"\n Return a sorted copy of the list.\n\n Sort the list in ascending order and return a copy of the result using the bubble\n sort algorithm.\n \"\"\"\n```\n\n## Options\n- `lint.pydocstyle.convention`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n\n[D212]: https://docs.astral.sh/ruff/rules/multi-line-summary-first-line\n[PEP 257]: https://peps.python.org/pep-0257\n",
|
|
607
|
+
"ruff/D214": "## What it does\nChecks for over-indented sections in docstrings.\n\n## Why is this bad?\nThis rule enforces a consistent style for docstrings with multiple\nsections.\n\nMultiline docstrings are typically composed of a summary line, followed by\na blank line, followed by a series of sections, each with a section header\nand a section body. The convention is that all sections should use\nconsistent indentation. In each section, the header should match the\nindentation of the docstring's opening quotes, and the body should be\nindented one level further.\n\nThis rule is enabled when using the `numpy` and `google` conventions, and\ndisabled when using the `pep257` convention.\n\n## Example\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Args:\n distance: Distance traveled.\n time: Time spent traveling.\n\n Returns:\n Speed as distance divided by time.\n\n Raises:\n FasterThanLightError: If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\nUse instead:\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Args:\n distance: Distance traveled.\n time: Time spent traveling.\n\n Returns:\n Speed as distance divided by time.\n\n Raises:\n FasterThanLightError: If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\n## Options\n- `lint.pydocstyle.convention`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n",
|
|
608
|
+
"ruff/D215": "## What it does\nChecks for over-indented section underlines in docstrings.\n\n## Why is this bad?\nThis rule enforces a consistent style for multiline numpy-style docstrings,\nand helps prevent incorrect syntax in docstrings using reStructuredText.\n\nMultiline numpy-style docstrings are typically composed of a summary line,\nfollowed by a blank line, followed by a series of sections. Each section\nhas a section header and a section body, and there should be a series of\nunderline characters in the line following the header. The underline should\nhave the same indentation as the header.\n\nThis rule enforces a consistent style for multiline numpy-style docstrings\nwith sections. If your docstring uses reStructuredText, the rule also\nhelps protect against incorrect reStructuredText syntax, which would cause\nerrors if you tried to use a tool such as Sphinx to generate documentation\nfrom the docstring.\n\nThis rule is enabled when using the `numpy` convention, and disabled when\nusing the `google` or `pep257` conventions.\n\n## Example\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Parameters\n ----------\n distance : float\n Distance traveled.\n time : float\n Time spent traveling.\n\n Returns\n -------\n float\n Speed as distance divided by time.\n\n Raises\n ------\n FasterThanLightError\n If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\nUse instead:\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Parameters\n ----------\n distance : float\n Distance traveled.\n time : float\n Time spent traveling.\n\n Returns\n -------\n float\n Speed as distance divided by time.\n\n Raises\n ------\n FasterThanLightError\n If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\n## Options\n- `lint.pydocstyle.convention`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n",
|
|
609
|
+
"ruff/D300": "## What it does\nChecks for docstrings that don't use `\"\"\"triple double quotes\"\"\"`.\n\n## Why is this bad?\n[PEP 257](https://peps.python.org/pep-0257/#what-is-a-docstring) recommends\nthe use of `\"\"\"triple double quotes\"\"\"` for docstrings, to ensure\nconsistency.\n\n## Example\n```python\ndef kos_root():\n '''Return the pathname of the KOS root directory.'''\n\ndef kos_branch():\n 'Return the branch name.'\n```\n\nUse instead:\n```python\ndef kos_root():\n \"\"\"Return the pathname of the KOS root directory.\"\"\"\n\ndef kos_branch():\n \"\"\"Return the branch name.\"\"\"\n```\n\n## Formatter compatibility\nWe recommend against using this rule alongside the [formatter]. The\nformatter enforces consistent quotes, making the rule redundant.\n\n## Options\n\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n\n[formatter]: https://docs.astral.sh/ruff/formatter/\n",
|
|
610
|
+
"ruff/D301": "## What it does\nChecks for docstrings that include backslashes, but are not defined as\nraw string literals.\n\n## Why is this bad?\nIn Python, backslashes are typically used to escape characters in strings.\nIn raw strings (those prefixed with an `r`), however, backslashes are\ntreated as literal characters.\n\n[PEP 257](https://peps.python.org/pep-0257/#what-is-a-docstring) recommends\nthe use of raw strings (i.e., `r\"\"\"raw triple double quotes\"\"\"`) for\ndocstrings that include backslashes. The use of a raw string ensures that\nany backslashes are treated as literal characters, and not as escape\nsequences, which avoids confusion.\n\n## Example\n```python\ndef foobar():\n \"\"\"Docstring for foo\\bar.\"\"\"\n\n\nfoobar.__doc__ # \"Docstring for foar.\"\n```\n\nUse instead:\n```python\ndef foobar():\n r\"\"\"Docstring for foo\\bar.\"\"\"\n\n\nfoobar.__doc__ # \"Docstring for foo\\bar.\"\n```\n\n## Options\n\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [Python documentation: String and Bytes literals](https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals)\n",
|
|
611
|
+
"ruff/D400": "## What it does\nChecks for docstrings in which the first line does not end in a period.\n\n## Why is this bad?\n[PEP 257] recommends that the first line of a docstring is written in the\nform of a command, ending in a period.\n\nThis rule may not apply to all projects; its applicability is a matter of\nconvention. By default, this rule is enabled when using the `numpy` and\n`pep257` conventions, and disabled when using the `google` convention.\n\n## Example\n```python\ndef average(values: list[float]) -> float:\n \"\"\"Return the mean of the given values\"\"\"\n```\n\nUse instead:\n```python\ndef average(values: list[float]) -> float:\n \"\"\"Return the mean of the given values.\"\"\"\n```\n\n## Fix safety\nThis fix is marked as unsafe, as it may alter the intended formatting of the\ndocstring, or affect tools that parse docstrings and rely on specific\nformatting.\n\n## Options\n- `lint.pydocstyle.convention`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n\n[PEP 257]: https://peps.python.org/pep-0257/\n",
|
|
612
|
+
"ruff/D401": "## What it does\nChecks for docstring first lines that are not in an imperative mood.\n\n## Why is this bad?\n[PEP 257] recommends that the first line of a docstring be written in the\nimperative mood, for consistency.\n\nHint: to rewrite the docstring in the imperative, phrase the first line as\nif it were a command.\n\nThis rule may not apply to all projects; its applicability is a matter of\nconvention. By default, this rule is enabled when using the `numpy` and\n`pep257` conventions, and disabled when using the `google` conventions.\n\n## Example\n```python\ndef average(values: list[float]) -> float:\n \"\"\"Returns the mean of the given values.\"\"\"\n```\n\nUse instead:\n```python\ndef average(values: list[float]) -> float:\n \"\"\"Return the mean of the given values.\"\"\"\n```\n\n## Options\n- `lint.pydocstyle.convention`\n- `lint.pydocstyle.property-decorators`\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n\n[PEP 257]: https://peps.python.org/pep-0257/\n",
|
|
613
|
+
"ruff/D402": "## What it does\nChecks for function docstrings that include the function's signature in\nthe summary line.\n\n## Why is this bad?\n[PEP 257] recommends against including a function's signature in its\ndocstring. Instead, consider using type annotations as a form of\ndocumentation for the function's parameters and return value.\n\nThis rule may not apply to all projects; its applicability is a matter of\nconvention. By default, this rule is enabled when using the `google` and\n`pep257` conventions, and disabled when using the `numpy` convention.\n\n## Example\n```python\ndef foo(a, b):\n \"\"\"foo(a: int, b: int) -> list[int]\"\"\"\n```\n\nUse instead:\n```python\ndef foo(a: int, b: int) -> list[int]:\n \"\"\"Return a list of a and b.\"\"\"\n```\n\n## Options\n- `lint.pydocstyle.convention`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n\n[PEP 257]: https://peps.python.org/pep-0257/\n",
|
|
614
|
+
"ruff/D403": "## What it does\nChecks for docstrings that do not start with a capital letter.\n\n## Why is this bad?\nThe first non-whitespace character in a docstring should be\ncapitalized for grammatical correctness and consistency.\n\n## Example\n```python\ndef average(values: list[float]) -> float:\n \"\"\"return the mean of the given values.\"\"\"\n```\n\nUse instead:\n```python\ndef average(values: list[float]) -> float:\n \"\"\"Return the mean of the given values.\"\"\"\n```\n\n## Options\n\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n",
|
|
615
|
+
"ruff/D404": "## What it does\nChecks for docstrings that start with `This`.\n\n## Why is this bad?\n[PEP 257] recommends that the first line of a docstring be written in the\nimperative mood, for consistency.\n\nHint: to rewrite the docstring in the imperative, phrase the first line as\nif it were a command.\n\nThis rule may not apply to all projects; its applicability is a matter of\nconvention. By default, this rule is enabled when using the `numpy`\nconvention, and disabled when using the `google` and `pep257` conventions.\n\n## Example\n```python\ndef average(values: list[float]) -> float:\n \"\"\"This function returns the mean of the given values.\"\"\"\n```\n\nUse instead:\n```python\ndef average(values: list[float]) -> float:\n \"\"\"Return the mean of the given values.\"\"\"\n```\n\n## Options\n- `lint.pydocstyle.convention`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n\n[PEP 257]: https://peps.python.org/pep-0257/\n",
|
|
616
|
+
"ruff/D405": "## What it does\nChecks for section headers in docstrings that do not begin with capital\nletters.\n\n## Why is this bad?\nFor stylistic consistency, all section headers in a docstring should be\ncapitalized.\n\nMultiline docstrings are typically composed of a summary line, followed by\na blank line, followed by a series of sections. Each section typically has\na header and a body.\n\nThis rule is enabled when using the `numpy` and `google` conventions, and\ndisabled when using the `pep257` convention.\n\n## Example\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n args:\n distance: Distance traveled.\n time: Time spent traveling.\n\n returns:\n Speed as distance divided by time.\n\n raises:\n FasterThanLightError: If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\nUse instead:\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Args:\n distance: Distance traveled.\n time: Time spent traveling.\n\n Returns:\n Speed as distance divided by time.\n\n Raises:\n FasterThanLightError: If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\n## Options\n- `lint.pydocstyle.convention`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n",
|
|
617
|
+
"ruff/D406": "## What it does\nChecks for section headers in docstrings that are followed by non-newline\ncharacters.\n\n## Why is this bad?\nThis rule enforces a consistent style for multiline numpy-style docstrings.\n\nMultiline numpy-style docstrings are typically composed of a summary line,\nfollowed by a blank line, followed by a series of sections. Each section\nhas a section header and a section body. The section header should be\nfollowed by a newline, rather than by some other character (like a colon).\n\nThis rule is enabled when using the `numpy` convention, and disabled\nwhen using the `google` or `pep257` conventions.\n\n## Example\n```python\n# The `Parameters`, `Returns` and `Raises` section headers are all followed\n# by a colon in this function's docstring:\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Parameters:\n -----------\n distance : float\n Distance traveled.\n time : float\n Time spent traveling.\n\n Returns:\n --------\n float\n Speed as distance divided by time.\n\n Raises:\n -------\n FasterThanLightError\n If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\nUse instead:\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Parameters\n ----------\n distance : float\n Distance traveled.\n time : float\n Time spent traveling.\n\n Returns\n -------\n float\n Speed as distance divided by time.\n\n Raises\n ------\n FasterThanLightError\n If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\n## Options\n- `lint.pydocstyle.convention`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n",
|
|
618
|
+
"ruff/D407": "## What it does\nChecks for section headers in docstrings that are not followed by\nunderlines.\n\n## Why is this bad?\nThis rule enforces a consistent style for multiline numpy-style docstrings,\nand helps prevent incorrect syntax in docstrings using reStructuredText.\n\nMultiline numpy-style docstrings are typically composed of a summary line,\nfollowed by a blank line, followed by a series of sections. Each section\nhas a section header and a section body, and the header should be followed\nby a series of underline characters in the following line.\n\nThis rule enforces a consistent style for multiline numpy-style docstrings\nwith sections. If your docstring uses reStructuredText, the rule also\nhelps protect against incorrect reStructuredText syntax, which would cause\nerrors if you tried to use a tool such as Sphinx to generate documentation\nfrom the docstring.\n\nThis rule is enabled when using the `numpy` convention, and disabled\nwhen using the `google` or `pep257` conventions.\n\n## Example\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Parameters\n\n distance : float\n Distance traveled.\n time : float\n Time spent traveling.\n\n Returns\n\n float\n Speed as distance divided by time.\n\n Raises\n\n FasterThanLightError\n If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\nUse instead:\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Parameters\n ----------\n distance : float\n Distance traveled.\n time : float\n Time spent traveling.\n\n Returns\n -------\n float\n Speed as distance divided by time.\n\n Raises\n ------\n FasterThanLightError\n If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\n## Options\n- `lint.pydocstyle.convention`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n",
|
|
619
|
+
"ruff/D408": "## What it does\nChecks for section underlines in docstrings that are not on the line\nimmediately following the section name.\n\n## Why is this bad?\nThis rule enforces a consistent style for multiline numpy-style docstrings,\nand helps prevent incorrect syntax in docstrings using reStructuredText.\n\nMultiline numpy-style docstrings are typically composed of a summary line,\nfollowed by a blank line, followed by a series of sections. Each section\nhas a header and a body. There should be a series of underline characters\nin the line immediately below the header.\n\nThis rule enforces a consistent style for multiline numpy-style docstrings\nwith sections. If your docstring uses reStructuredText, the rule also\nhelps protect against incorrect reStructuredText syntax, which would cause\nerrors if you tried to use a tool such as Sphinx to generate documentation\nfrom the docstring.\n\nThis rule is enabled when using the `numpy` convention, and disabled\nwhen using the `google` or `pep257` conventions.\n\n## Example\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Parameters\n\n ----------\n distance : float\n Distance traveled.\n time : float\n Time spent traveling.\n\n Returns\n\n -------\n float\n Speed as distance divided by time.\n\n Raises\n\n ------\n FasterThanLightError\n If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\nUse instead:\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Parameters\n ----------\n distance : float\n Distance traveled.\n time : float\n Time spent traveling.\n\n Returns\n -------\n float\n Speed as distance divided by time.\n\n Raises\n ------\n FasterThanLightError\n If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\n## Options\n- `lint.pydocstyle.convention`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n",
|
|
620
|
+
"ruff/D409": "## What it does\nChecks for section underlines in docstrings that do not match the length of\nthe corresponding section header.\n\n## Why is this bad?\nThis rule enforces a consistent style for multiline numpy-style docstrings,\nand helps prevent incorrect syntax in docstrings using reStructuredText.\n\nMultiline numpy-style docstrings are typically composed of a summary line,\nfollowed by a blank line, followed by a series of sections. Each section\nhas a section header and a section body, and there should be a series of\nunderline characters in the line following the header. The length of the\nunderline should exactly match the length of the section header.\n\nThis rule enforces a consistent style for multiline numpy-style docstrings\nwith sections. If your docstring uses reStructuredText, the rule also\nhelps protect against incorrect reStructuredText syntax, which would cause\nerrors if you tried to use a tool such as Sphinx to generate documentation\nfrom the docstring.\n\nThis rule is enabled when using the `numpy` convention, and disabled\nwhen using the `google` or `pep257` conventions.\n\n## Example\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Parameters\n ---\n distance : float\n Distance traveled.\n time : float\n Time spent traveling.\n\n Returns\n ---\n float\n Speed as distance divided by time.\n\n Raises\n ---\n FasterThanLightError\n If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\nUse instead:\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Parameters\n ----------\n distance : float\n Distance traveled.\n time : float\n Time spent traveling.\n\n Returns\n -------\n float\n Speed as distance divided by time.\n\n Raises\n ------\n FasterThanLightError\n If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\n## Options\n- `lint.pydocstyle.convention`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n",
|
|
621
|
+
"ruff/D410": "## What it does\nChecks for docstring sections that are not separated by a single blank\nline.\n\n## Why is this bad?\nThis rule enforces consistency in your docstrings, and helps ensure\ncompatibility with documentation tooling.\n\nMultiline docstrings are typically composed of a summary line, followed by\na blank line, followed by a series of sections, each with a section header\nand a section body. If a multiline numpy-style or Google-style docstring\nconsists of multiple sections, each section should be separated by a single\nblank line.\n\nThis rule is enabled when using the `numpy` and `google` conventions, and\ndisabled when using the `pep257` convention.\n\n## Example\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Parameters\n ----------\n distance : float\n Distance traveled.\n time : float\n Time spent traveling.\n Returns\n -------\n float\n Speed as distance divided by time.\n Raises\n ------\n FasterThanLightError\n If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\nUse instead:\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Parameters\n ----------\n distance : float\n Distance traveled.\n time : float\n Time spent traveling.\n\n Returns\n -------\n float\n Speed as distance divided by time.\n\n Raises\n ------\n FasterThanLightError\n If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\n## Options\n- `lint.pydocstyle.convention`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Style Guide](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n",
|
|
622
|
+
"ruff/D411": "## What it does\nChecks for docstring sections that are not separated by a blank line.\n\n## Why is this bad?\nThis rule enforces consistency in numpy-style and Google-style docstrings,\nand helps ensure compatibility with documentation tooling.\n\nMultiline docstrings are typically composed of a summary line, followed by\na blank line, followed by a series of sections, each with a section header\nand a section body. Sections should be separated by a single blank line.\n\nThis rule is enabled when using the `numpy` and `google` conventions, and\ndisabled when using the `pep257` convention.\n\n## Example\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Parameters\n ----------\n distance : float\n Distance traveled.\n time : float\n Time spent traveling.\n Returns\n -------\n float\n Speed as distance divided by time.\n Raises\n ------\n FasterThanLightError\n If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\nUse instead:\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Parameters\n ----------\n distance : float\n Distance traveled.\n time : float\n Time spent traveling.\n\n Returns\n -------\n float\n Speed as distance divided by time.\n\n Raises\n ------\n FasterThanLightError\n If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\n## Options\n- `lint.pydocstyle.convention`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n",
|
|
623
|
+
"ruff/D412": "## What it does\nChecks for docstring sections that contain blank lines between a section\nheader and a section body.\n\n## Why is this bad?\nThis rule enforces a consistent style for multiline docstrings.\n\nMultiline docstrings are typically composed of a summary line, followed by\na blank line, followed by a series of sections, each with a section header\nand a section body. There should be no blank lines between a section header\nand a section body.\n\n## Example\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Args:\n\n distance: Distance traveled.\n time: Time spent traveling.\n\n Returns:\n Speed as distance divided by time.\n\n Raises:\n FasterThanLightError: If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\nUse instead:\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Args:\n distance: Distance traveled.\n time: Time spent traveling.\n\n Returns:\n Speed as distance divided by time.\n\n Raises:\n FasterThanLightError: If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\n## Options\n\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n",
|
|
624
|
+
"ruff/D413": "## What it does\nChecks for missing blank lines after the last section of a multiline\ndocstring.\n\n## Why is this bad?\nThis rule enforces a consistent style for multiline docstrings.\n\nMultiline docstrings are typically composed of a summary line, followed by\na blank line, followed by a series of sections, each with a section header\nand a section body.\n\nThis rule may not apply to all projects; its applicability is a matter of\nconvention. By default, the rule is disabled when using the `google`,\n`numpy`, and `pep257` conventions.\n\n## Example\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Parameters\n ----------\n distance : float\n Distance traveled.\n time : float\n Time spent traveling.\n Returns\n -------\n float\n Speed as distance divided by time.\n Raises\n ------\n FasterThanLightError\n If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\nUse instead:\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Parameters\n ----------\n distance : float\n Distance traveled.\n time : float\n Time spent traveling.\n\n Returns\n -------\n float\n Speed as distance divided by time.\n\n Raises\n ------\n FasterThanLightError\n If speed is greater than the speed of light.\n\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\n## Options\n- `lint.pydocstyle.convention`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n",
|
|
625
|
+
"ruff/D414": "## What it does\nChecks for docstrings with empty sections.\n\n## Why is this bad?\nAn empty section in a multiline docstring likely indicates an unfinished\nor incomplete docstring.\n\nMultiline docstrings are typically composed of a summary line, followed by\na blank line, followed by a series of sections, each with a section header\nand a section body. Each section body should be non-empty; empty sections\nshould either have content added to them, or be removed entirely.\n\n## Example\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Parameters\n ----------\n distance : float\n Distance traveled.\n time : float\n Time spent traveling.\n\n Returns\n -------\n float\n Speed as distance divided by time.\n\n Raises\n ------\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\nUse instead:\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Parameters\n ----------\n distance : float\n Distance traveled.\n time : float\n Time spent traveling.\n\n Returns\n -------\n float\n Speed as distance divided by time.\n\n Raises\n ------\n FasterThanLightError\n If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\n## Options\n\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Style Guide](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n",
|
|
626
|
+
"ruff/D415": "## What it does\nChecks for docstrings in which the first line does not end in a punctuation\nmark, such as a period, question mark, or exclamation point.\n\n## Why is this bad?\nThe first line of a docstring should end with a period, question mark, or\nexclamation point, for grammatical correctness and consistency.\n\nThis rule may not apply to all projects; its applicability is a matter of\nconvention. By default, this rule is enabled when using the `google`\nconvention, and disabled when using the `numpy` and `pep257` conventions.\n\n## Example\n```python\ndef average(values: list[float]) -> float:\n \"\"\"Return the mean of the given values\"\"\"\n```\n\nUse instead:\n```python\ndef average(values: list[float]) -> float:\n \"\"\"Return the mean of the given values.\"\"\"\n```\n\n## Options\n- `lint.pydocstyle.convention`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n",
|
|
627
|
+
"ruff/D416": "## What it does\nChecks for docstring section headers that do not end with a colon.\n\n## Why is this bad?\nThis rule enforces a consistent style for multiline Google-style\ndocstrings. If a multiline Google-style docstring consists of multiple\nsections, each section header should end with a colon.\n\nMultiline docstrings are typically composed of a summary line, followed by\na blank line, followed by a series of sections, each with a section header\nand a section body.\n\nThis rule is enabled when using the `google` convention, and disabled when\nusing the `pep257` and `numpy` conventions.\n\n## Example\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Args\n distance: Distance traveled.\n time: Time spent traveling.\n\n Returns\n Speed as distance divided by time.\n\n Raises\n FasterThanLightError: If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\nUse instead:\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Args:\n distance: Distance traveled.\n time: Time spent traveling.\n\n Returns:\n Speed as distance divided by time.\n\n Raises:\n FasterThanLightError: If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\n## Options\n- `lint.pydocstyle.convention`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [Google Style Guide](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n",
|
|
628
|
+
"ruff/D417": "## What it does\nChecks for function docstrings that do not include documentation for all\nparameters in the function.\n\n## Why is this bad?\nThis rule helps prevent you from leaving Google-style docstrings unfinished\nor incomplete. Multiline Google-style docstrings should describe all\nparameters for the function they are documenting.\n\nMultiline docstrings are typically composed of a summary line, followed by\na blank line, followed by a series of sections, each with a section header\nand a section body. Function docstrings often include a section for\nfunction arguments; this rule is concerned with that section only.\nNote that this rule only checks docstrings with an arguments (e.g. `Args`) section.\n\nThis rule is enabled when using the `google` convention, and disabled when\nusing the `pep257` and `numpy` conventions.\n\nParameters annotated with `typing.Unpack` are exempt from this rule.\nThis follows the Python typing specification for unpacking keyword arguments.\n\n## Example\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Args:\n distance: Distance traveled.\n\n Returns:\n Speed as distance divided by time.\n\n Raises:\n FasterThanLightError: If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\nUse instead:\n```python\ndef calculate_speed(distance: float, time: float) -> float:\n \"\"\"Calculate speed as distance divided by time.\n\n Args:\n distance: Distance traveled.\n time: Time spent traveling.\n\n Returns:\n Speed as distance divided by time.\n\n Raises:\n FasterThanLightError: If speed is greater than the speed of light.\n \"\"\"\n try:\n return distance / time\n except ZeroDivisionError as exc:\n raise FasterThanLightError from exc\n```\n\n## Options\n- `lint.pydocstyle.convention`\n- `lint.pydocstyle.ignore-var-parameters`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [PEP 287 \u2013 reStructuredText Docstring Format](https://peps.python.org/pep-0287/)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n- [Python - Unpack for keyword arguments](https://typing.python.org/en/latest/spec/callables.html#unpack-kwargs)\n",
|
|
629
|
+
"ruff/D418": "## What it does\nChecks for `@overload` function definitions that contain a docstring.\n\n## Why is this bad?\nThe `@overload` decorator is used to define multiple compatible signatures\nfor a given function, to support type-checking. A series of `@overload`\ndefinitions should be followed by a single non-decorated definition that\ncontains the implementation of the function.\n\n`@overload` function definitions should not contain a docstring; instead,\nthe docstring should be placed on the non-decorated definition that contains\nthe implementation.\n\nThis rule does not apply to stub files, which don't contain implementations.\n\n## Example\n\n```python\nfrom typing import overload\n\n\n@overload\ndef factorial(n: int) -> int:\n \"\"\"Return the factorial of n.\"\"\"\n\n\n@overload\ndef factorial(n: float) -> float:\n \"\"\"Return the factorial of n.\"\"\"\n\n\ndef factorial(n):\n \"\"\"Return the factorial of n.\"\"\"\n\n\nfactorial.__doc__ # \"Return the factorial of n.\"\n```\n\nUse instead:\n\n```python\nfrom typing import overload\n\n\n@overload\ndef factorial(n: int) -> int: ...\n\n\n@overload\ndef factorial(n: float) -> float: ...\n\n\ndef factorial(n):\n \"\"\"Return the factorial of n.\"\"\"\n\n\nfactorial.__doc__ # \"Return the factorial of n.\"\n```\n\n## Options\n\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [Python documentation: `typing.overload`](https://docs.python.org/3/library/typing.html#typing.overload)\n",
|
|
630
|
+
"ruff/D419": "## What it does\nChecks for empty docstrings.\n\n## Why is this bad?\nAn empty docstring is indicative of incomplete documentation. It should either\nbe removed or replaced with a meaningful docstring.\n\n## Example\n```python\ndef average(values: list[float]) -> float:\n \"\"\"\"\"\"\n```\n\nUse instead:\n```python\ndef average(values: list[float]) -> float:\n \"\"\"Return the mean of the given values.\"\"\"\n```\n\n## Options\n\n- `lint.pydocstyle.ignore-decorators`\n\n## References\n- [PEP 257 \u2013 Docstring Conventions](https://peps.python.org/pep-0257/)\n- [NumPy Style Guide](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide - Docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)\n",
|
|
631
|
+
"ruff/D420": "## What it does\nChecks for docstring sections that appear out of order.\n\n## Why is this bad?\nDocstring sections should follow the canonical ordering specified by the\ndocstring convention (NumPy or Google). Consistent ordering makes\ndocstrings easier to read and navigate.\n\nFor the NumPy convention, all sections have a prescribed order per the\nnumpydoc style guide. For the Google convention, only the relative ordering\nof `Args`, `Returns`/`Yields`, and `Raises` is enforced; all other sections\nare unordered.\n\n## Example\n\nGiven `lint.pydocstyle.convention = \"numpy\"`:\n\n```python\ndef func() -> int:\n \"\"\"Summary.\n\n Notes\n -----\n Some notes.\n\n Returns\n -------\n int\n \"\"\"\n```\n\nUse instead:\n```python\ndef func() -> int:\n \"\"\"Summary.\n\n Returns\n -------\n int\n\n Notes\n -----\n Some notes.\n \"\"\"\n```\n\nGiven `lint.pydocstyle.convention = \"google\"`:\n\n```python\ndef func(x: int) -> int:\n \"\"\"Summary.\n\n Returns:\n int\n\n Args:\n x: Description.\n \"\"\"\n```\n\nUse instead:\n```python\ndef func(x: int) -> int:\n \"\"\"Summary.\n\n Args:\n x: Description.\n\n Returns:\n int\n \"\"\"\n```\n\n## Options\n- `lint.pydocstyle.convention`\n\n## References\n- [NumPy docstring standard](https://numpydoc.readthedocs.io/en/latest/format.html)\n- [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html#383-functions-and-methods)\n",
|
|
632
|
+
"ruff/D421": "## What it does\nChecks for `@property` method docstrings that start with known verbs\n(e.g., \"returns\", \"gets\", etc).\n\n## Why is this bad?\nThe [Google Python style guide] recommends that the docstring for a\n`@property` data descriptor use the same style as the docstring for an\nattribute or a function argument (e.g., `\"\"\"The Bigtable path.\"\"\"`),\nrather than a function-style docstring (e.g.,\n`\"\"\"Returns the Bigtable path.\"\"\"`).\n\n## Example\n```python\nclass Foo:\n @property\n def bar(self) -> str:\n \"\"\"Returns the bar.\"\"\"\n return self._bar\n```\n\nUse instead:\n```python\nclass Foo:\n @property\n def bar(self) -> str:\n \"\"\"The bar.\"\"\"\n return self._bar\n```\n\n## Options\n- `lint.pydocstyle.property-decorators`\n\n## References\n- [Google Python Style Guide \u2013 Properties](https://google.github.io/styleguide/pyguide.html#383-functions-and-methods)\n\n[Google Python style guide]: https://google.github.io/styleguide/pyguide.html#383-functions-and-methods\n",
|
|
633
|
+
"ruff/F401": "## What it does\nChecks for unused imports.\n\n## Why is this bad?\nUnused imports add a performance overhead at runtime, and risk creating\nimport cycles. They also increase the cognitive load of reading the code.\n\nIf an import statement is used to check for the availability or existence\nof a module, consider using `importlib.util.find_spec` instead.\n\nIf an import statement is used to re-export a symbol as part of a module's\npublic interface, consider using a \"redundant\" import alias, which\ninstructs Ruff (and other tools) to respect the re-export, and avoid\nmarking it as unused, as in:\n\n```python\nfrom module import member as member\n```\n\nAlternatively, you can use `__all__` to declare a symbol as part of the module's\ninterface, as in:\n\n```python\n# __init__.py\nimport some_module\n\n__all__ = [\"some_module\"]\n```\n\n## Preview\nWhen [preview] is enabled (and certain simplifying assumptions\nare met), we analyze all import statements for a given module\nwhen determining whether an import is used, rather than simply\nthe last of these statements. This can result in both different and\nmore import statements being marked as unused.\n\nFor example, if a module consists of\n\n```python\nimport a\nimport a.b\n```\n\nthen both statements are marked as unused under [preview], whereas\nonly the second is marked as unused under stable behavior.\n\nAs another example, if a module consists of\n\n```python\nimport a.b\nimport a\n\na.b.foo()\n```\n\nthen a diagnostic will be emitted for the second line under [preview],\nwhereas no diagnostic is emitted under stable behavior.\n\nNote that this behavior is somewhat subjective and is designed\nto conform to the developer's intuition rather than Python's actual\nexecution. To wit, the statement `import a.b` automatically executes\n`import a`, so in some sense `import a` is _always_ redundant\nin the presence of `import a.b`.\n\n\n## Fix safety\n\nFixes to remove unused imports are safe, except in `__init__.py` files.\n\nApplying fixes to `__init__.py` files is currently in preview. The fix offered depends on the\ntype of the unused import. Ruff will suggest a safe fix to export first-party imports with\neither a redundant alias or, if already present in the file, an `__all__` entry. If multiple\n`__all__` declarations are present, Ruff will not offer a fix. Ruff will suggest an unsafe fix\nto remove third-party and standard library imports -- the fix is unsafe because the module's\ninterface changes.\n\nSee [this FAQ section](https://docs.astral.sh/ruff/faq/#how-does-ruff-determine-which-of-my-imports-are-first-party-third-party-etc)\nfor more details on how Ruff\ndetermines whether an import is first or third-party.\n\n## Example\n\n```python\nimport numpy as np # unused import\n\n\ndef area(radius):\n return 3.14 * radius**2\n```\n\nUse instead:\n\n```python\ndef area(radius):\n return 3.14 * radius**2\n```\n\nTo check the availability of a module, use `importlib.util.find_spec`:\n\n```python\nfrom importlib.util import find_spec\n\nif find_spec(\"numpy\") is not None:\n print(\"numpy is installed\")\nelse:\n print(\"numpy is not installed\")\n```\n\n## Options\n- `lint.ignore-init-module-imports`\n- `lint.pyflakes.allowed-unused-imports`\n\n## References\n- [Python documentation: `import`](https://docs.python.org/3/reference/simple_stmts.html#the-import-statement)\n- [Python documentation: `importlib.util.find_spec`](https://docs.python.org/3/library/importlib.html#importlib.util.find_spec)\n- [Typing documentation: interface conventions](https://typing.python.org/en/latest/spec/distributing.html#library-interface-public-and-private-symbols)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
634
|
+
"ruff/F402": "## What it does\nChecks for import bindings that are shadowed by loop variables.\n\n## Why is this bad?\nShadowing an import with loop variables makes the code harder to read and\nreason about, as the identify of the imported binding is no longer clear.\nIt's also often indicative of a mistake, as it's unlikely that the loop\nvariable is intended to be used as the imported binding.\n\nConsider using a different name for the loop variable.\n\n## Example\n```python\nfrom os import path\n\nfor path in files:\n print(path)\n```\n\nUse instead:\n```python\nfrom os import path\n\n\nfor filename in files:\n print(filename)\n```\n",
|
|
635
|
+
"ruff/F403": "## What it does\nChecks for the use of wildcard imports.\n\n## Why is this bad?\nWildcard imports (e.g., `from module import *`) make it hard to determine\nwhich symbols are available in the current namespace, and from which module\nthey were imported. They're also discouraged by [PEP 8].\n\n## Example\n```python\nfrom math import *\n\n\ndef area(radius):\n return pi * radius**2\n```\n\nUse instead:\n```python\nfrom math import pi\n\n\ndef area(radius):\n return pi * radius**2\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#imports\n",
|
|
636
|
+
"ruff/F404": "## What it does\nChecks for `__future__` imports that are not located at the beginning of a\nfile.\n\n## Why is this bad?\nImports from `__future__` must be placed the beginning of the file, before any\nother statements (apart from docstrings). The use of `__future__` imports\nelsewhere is invalid and will result in a `SyntaxError`.\n\n## Example\n```python\nfrom pathlib import Path\n\nfrom __future__ import annotations\n```\n\nUse instead:\n```python\nfrom __future__ import annotations\n\nfrom pathlib import Path\n```\n\n## References\n- [Python documentation: Future statements](https://docs.python.org/3/reference/simple_stmts.html#future)\n",
|
|
637
|
+
"ruff/F405": "## What it does\nChecks for names that might be undefined, but may also be defined in a\nwildcard import.\n\n## Why is this bad?\nWildcard imports (e.g., `from module import *`) make it hard to determine\nwhich symbols are available in the current namespace. If a module contains\na wildcard import, and a name in the current namespace has not been\nexplicitly defined or imported, then it's unclear whether the name is\nundefined or was imported by the wildcard import.\n\nIf the name _is_ defined in via a wildcard import, that member should be\nimported explicitly to avoid confusion.\n\nIf the name is _not_ defined in a wildcard import, it should be defined or\nimported.\n\n## Example\n```python\nfrom math import *\n\n\ndef area(radius):\n return pi * radius**2\n```\n\nUse instead:\n```python\nfrom math import pi\n\n\ndef area(radius):\n return pi * radius**2\n```\n",
|
|
638
|
+
"ruff/F406": "## What it does\nCheck for the use of wildcard imports outside of the module namespace.\n\n## Why is this bad?\nThe use of wildcard imports outside of the module namespace (e.g., within\nfunctions) can lead to confusion, as the import can shadow local variables.\n\nThough wildcard imports are discouraged by [PEP 8], when necessary, they\nshould be placed in the module namespace (i.e., at the top-level of a\nmodule).\n\n## Example\n\n```python\ndef foo():\n from math import *\n```\n\nUse instead:\n\n```python\nfrom math import *\n\n\ndef foo(): ...\n```\n\n[PEP 8]: https://peps.python.org/pep-0008/#imports\n",
|
|
639
|
+
"ruff/F407": "## What it does\nChecks for `__future__` imports that are not defined in the current Python\nversion.\n\n## Why is this bad?\nImporting undefined or unsupported members from the `__future__` module is\na `SyntaxError`.\n\n## References\n- [Python documentation: `__future__`](https://docs.python.org/3/library/__future__.html)\n",
|
|
640
|
+
"ruff/F501": "## What it does\nChecks for invalid `printf`-style format strings.\n\n## Why is this bad?\nConversion specifiers are required for `printf`-style format strings. These\nspecifiers must contain a `%` character followed by a conversion type.\n\n## Example\n```python\n\"Hello, %\" % \"world\"\n```\n\nUse instead:\n```python\n\"Hello, %s\" % \"world\"\n```\n\n## References\n- [Python documentation: `printf`-style String Formatting](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting)\n",
|
|
641
|
+
"ruff/F502": "## What it does\nChecks for named placeholders in `printf`-style format strings without\nmapping-type values.\n\n## Why is this bad?\nWhen using named placeholders in `printf`-style format strings, the values\nmust be a map type (such as a dictionary). Otherwise, the expression will\nraise a `TypeError`.\n\n## Example\n```python\n\"%(greeting)s, %(name)s\" % (\"Hello\", \"World\")\n```\n\nUse instead:\n```python\n\"%(greeting)s, %(name)s\" % {\"greeting\": \"Hello\", \"name\": \"World\"}\n```\n\nOr:\n```python\n\"%s, %s\" % (\"Hello\", \"World\")\n```\n\n## References\n- [Python documentation: `printf`-style String Formatting](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting)\n",
|
|
642
|
+
"ruff/F503": "## What it does\nChecks for uses of mapping-type values in `printf`-style format strings\nwithout named placeholders.\n\n## Why is this bad?\nWhen using mapping-type values (such as `dict`) in `printf`-style format\nstrings, the keys must be named. Otherwise, the expression will raise a\n`TypeError`.\n\n## Example\n```python\n\"%s, %s\" % {\"greeting\": \"Hello\", \"name\": \"World\"}\n```\n\nUse instead:\n```python\n\"%(greeting)s, %(name)s\" % {\"greeting\": \"Hello\", \"name\": \"World\"}\n```\n\nOr:\n```python\n\"%s, %s\" % (\"Hello\", \"World\")\n```\n\n## References\n- [Python documentation: `printf`-style String Formatting](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting)\n",
|
|
643
|
+
"ruff/F504": "## What it does\nChecks for unused mapping keys in `printf`-style format strings.\n\n## Why is this bad?\nUnused named placeholders in `printf`-style format strings are unnecessary,\nand likely indicative of a mistake. They should be removed.\n\n## Example\n```python\n\"Hello, %(name)s\" % {\"greeting\": \"Hello\", \"name\": \"World\"}\n```\n\nUse instead:\n```python\n\"Hello, %(name)s\" % {\"name\": \"World\"}\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe for mapping key\ncontaining function calls with potential side effects,\nbecause removing such arguments could change the behavior of the code.\n\nFor example, the fix would be marked as unsafe in the following case:\n```python\n\"Hello, %(name)s\" % {\"greeting\": print(1), \"name\": \"World\"}\n```\n\n## References\n- [Python documentation: `printf`-style String Formatting](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting)\n",
|
|
644
|
+
"ruff/F505": "## What it does\nChecks for named placeholders in `printf`-style format strings that are not\npresent in the provided mapping.\n\n## Why is this bad?\nNamed placeholders that lack a corresponding value in the provided mapping\nwill raise a `KeyError`.\n\n## Example\n```python\n\"%(greeting)s, %(name)s\" % {\"name\": \"world\"}\n```\n\nUse instead:\n```python\n\"Hello, %(name)s\" % {\"name\": \"world\"}\n```\n\n## References\n- [Python documentation: `printf`-style String Formatting](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting)\n",
|
|
645
|
+
"ruff/F506": "## What it does\nChecks for `printf`-style format strings that have mixed positional and\nnamed placeholders.\n\n## Why is this bad?\nPython does not support mixing positional and named placeholders in\n`printf`-style format strings. The use of mixed placeholders will raise a\n`TypeError` at runtime.\n\n## Example\n```python\n\"%s, %(name)s\" % (\"Hello\", {\"name\": \"World\"})\n```\n\nUse instead:\n```python\n\"%s, %s\" % (\"Hello\", \"World\")\n```\n\nOr:\n```python\n\"%(greeting)s, %(name)s\" % {\"greeting\": \"Hello\", \"name\": \"World\"}\n```\n\n## References\n- [Python documentation: `printf`-style String Formatting](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting)\n",
|
|
646
|
+
"ruff/F507": "## What it does\nChecks for `printf`-style format strings that have a mismatch between the\nnumber of positional placeholders and the number of substitution values.\n\n## Why is this bad?\nWhen a `printf`-style format string is provided with too many or too few\nsubstitution values, it will raise a `TypeError` at runtime.\n\n## Example\n```python\n\"%s, %s\" % (\"Hello\", \"world\", \"!\")\n```\n\nUse instead:\n```python\n\"%s, %s\" % (\"Hello\", \"world\")\n```\n\n## References\n- [Python documentation: `printf`-style String Formatting](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting)\n",
|
|
647
|
+
"ruff/F508": "## What it does\nChecks for `printf`-style format strings that use the `*` specifier with\nnon-tuple values.\n\n## Why is this bad?\nThe use of the `*` specifier with non-tuple values will raise a\n`TypeError` at runtime.\n\n## Example\n```python\nfrom math import pi\n\n\"%(n).*f\" % {\"n\": (2, pi)}\n```\n\nUse instead:\n```python\nfrom math import pi\n\n\"%.*f\" % (2, pi) # 3.14\n```\n\n## References\n- [Python documentation: `printf`-style String Formatting](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting)\n",
|
|
648
|
+
"ruff/F509": "## What it does\nChecks for `printf`-style format strings with invalid format characters.\n\n## Why is this bad?\nIn `printf`-style format strings, the `%` character is used to indicate\nplaceholders. If a `%` character is not followed by a valid format\ncharacter, it will raise a `ValueError` at runtime.\n\n## Example\n```python\n\"Hello, %S\" % \"world\"\n```\n\nUse instead:\n```python\n\"Hello, %s\" % \"world\"\n```\n\n## References\n- [Python documentation: `printf`-style String Formatting](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting)\n",
|
|
649
|
+
"ruff/F521": "## What it does\nChecks for `str.format` calls with invalid format strings.\n\n## Why is this bad?\nInvalid format strings will raise a `ValueError`.\n\n## Example\n```python\n\"{\".format(foo)\n```\n\nUse instead:\n```python\n\"{}\".format(foo)\n```\n\n## References\n- [Python documentation: `str.format`](https://docs.python.org/3/library/stdtypes.html#str.format)\n",
|
|
650
|
+
"ruff/F522": "## What it does\nChecks for `str.format` calls with unused keyword arguments.\n\n## Why is this bad?\nUnused keyword arguments are redundant, and often indicative of a mistake.\nThey should be removed.\n\n## Example\n```python\n\"Hello, {name}\".format(greeting=\"Hello\", name=\"World\")\n```\n\nUse instead:\n```python\n\"Hello, {name}\".format(name=\"World\")\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe if the unused keyword argument\ncontains a function call with potential side effects,\nbecause removing such arguments could change the behavior of the code.\n\nFor example, the fix would be marked as unsafe in the following case:\n```python\n\"Hello, {name}\".format(greeting=print(1), name=\"World\")\n```\n\n## References\n- [Python documentation: `str.format`](https://docs.python.org/3/library/stdtypes.html#str.format)\n",
|
|
651
|
+
"ruff/F523": "## What it does\nChecks for `str.format` calls with unused positional arguments.\n\n## Why is this bad?\nUnused positional arguments are redundant, and often indicative of a mistake.\nThey should be removed.\n\n## Example\n```python\n\"Hello, {0}\".format(\"world\", \"!\")\n```\n\nUse instead:\n```python\n\"Hello, {0}\".format(\"world\")\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe if the unused positional argument\ncontains a function call with potential side effects,\nbecause removing such arguments could change the behavior of the code.\n\nFor example, the fix would be marked as unsafe in the following case:\n```python\n\"Hello, {0}\".format(\"world\", print(1))\n```\n\n## References\n- [Python documentation: `str.format`](https://docs.python.org/3/library/stdtypes.html#str.format)\n",
|
|
652
|
+
"ruff/F524": "## What it does\nChecks for `str.format` calls with placeholders that are missing arguments.\n\n## Why is this bad?\nIn `str.format` calls, omitting arguments for placeholders will raise a\n`KeyError` at runtime.\n\n## Example\n```python\n\"{greeting}, {name}\".format(name=\"World\")\n```\n\nUse instead:\n```python\n\"{greeting}, {name}\".format(greeting=\"Hello\", name=\"World\")\n```\n\n## References\n- [Python documentation: `str.format`](https://docs.python.org/3/library/stdtypes.html#str.format)\n",
|
|
653
|
+
"ruff/F525": "## What it does\nChecks for `str.format` calls that mix automatic and manual numbering.\n\n## Why is this bad?\nIn `str.format` calls, mixing automatic and manual numbering will raise a\n`ValueError` at runtime.\n\n## Example\n```python\n\"{0}, {}\".format(\"Hello\", \"World\")\n```\n\nUse instead:\n```python\n\"{0}, {1}\".format(\"Hello\", \"World\")\n```\n\nOr:\n```python\n\"{}, {}\".format(\"Hello\", \"World\")\n```\n\n## References\n- [Python documentation: `str.format`](https://docs.python.org/3/library/stdtypes.html#str.format)\n",
|
|
654
|
+
"ruff/F541": "## What it does\nChecks for f-strings that do not contain any placeholder expressions.\n\n## Why is this bad?\nf-strings are a convenient way to format strings, but they are not\nnecessary if there are no placeholder expressions to format. In this\ncase, a regular string should be used instead, as an f-string without\nplaceholders can be confusing for readers, who may expect such a\nplaceholder to be present.\n\nAn f-string without any placeholders could also indicate that the\nauthor forgot to add a placeholder expression.\n\n## Example\n```python\nf\"Hello, world!\"\n```\n\nUse instead:\n```python\n\"Hello, world!\"\n```\n\n**Note:** to maintain compatibility with PyFlakes, this rule only flags\nf-strings that are part of an implicit concatenation if _none_ of the\nf-string segments contain placeholder expressions.\n\nFor example:\n\n```python\n# Will not be flagged.\n(\n f\"Hello,\"\n f\" {name}!\"\n)\n\n# Will be flagged.\n(\n f\"Hello,\"\n f\" World!\"\n)\n```\n\nSee [#10885](https://github.com/astral-sh/ruff/issues/10885) for more.\n\n## Fix safety\nThe fix is marked unsafe when it would create a docstring.\n\n## References\n- [PEP 498 \u2013 Literal String Interpolation](https://peps.python.org/pep-0498/)\n",
|
|
655
|
+
"ruff/F601": "## What it does\nChecks for dictionary literals that associate multiple values with the\nsame key.\n\n## Why is this bad?\nDictionary keys should be unique. If a key is associated with multiple values,\nthe earlier values will be overwritten. Including multiple values for the\nsame key in a dictionary literal is likely a mistake.\n\n## Example\n```python\nfoo = {\n \"bar\": 1,\n \"baz\": 2,\n \"baz\": 3,\n}\nfoo[\"baz\"] # 3\n```\n\nUse instead:\n```python\nfoo = {\n \"bar\": 1,\n \"baz\": 2,\n}\nfoo[\"baz\"] # 2\n```\n\n## Fix safety\n\nThis rule's fix is marked as unsafe because removing a repeated dictionary key\nmay delete comments that are attached to the removed key-value pair. This can also change\nthe program's behavior if the value expressions have side effects.\n\n## References\n- [Python documentation: Dictionaries](https://docs.python.org/3/tutorial/datastructures.html#dictionaries)\n",
|
|
656
|
+
"ruff/F602": "## What it does\nChecks for dictionary keys that are repeated with different values.\n\n## Why is this bad?\nDictionary keys should be unique. If a key is repeated with a different\nvalue, the first values will be overwritten and the key will correspond to\nthe last value. This is likely a mistake.\n\n## Example\n```python\nfoo = {\n bar: 1,\n baz: 2,\n baz: 3,\n}\nfoo[baz] # 3\n```\n\nUse instead:\n```python\nfoo = {\n bar: 1,\n baz: 2,\n}\nfoo[baz] # 2\n```\n\n## Fix safety\n\nThis rule's fix is marked as unsafe because removing a repeated dictionary key\nmay delete comments that are attached to the removed key-value pair. This can also change\nthe program's behavior if the value expressions have side effects.\n\n## References\n- [Python documentation: Dictionaries](https://docs.python.org/3/tutorial/datastructures.html#dictionaries)\n",
|
|
657
|
+
"ruff/F621": "## What it does\nChecks for the use of too many expressions in starred assignment statements.\n\n## Why is this bad?\nIn assignment statements, starred expressions can be used to unpack iterables.\n\nIn Python 3, no more than `1 << 8` assignments are allowed before a starred\nexpression, and no more than `1 << 24` expressions are allowed after a starred\nexpression.\n\n## References\n- [PEP 3132 \u2013 Extended Iterable Unpacking](https://peps.python.org/pep-3132/)\n",
|
|
658
|
+
"ruff/F622": "## What it does\nChecks for the use of multiple starred expressions in assignment statements.\n\n## Why is this bad?\nIn assignment statements, starred expressions can be used to unpack iterables.\nIncluding more than one starred expression on the left-hand-side of an\nassignment will cause a `SyntaxError`, as it is unclear which expression\nshould receive the remaining values.\n\n## Example\n```python\n*foo, *bar, baz = (1, 2, 3)\n```\n\n## References\n- [PEP 3132 \u2013 Extended Iterable Unpacking](https://peps.python.org/pep-3132/)\n",
|
|
659
|
+
"ruff/F631": "## What it does\nChecks for `assert` statements that use non-empty tuples as test\nconditions.\n\n## Why is this bad?\nNon-empty tuples are always `True`, so an `assert` statement with a\nnon-empty tuple as its test condition will always pass. This is likely a\nmistake.\n\n## Example\n```python\nassert (some_condition,)\n```\n\nUse instead:\n```python\nassert some_condition\n```\n\n## References\n- [Python documentation: The `assert` statement](https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement)\n",
|
|
660
|
+
"ruff/F632": "## What it does\nChecks for `is` and `is not` comparisons against literals, like integers,\nstrings, or lists.\n\n## Why is this bad?\nThe `is` and `is not` comparators operate on identity, in that they check\nwhether two objects are the same object. If the objects are not the same\nobject, the comparison will always be `False`. Using `is` and `is not` with\nconstant literals often works \"by accident\", but are not guaranteed to produce\nthe expected result.\n\nAs of Python 3.8, using `is` and `is not` with constant literals will produce\na `SyntaxWarning`.\n\nThis rule will also flag `is` and `is not` comparisons against non-constant\nliterals, like lists, sets, and dictionaries. While such comparisons will\nnot raise a `SyntaxWarning`, they are still likely to be incorrect, as they\nwill compare the identities of the objects instead of their values, which\nwill always evaluate to `False`.\n\nInstead, use `==` and `!=` to compare literals, which will compare the\nvalues of the objects instead of their identities.\n\n## Example\n```python\nx = 200\nif x is 200:\n print(\"It's 200!\")\n```\n\nUse instead:\n```python\nx = 200\nif x == 200:\n print(\"It's 200!\")\n```\n\n## References\n- [Python documentation: Identity comparisons](https://docs.python.org/3/reference/expressions.html#is-not)\n- [Python documentation: Value comparisons](https://docs.python.org/3/reference/expressions.html#value-comparisons)\n- [_Why does Python log a SyntaxWarning for \u2018is\u2019 with literals?_ by Adam Johnson](https://adamj.eu/tech/2020/01/21/why-does-python-3-8-syntaxwarning-for-is-literal/)\n",
|
|
661
|
+
"ruff/F633": "## What it does\nChecks for `print` statements that use the `>>` syntax.\n\n## Why is this bad?\nIn Python 2, the `print` statement can be used with the `>>` syntax to\nprint to a file-like object. This `print >> sys.stderr` syntax no\nlonger exists in Python 3, where `print` is only a function, not a\nstatement.\n\nInstead, use the `file` keyword argument to the `print` function, the\n`sys.stderr.write` function, or the `logging` module.\n\n## Example\n```python\nfrom __future__ import print_function\nimport sys\n\nprint >> sys.stderr, \"Hello, world!\"\n```\n\nUse instead:\n```python\nprint(\"Hello, world!\", file=sys.stderr)\n```\n\nOr:\n```python\nimport sys\n\nsys.stderr.write(\"Hello, world!\\n\")\n```\n\nOr:\n```python\nimport logging\n\nlogging.error(\"Hello, world!\")\n```\n\n## References\n- [Python documentation: `print`](https://docs.python.org/3/library/functions.html#print)\n",
|
|
662
|
+
"ruff/F634": "## What it does\nChecks for `if` statements that use non-empty tuples as test conditions.\n\n## Why is this bad?\nNon-empty tuples are always `True`, so an `if` statement with a non-empty\ntuple as its test condition will always pass. This is likely a mistake.\n\n## Example\n```python\nif (False,):\n print(\"This will always run\")\n```\n\nUse instead:\n```python\nif False:\n print(\"This will never run\")\n```\n\n## References\n- [Python documentation: The `if` statement](https://docs.python.org/3/reference/compound_stmts.html#the-if-statement)\n",
|
|
663
|
+
"ruff/F701": "## What it does\nChecks for `break` statements outside of loops.\n\n## Why is this bad?\nThe use of a `break` statement outside of a `for` or `while` loop will\nraise a `SyntaxError`.\n\n## Example\n```python\ndef foo():\n break\n```\n\n## References\n- [Python documentation: `break`](https://docs.python.org/3/reference/simple_stmts.html#the-break-statement)\n",
|
|
664
|
+
"ruff/F702": "## What it does\nChecks for `continue` statements outside of loops.\n\n## Why is this bad?\nThe use of a `continue` statement outside of a `for` or `while` loop will\nraise a `SyntaxError`.\n\n## Example\n```python\ndef foo():\n continue # SyntaxError\n```\n\n## References\n- [Python documentation: `continue`](https://docs.python.org/3/reference/simple_stmts.html#the-continue-statement)\n",
|
|
665
|
+
"ruff/F704": "## What it does\nChecks for `yield`, `yield from`, and `await` usages outside of functions.\n\n## Why is this bad?\nThe use of `yield`, `yield from`, or `await` outside of a function will\nraise a `SyntaxError`.\n\n## Example\n```python\nclass Foo:\n yield 1\n```\n\n## Notebook behavior\nAs an exception, `await` is allowed at the top level of a Jupyter notebook\n(see: [autoawait]).\n\n## References\n- [Python documentation: `yield`](https://docs.python.org/3/reference/simple_stmts.html#the-yield-statement)\n\n[autoawait]: https://ipython.readthedocs.io/en/stable/interactive/autoawait.html\n",
|
|
666
|
+
"ruff/F706": "## What it does\nChecks for `return` statements outside of functions.\n\n## Why is this bad?\nThe use of a `return` statement outside of a function will raise a\n`SyntaxError`.\n\n## Example\n```python\nclass Foo:\n return 1\n```\n\n## References\n- [Python documentation: `return`](https://docs.python.org/3/reference/simple_stmts.html#the-return-statement)\n",
|
|
667
|
+
"ruff/F707": "## What it does\nChecks for `except` blocks that handle all exceptions, but are not the last\n`except` block in a `try` statement.\n\n## Why is this bad?\nWhen an exception is raised within a `try` block, the `except` blocks are\nevaluated in order, and the first matching block is executed. If an `except`\nblock handles all exceptions, but isn't the last block, Python will raise a\n`SyntaxError`, as the following blocks would never be executed.\n\n## Example\n```python\ndef reciprocal(n):\n try:\n reciprocal = 1 / n\n except:\n print(\"An exception occurred.\")\n except ZeroDivisionError:\n print(\"Cannot divide by zero.\")\n else:\n return reciprocal\n```\n\nUse instead:\n```python\ndef reciprocal(n):\n try:\n reciprocal = 1 / n\n except ZeroDivisionError:\n print(\"Cannot divide by zero.\")\n except:\n print(\"An exception occurred.\")\n else:\n return reciprocal\n```\n\n## References\n- [Python documentation: `except` clause](https://docs.python.org/3/reference/compound_stmts.html#except-clause)\n",
|
|
668
|
+
"ruff/F722": "## What it does\nChecks for forward annotations that include invalid syntax.\n\n\n## Why is this bad?\nIn Python, type annotations can be quoted as strings literals to enable\nreferences to types that have not yet been defined, known as \"forward\nreferences\".\n\nHowever, these quoted annotations must be valid Python expressions. The use\nof invalid syntax in a quoted annotation won't raise a `SyntaxError`, but\nwill instead raise an error when type checking is performed.\n\n## Example\n\n```python\ndef foo() -> \"/\": ...\n```\n\n## References\n- [PEP 563 \u2013 Postponed Evaluation of Annotations](https://peps.python.org/pep-0563/)\n",
|
|
669
|
+
"ruff/F811": "## What it does\nChecks for variable definitions that redefine (or \"shadow\") unused\nvariables.\n\n## Why is this bad?\nRedefinitions of unused names are unnecessary and often indicative of a\nmistake.\n\n## Example\n\n```python\nimport foo\nimport bar\nimport foo # Redefinition of unused `foo` from line 1\n```\n\nUse instead:\n\n```python\nimport foo\nimport bar\n```\n\n## Preview\nWhen [preview] is enabled, this rule also flags annotated variable\nredeclarations. For example, `bar: int = 1` followed by `bar: int = 2`\nwill be flagged as a redefinition of an unused variable, whereas plain\nreassignments like `bar = 1` followed by `bar = 2` remain unflagged.\n\nIn preview, this rule will also flag redefinitions in `typing.TYPE_CHECKING` blocks:\n\n```python\nimport typing\nfrom collections.abc import Sequence\n\nif typing.TYPE_CHECKING:\n # Redefinition of unused `Sequence` from line 2\n from collections.abc import Sequence\n```\n\nUse instead:\n\n```python\nfrom collections.abc import Sequence\n```\n\n[preview]: https://docs.astral.sh/ruff/preview/\n\n## Options\n\nThis rule ignores dummy variables, as determined by:\n\n- `lint.dummy-variable-rgx`\n",
|
|
670
|
+
"ruff/F821": "## What it does\nChecks for uses of undefined names.\n\n## Why is this bad?\nAn undefined name is likely to raise `NameError` at runtime.\n\n## Example\n```python\ndef double():\n return n * 2 # raises `NameError` if `n` is undefined when `double` is called\n```\n\nUse instead:\n```python\ndef double(n):\n return n * 2\n```\n\n## Options\n- [`target-version`]: Can be used to configure which symbols Ruff will understand\n as being available in the `builtins` namespace.\n\n## References\n- [Python documentation: Naming and binding](https://docs.python.org/3/reference/executionmodel.html#naming-and-binding)\n",
|
|
671
|
+
"ruff/F822": "## What it does\nChecks for undefined names in `__all__`.\n\n## Why is this bad?\nIn Python, the `__all__` variable is used to define the names that are\nexported when a module is imported as a wildcard (e.g.,\n`from foo import *`). The names in `__all__` must be defined in the module,\nbut are included as strings.\n\nIncluding an undefined name in `__all__` is likely to raise `NameError` at\nruntime, when the module is imported.\n\nIn [preview], this rule will flag undefined names in `__init__.py` file,\neven if those names implicitly refer to other modules in the package. Users\nthat rely on implicit exports should disable this rule in `__init__.py`\nfiles via [`lint.per-file-ignores`].\n\n## Example\n```python\nfrom foo import bar\n\n\n__all__ = [\"bar\", \"baz\"] # undefined name `baz` in `__all__`\n```\n\nUse instead:\n```python\nfrom foo import bar, baz\n\n\n__all__ = [\"bar\", \"baz\"]\n```\n\n## References\n- [Python documentation: `__all__`](https://docs.python.org/3/tutorial/modules.html#importing-from-a-package)\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
672
|
+
"ruff/F823": "## What it does\nChecks for undefined local variables.\n\n## Why is this bad?\nReferencing a local variable before it has been assigned will raise\nan `UnboundLocalError` at runtime.\n\n## Example\n```python\nx = 1\n\n\ndef foo():\n x += 1\n```\n\nUse instead:\n```python\nx = 1\n\n\ndef foo():\n global x\n x += 1\n```\n",
|
|
673
|
+
"ruff/F841": "## What it does\nChecks for the presence of unused variables in function scopes.\n\n## Why is this bad?\nA variable that is defined but not used is likely a mistake, and should\nbe removed to avoid confusion.\n\nIf a variable is intentionally defined-but-not-used, it should be\nprefixed with an underscore, or some other value that adheres to the\n[`lint.dummy-variable-rgx`] pattern.\n\n## Example\n```python\ndef foo():\n x = 1\n y = 2\n return x\n```\n\nUse instead:\n```python\ndef foo():\n x = 1\n return x\n```\n\n## Fix safety\n\nThis rule's fix is marked as unsafe because removing an unused variable assignment may\ndelete comments that are attached to the assignment.\n\n## See also\n\nThis rule does not apply to bindings in unpacked assignments (e.g. `x, y = 1, 2`). See\n[`unused-unpacked-variable`][RUF059] for this case.\n\n## Options\n- `lint.dummy-variable-rgx`\n\n[RUF059]: https://docs.astral.sh/ruff/rules/unused-unpacked-variable/\n",
|
|
674
|
+
"ruff/F842": "## What it does\nChecks for local variables that are annotated but never used.\n\n## Why is this bad?\nAnnotations are used to provide type hints to static type checkers. If a\nvariable is annotated but never used, the annotation is unnecessary.\n\n## Example\n```python\ndef foo():\n bar: int\n```\n\n## Options\n\nThis rule ignores dummy variables, as determined by:\n\n- `lint.dummy-variable-rgx`\n\n## References\n- [PEP 484 \u2013 Type Hints](https://peps.python.org/pep-0484/)\n",
|
|
675
|
+
"ruff/F901": "## What it does\nChecks for `raise` statements that raise `NotImplemented`.\n\n## Why is this bad?\n`NotImplemented` is a special value returned by binary special methods to indicate\nthat an operation is not implemented with respect to a particular type.\n\nBecause `NotImplemented` is not an exception, it cannot be raised.\nRaise `NotImplementedError` instead, which is used to indicate that a method is\nabstract or not implemented in the derived class.\n\n## Example\n```python\nclass Foo:\n def bar(self):\n raise NotImplemented\n```\n\nUse instead:\n```python\nclass Foo:\n def bar(self):\n raise NotImplementedError\n```\n\n## References\n- [Python documentation: `NotImplemented`](https://docs.python.org/3/library/constants.html#NotImplemented)\n- [Python documentation: `NotImplementedError`](https://docs.python.org/3/library/exceptions.html#NotImplementedError)\n",
|
|
676
|
+
"ruff/PGH001": "## Removed\nThis rule is identical to [S307] which should be used instead.\n\n## What it does\nChecks for uses of the builtin `eval()` function.\n\n## Why is this bad?\nThe `eval()` function is insecure as it enables arbitrary code execution.\n\n## Example\n```python\ndef foo():\n x = eval(input(\"Enter a number: \"))\n ...\n```\n\nUse instead:\n```python\ndef foo():\n x = input(\"Enter a number: \")\n ...\n```\n\n## References\n- [Python documentation: `eval`](https://docs.python.org/3/library/functions.html#eval)\n- [_Eval really is dangerous_ by Ned Batchelder](https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html)\n\n[S307]: https://docs.astral.sh/ruff/rules/suspicious-eval-usage/\n",
|
|
677
|
+
"ruff/PGH002": "## Removed\nThis rule is identical to [G010] which should be used instead.\n\n## What it does\nCheck for usages of the deprecated `warn` method from the `logging` module.\n\n## Why is this bad?\nThe `warn` method is deprecated. Use `warning` instead.\n\n## Example\n```python\nimport logging\n\n\ndef foo():\n logging.warn(\"Something happened\")\n```\n\nUse instead:\n```python\nimport logging\n\n\ndef foo():\n logging.warning(\"Something happened\")\n```\n\n## References\n- [Python documentation: `logger.Logger.warning`](https://docs.python.org/3/library/logging.html#logging.Logger.warning)\n\n[G010]: https://docs.astral.sh/ruff/rules/logging-warn/\n",
|
|
678
|
+
"ruff/PGH003": "## What it does\nCheck for `type: ignore` annotations that suppress all type warnings, as\nopposed to targeting specific type warnings.\n\n## Why is this bad?\nSuppressing all warnings can hide issues in the code.\n\nBlanket `type: ignore` annotations are also more difficult to interpret and\nmaintain, as the annotation does not clarify which warnings are intended\nto be suppressed.\n\n## Example\n```python\nfrom foo import secrets # type: ignore\n```\n\nUse instead:\n```python\nfrom foo import secrets # type: ignore[attr-defined]\n```\n\n## References\nMypy supports a [built-in setting](https://mypy.readthedocs.io/en/stable/error_code_list2.html#check-that-type-ignore-include-an-error-code-ignore-without-code)\nto enforce that all `type: ignore` annotations include an error code, akin\nto enabling this rule:\n```toml\n[tool.mypy]\nenable_error_code = [\"ignore-without-code\"]\n```\n",
|
|
679
|
+
"ruff/PGH004": "## What it does\nCheck for `noqa` annotations that suppress all diagnostics, as opposed to\ntargeting specific diagnostics.\n\n## Why is this bad?\nSuppressing all diagnostics can hide issues in the code.\n\nBlanket `noqa` annotations are also more difficult to interpret and\nmaintain, as the annotation does not clarify which diagnostics are intended\nto be suppressed.\n\n## Example\n```python\nfrom .base import * # noqa\n```\n\nUse instead:\n```python\nfrom .base import * # noqa: F403\n```\n\n## Fix safety\nThis rule will attempt to fix blanket `noqa` annotations that appear to\nbe unintentional. For example, given `# noqa F401`, the rule will suggest\ninserting a colon, as in `# noqa: F401`.\n\nWhile modifying `noqa` comments is generally safe, doing so may introduce\nadditional diagnostics.\n\n## References\n- [Ruff documentation](https://docs.astral.sh/ruff/configuration/#error-suppression)\n",
|
|
680
|
+
"ruff/PGH005": "## What it does\nChecks for common mistakes when using mock objects.\n\n## Why is this bad?\nThe `mock` module exposes an assertion API that can be used to verify that\nmock objects undergo expected interactions. This rule checks for common\nmistakes when using this API.\n\nFor example, it checks for mock attribute accesses that should be replaced\nwith mock method calls.\n\n## Example\n```python\nmy_mock.assert_called\n```\n\nUse instead:\n```python\nmy_mock.assert_called()\n```\n",
|
|
681
|
+
"ruff/PLC0105": "## What it does\nChecks for type names that do not match the variance of their associated\ntype parameter.\n\n## Why is this bad?\n[PEP 484] recommends the use of the `_co` and `_contra` suffixes for\ncovariant and contravariant type parameters, respectively (while invariant\ntype parameters should not have any such suffix).\n\n## Example\n```python\nfrom typing import TypeVar\n\nT = TypeVar(\"T\", covariant=True)\nU = TypeVar(\"U\", contravariant=True)\nV_co = TypeVar(\"V_co\")\n```\n\nUse instead:\n```python\nfrom typing import TypeVar\n\nT_co = TypeVar(\"T_co\", covariant=True)\nU_contra = TypeVar(\"U_contra\", contravariant=True)\nV = TypeVar(\"V\")\n```\n\n## References\n- [Python documentation: `typing` \u2014 Support for type hints](https://docs.python.org/3/library/typing.html)\n- [PEP 483 \u2013 The Theory of Type Hints: Covariance and Contravariance](https://peps.python.org/pep-0483/#covariance-and-contravariance)\n- [PEP 484 \u2013 Type Hints: Covariance and contravariance](https://peps.python.org/pep-0484/#covariance-and-contravariance)\n\n[PEP 484]: https://peps.python.org/pep-0484/\n",
|
|
682
|
+
"ruff/PLC0131": "## What it does\nChecks for `TypeVar` and `ParamSpec` definitions in which the type is\nboth covariant and contravariant.\n\n## Why is this bad?\nBy default, Python's generic types are invariant, but can be marked as\neither covariant or contravariant via the `covariant` and `contravariant`\nkeyword arguments. While the API does allow you to mark a type as both\ncovariant and contravariant, this is not supported by the type system,\nand should be avoided.\n\nInstead, change the variance of the type to be either covariant,\ncontravariant, or invariant. If you want to describe both covariance and\ncontravariance, consider using two separate type parameters.\n\nFor context: an \"invariant\" generic type only accepts values that exactly\nmatch the type parameter; for example, `list[Dog]` accepts only `list[Dog]`,\nnot `list[Animal]` (superclass) or `list[Bulldog]` (subclass). This is\nthe default behavior for Python's generic types.\n\nA \"covariant\" generic type accepts subclasses of the type parameter; for\nexample, `Sequence[Animal]` accepts `Sequence[Dog]`. A \"contravariant\"\ngeneric type accepts superclasses of the type parameter; for example,\n`Callable[Dog]` accepts `Callable[Animal]`.\n\n## Example\n```python\nfrom typing import TypeVar\n\nT = TypeVar(\"T\", covariant=True, contravariant=True)\n```\n\nUse instead:\n```python\nfrom typing import TypeVar\n\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n```\n\n## References\n- [Python documentation: `typing` \u2014 Support for type hints](https://docs.python.org/3/library/typing.html)\n- [PEP 483 \u2013 The Theory of Type Hints: Covariance and Contravariance](https://peps.python.org/pep-0483/#covariance-and-contravariance)\n- [PEP 484 \u2013 Type Hints: Covariance and contravariance](https://peps.python.org/pep-0484/#covariance-and-contravariance)\n",
|
|
683
|
+
"ruff/PLC0132": "## What it does\nChecks for `TypeVar`, `TypeVarTuple`, `ParamSpec`, and `NewType`\ndefinitions in which the name of the type parameter does not match the name\nof the variable to which it is assigned.\n\n## Why is this bad?\nWhen defining a `TypeVar` or a related type parameter, Python allows you to\nprovide a name for the type parameter. According to [PEP 484], the name\nprovided to the `TypeVar` constructor must be equal to the name of the\nvariable to which it is assigned.\n\n## Example\n```python\nfrom typing import TypeVar\n\nT = TypeVar(\"U\")\n```\n\nUse instead:\n```python\nfrom typing import TypeVar\n\nT = TypeVar(\"T\")\n```\n\n## References\n- [Python documentation: `typing` \u2014 Support for type hints](https://docs.python.org/3/library/typing.html)\n- [PEP 484 \u2013 Type Hints: Generics](https://peps.python.org/pep-0484/#generics)\n\n[PEP 484]:https://peps.python.org/pep-0484/#generics\n",
|
|
684
|
+
"ruff/PLC0205": "## What it does\nChecks for single strings assigned to `__slots__`.\n\n## Why is this bad?\nIn Python, the `__slots__` attribute allows you to explicitly define the\nattributes (instance variables) that a class can have. By default, Python\nuses a dictionary to store an object's attributes, which incurs some memory\noverhead. However, when `__slots__` is defined, Python uses a more compact\ninternal structure to store the object's attributes, resulting in memory\nsavings.\n\nAny string iterable may be assigned to `__slots__` (most commonly, a\n`tuple` of strings). If a string is assigned to `__slots__`, it is\ninterpreted as a single attribute name, rather than an iterable of attribute\nnames. This can cause confusion, as users that iterate over the `__slots__`\nvalue may expect to iterate over a sequence of attributes, but would instead\niterate over the characters of the string.\n\nTo use a single string attribute in `__slots__`, wrap the string in an\niterable container type, like a `tuple`.\n\n## Example\n```python\nclass Person:\n __slots__: str = \"name\"\n\n def __init__(self, name: str) -> None:\n self.name = name\n```\n\nUse instead:\n```python\nclass Person:\n __slots__: tuple[str, ...] = (\"name\",)\n\n def __init__(self, name: str) -> None:\n self.name = name\n```\n\n## References\n- [Python documentation: `__slots__`](https://docs.python.org/3/reference/datamodel.html#slots)\n",
|
|
685
|
+
"ruff/PLC0206": "## What it does\nChecks for dictionary iterations that extract the dictionary value\nvia explicit indexing, instead of using `.items()`.\n\n## Why is this bad?\nIterating over a dictionary with `.items()` is semantically clearer\nand more efficient than extracting the value with the key.\n\n## Example\n```python\nORCHESTRA = {\n \"violin\": \"strings\",\n \"oboe\": \"woodwind\",\n \"tuba\": \"brass\",\n \"gong\": \"percussion\",\n}\n\nfor instrument in ORCHESTRA:\n print(f\"{instrument}: {ORCHESTRA[instrument]}\")\n```\n\nUse instead:\n```python\nORCHESTRA = {\n \"violin\": \"strings\",\n \"oboe\": \"woodwind\",\n \"tuba\": \"brass\",\n \"gong\": \"percussion\",\n}\n\nfor instrument, section in ORCHESTRA.items():\n print(f\"{instrument}: {section}\")\n```\n",
|
|
686
|
+
"ruff/PLC0207": "## What it does\nChecks for access to the first or last element of `str.split()` or `str.rsplit()` without a\n`maxsplit=1` argument.\n\n## Why is this bad?\nCalling `str.split()` or `str.rsplit()` without passing `maxsplit=1` splits on every delimiter in the\nstring. When accessing only the first or last element of the result, it\nwould be more efficient to split only once.\n\n## Example\n```python\nurl = \"www.example.com\"\nprefix = url.split(\".\")[0]\n```\n\nUse instead:\n```python\nurl = \"www.example.com\"\nprefix = url.split(\".\", maxsplit=1)[0]\n```\n\nTo access the last element, use `str.rsplit()` instead of `str.split()`:\n```python\nurl = \"www.example.com\"\nsuffix = url.rsplit(\".\", maxsplit=1)[-1]\n```\n\n## Fix Safety\nThis rule's fix is marked as unsafe for `split()`/`rsplit()` calls that contain `*args` or\n`**kwargs` arguments, as adding a `maxsplit` argument to such a call may lead to duplicate\narguments.\n",
|
|
687
|
+
"ruff/PLC0208": "## What it does\nChecks for iteration over a `set` literal in which each element is a literal.\n\n## Why is this bad?\nIterating over a `set` is less efficient than iterating over a sequence\ntype, such as `list` or `tuple`.\n\n## Example\n```python\nfor number in {1, 2, 3}:\n ...\n```\n\nUse instead:\n```python\nfor number in (1, 2, 3):\n ...\n```\n\n## References\n- [Python documentation: `set`](https://docs.python.org/3/library/stdtypes.html#set)\n",
|
|
688
|
+
"ruff/PLC0414": "## What it does\nChecks for import aliases that do not rename the original package.\nThis rule does not apply in `__init__.py` files.\n\n## Why is this bad?\nThe import alias is redundant and should be removed to avoid confusion.\n\n## Fix safety\nThis fix is marked as always unsafe because the user may be intentionally\nre-exporting the import. While statements like `import numpy as numpy`\nappear redundant, they can have semantic meaning in certain contexts.\n\n## Example\n```python\nimport numpy as numpy\n```\n\nUse instead:\n```python\nimport numpy as np\n```\n\nor\n\n```python\nimport numpy\n```\n\n## Options\n\nThe rule will emit a diagnostic but not a fix if the import is required by the `isort`\nconfiguration option:\n\n- `lint.isort.required-imports`\n",
|
|
689
|
+
"ruff/PLC0415": "## What it does\nChecks for `import` statements outside of a module's top-level scope, such\nas within a function or class definition.\n\n## Why is this bad?\n[PEP 8] recommends placing imports not only at the top-level of a module,\nbut at the very top of the file, \"just after any module comments and\ndocstrings, and before module globals and constants.\"\n\n`import` statements have effects that are global in scope; defining them at\nthe top level has a number of benefits. For example, it makes it easier to\nidentify the dependencies of a module, and ensures that any invalid imports\nare caught regardless of whether a specific function is called or class is\ninstantiated.\n\nAn import statement would typically be placed within a function only to\navoid a circular dependency, to defer a costly module load, or to avoid\nloading a dependency altogether in a certain runtime environment.\n\n## Example\n```python\ndef print_python_version():\n import platform\n\n print(platform.python_version())\n```\n\nUse instead:\n```python\nimport platform\n\n\ndef print_python_version():\n print(platform.python_version())\n```\n\n## See also\nThis rule will ignore import statements configured in\n[`lint.flake8-tidy-imports.banned-module-level-imports`][banned-module-level-imports]\nif the rule [`banned-module-level-imports`][TID253] is enabled.\n\n[banned-module-level-imports]: https://docs.astral.sh/ruff/settings/#lint_flake8-tidy-imports_banned-module-level-imports\n[TID253]: https://docs.astral.sh/ruff/rules/banned-module-level-imports/\n[PEP 8]: https://peps.python.org/pep-0008/#imports\n",
|
|
690
|
+
"ruff/PLC1802": "## What it does\nChecks for `len` calls on sequences in a boolean test context.\n\n## Why is this bad?\nEmpty sequences are considered false in a boolean context.\nYou can either remove the call to `len`\nor compare the length against a scalar.\n\n## Example\n```python\nfruits = [\"orange\", \"apple\"]\nvegetables = []\n\nif len(fruits):\n print(fruits)\n\nif not len(vegetables):\n print(vegetables)\n```\n\nUse instead:\n```python\nfruits = [\"orange\", \"apple\"]\nvegetables = []\n\nif fruits:\n print(fruits)\n\nif not vegetables:\n print(vegetables)\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe when the `len` call includes a comment,\nas the comment would be removed.\n\nFor example, the fix would be marked as unsafe in the following case:\n```python\nfruits = []\nif len(\n fruits # comment\n):\n ...\n```\n\n## References\n[PEP 8: Programming Recommendations](https://peps.python.org/pep-0008/#programming-recommendations)\n",
|
|
691
|
+
"ruff/PLC1901": "## What it does\nChecks for comparisons to empty strings.\n\n## Why is this bad?\nAn empty string is falsy, so it is unnecessary to compare it to `\"\"`. If\nthe value can be something else Python considers falsy, such as `None`,\n`0`, or another empty container, then the code is not equivalent.\n\n## Known problems\nHigh false positive rate, as the check is context-insensitive and does not\nconsider the type of the variable being compared ([#4282]).\n\n## Example\n```python\nx: str = ...\n\nif x == \"\":\n print(\"x is empty\")\n```\n\nUse instead:\n```python\nx: str = ...\n\nif not x:\n print(\"x is empty\")\n```\n\n## References\n- [Python documentation: Truth Value Testing](https://docs.python.org/3/library/stdtypes.html#truth-value-testing)\n\n[#4282]: https://github.com/astral-sh/ruff/issues/4282\n",
|
|
692
|
+
"ruff/PLC2401": "## What it does\nChecks for the use of non-ASCII characters in variable names.\n\n## Why is this bad?\nThe use of non-ASCII characters in variable names can cause confusion\nand compatibility issues (see: [PEP 672]).\n\n## Example\n```python\n\u00e1pple_count: int\n```\n\nUse instead:\n```python\napple_count: int\n```\n\n[PEP 672]: https://peps.python.org/pep-0672/\n",
|
|
693
|
+
"ruff/PLC2403": "## What it does\nChecks for the use of non-ASCII characters in import statements.\n\n## Why is this bad?\nThe use of non-ASCII characters in import statements can cause confusion\nand compatibility issues (see: [PEP 672]).\n\n## Example\n```python\nimport b\u00e1r\n```\n\nUse instead:\n```python\nimport bar\n```\n\nIf the module is third-party, use an ASCII-only alias:\n```python\nimport b\u00e1r as bar\n```\n\n[PEP 672]: https://peps.python.org/pep-0672/\n",
|
|
694
|
+
"ruff/PLC2701": "## What it does\nChecks for import statements that import a private name (a name starting\nwith an underscore `_`) from another module.\n\n## Why is this bad?\n[PEP 8] states that names starting with an underscore are private. Thus,\nthey are not intended to be used outside of the module in which they are\ndefined.\n\nFurther, as private imports are not considered part of the public API, they\nare prone to unexpected changes, especially outside of semantic versioning.\n\nInstead, consider using the public API of the module.\n\nThis rule ignores private name imports that are exclusively used in type\nannotations. Ideally, types would be public; however, this is not always\npossible when using third-party libraries.\n\n## Known problems\nDoes not ignore private name imports from within the module that defines\nthe private name if the module is defined with [PEP 420] namespace packages\n(i.e., directories that omit the `__init__.py` file). Namespace packages\nmust be configured via the [`namespace-packages`] setting.\n\n## Example\n```python\nfrom foo import _bar\n```\n\n## Options\n- `namespace-packages`\n\n## References\n- [PEP 8: Naming Conventions](https://peps.python.org/pep-0008/#naming-conventions)\n- [Semantic Versioning](https://semver.org/)\n\n[PEP 8]: https://peps.python.org/pep-0008/\n[PEP 420]: https://peps.python.org/pep-0420/\n",
|
|
695
|
+
"ruff/PLC2801": "## What it does\nChecks for explicit use of dunder methods, like `__str__` and `__add__`.\n\n## Why is this bad?\nDunder names are not meant to be called explicitly and, in most cases, can\nbe replaced with builtins or operators.\n\n## Fix safety\nThis fix is always unsafe. When replacing dunder method calls with operators\nor builtins, the behavior can change in the following ways:\n\n1. Types may implement only a subset of related dunder methods. Calling a\n missing dunder method directly returns `NotImplemented`, but using the\n equivalent operator raises a `TypeError`.\n ```python\n class C: pass\n c = C()\n c.__gt__(1) # before fix: NotImplemented\n c > 1 # after fix: raises TypeError\n ```\n2. Instance-assigned dunder methods are ignored by operators and builtins.\n ```python\n class C: pass\n c = C()\n c.__bool__ = lambda: False\n c.__bool__() # before fix: False\n bool(c) # after fix: True\n ```\n\n3. Even with built-in types, behavior can differ.\n ```python\n (1).__gt__(1.0) # before fix: NotImplemented\n 1 > 1.0 # after fix: False\n ```\n\n## Example\n```python\nthree = (3.0).__str__()\ntwelve = \"1\".__add__(\"2\")\n\n\ndef is_greater_than_two(x: int) -> bool:\n return x.__gt__(2)\n```\n\nUse instead:\n```python\nthree = str(3.0)\ntwelve = \"1\" + \"2\"\n\n\ndef is_greater_than_two(x: int) -> bool:\n return x > 2\n```\n",
|
|
696
|
+
"ruff/PLC3002": "## What it does\nChecks for unnecessary direct calls to lambda expressions.\n\n## Why is this bad?\nCalling a lambda expression directly is unnecessary. The expression can be\nexecuted inline instead to improve readability.\n\n## Example\n```python\narea = (lambda r: 3.14 * r**2)(radius)\n```\n\nUse instead:\n```python\narea = 3.14 * radius**2\n```\n\n## References\n- [Python documentation: Lambdas](https://docs.python.org/3/reference/expressions.html#lambda)\n",
|
|
697
|
+
"ruff/PLE0100": "## What it does\nChecks for `__init__` methods that are turned into generators by the\ninclusion of `yield` or `yield from` expressions.\n\n## Why is this bad?\nThe `__init__` method is the constructor for a given Python class,\nresponsible for initializing, rather than creating, new objects.\n\nThe `__init__` method has to return `None`. By including a `yield` or\n`yield from` expression in an `__init__`, the method will return a\ngenerator object when called at runtime, resulting in a runtime error.\n\n## Example\n```python\nclass InitIsGenerator:\n def __init__(self, i):\n yield i\n```\n\n## References\n- [CodeQL: `py-init-method-is-generator`](https://codeql.github.com/codeql-query-help/python/py-init-method-is-generator/)\n",
|
|
698
|
+
"ruff/PLE0101": "## What it does\nChecks for `__init__` methods that return values.\n\n## Why is this bad?\nThe `__init__` method is the constructor for a given Python class,\nresponsible for initializing, rather than creating, new objects.\n\nThe `__init__` method has to return `None`. Returning any value from\nan `__init__` method will result in a runtime error.\n\n## Example\n```python\nclass Example:\n def __init__(self):\n return []\n```\n\nUse instead:\n```python\nclass Example:\n def __init__(self):\n self.value = []\n```\n\n## References\n- [CodeQL: `py-explicit-return-in-init`](https://codeql.github.com/codeql-query-help/python/py-explicit-return-in-init/)\n",
|
|
699
|
+
"ruff/PLE0115": "## What it does\nChecks for variables which are both declared as both `nonlocal` and\n`global`.\n\n## Why is this bad?\nA `nonlocal` variable is a variable that is defined in the nearest\nenclosing scope, but not in the global scope, while a `global` variable is\na variable that is defined in the global scope.\n\nDeclaring a variable as both `nonlocal` and `global` is contradictory and\nwill raise a `SyntaxError`.\n\n## Example\n```python\ncounter = 0\n\n\ndef increment():\n global counter\n nonlocal counter\n counter += 1\n```\n\nUse instead:\n```python\ncounter = 0\n\n\ndef increment():\n global counter\n counter += 1\n```\n\n## References\n- [Python documentation: The `global` statement](https://docs.python.org/3/reference/simple_stmts.html#the-global-statement)\n- [Python documentation: The `nonlocal` statement](https://docs.python.org/3/reference/simple_stmts.html#nonlocal)\n",
|
|
700
|
+
"ruff/PLE0116": "## What it does\nChecks for `continue` statements inside `finally`\n\n## Why is this bad?\n`continue` statements were not allowed within `finally` clauses prior to\nPython 3.8. Using a `continue` statement within a `finally` clause can\ncause a `SyntaxError`.\n\n## Example\n```python\nwhile True:\n try:\n pass\n finally:\n continue\n```\n\nUse instead:\n```python\nwhile True:\n try:\n pass\n except Exception:\n pass\n else:\n continue\n```\n\n## Options\n- `target-version`\n",
|
|
701
|
+
"ruff/PLE0117": "## What it does\nChecks for `nonlocal` names without bindings.\n\n## Why is this bad?\n`nonlocal` names must be bound to a name in an outer scope.\nViolating this rule leads to a `SyntaxError` at runtime.\n\n## Example\n```python\ndef foo():\n def get_bar(self):\n nonlocal bar\n ...\n```\n\nUse instead:\n```python\ndef foo():\n bar = 1\n\n def get_bar(self):\n nonlocal bar\n ...\n```\n\n## References\n- [Python documentation: The `nonlocal` statement](https://docs.python.org/3/reference/simple_stmts.html#nonlocal)\n- [PEP 3104 \u2013 Access to Names in Outer Scopes](https://peps.python.org/pep-3104/)\n",
|
|
702
|
+
"ruff/PLE0118": "## What it does\nChecks for uses of names that are declared as `global` prior to the\nrelevant `global` declaration.\n\n## Why is this bad?\nThe `global` declaration applies to the entire scope. Using a name that's\ndeclared as `global` in a given scope prior to the relevant `global`\ndeclaration is a `SyntaxError`.\n\n## Example\n```python\ncounter = 1\n\n\ndef increment():\n print(f\"Adding 1 to {counter}\")\n global counter\n counter += 1\n```\n\nUse instead:\n```python\ncounter = 1\n\n\ndef increment():\n global counter\n print(f\"Adding 1 to {counter}\")\n counter += 1\n```\n\n## References\n- [Python documentation: The `global` statement](https://docs.python.org/3/reference/simple_stmts.html#the-global-statement)\n",
|
|
703
|
+
"ruff/PLE0237": "## What it does\nChecks for assignments to attributes that are not defined in `__slots__`.\n\n## Why is this bad?\nWhen using `__slots__`, only the specified attributes are allowed.\nAttempting to assign to an attribute that is not defined in `__slots__`\nwill result in an `AttributeError` at runtime.\n\n## Known problems\nThis rule can't detect `__slots__` implementations in superclasses, and\nso limits its analysis to classes that inherit from (at most) `object`.\n\n## Example\n```python\nclass Student:\n __slots__ = (\"name\",)\n\n def __init__(self, name, surname):\n self.name = name\n self.surname = surname # [assigning-non-slot]\n self.setup()\n\n def setup(self):\n pass\n```\n\nUse instead:\n```python\nclass Student:\n __slots__ = (\"name\", \"surname\")\n\n def __init__(self, name, surname):\n self.name = name\n self.surname = surname\n self.setup()\n\n def setup(self):\n pass\n```\n",
|
|
704
|
+
"ruff/PLE0241": "## What it does\nChecks for duplicate base classes in class definitions.\n\n## Why is this bad?\nIncluding duplicate base classes will raise a `TypeError` at runtime.\n\n## Example\n```python\nclass Foo:\n pass\n\n\nclass Bar(Foo, Foo):\n pass\n```\n\nUse instead:\n```python\nclass Foo:\n pass\n\n\nclass Bar(Foo):\n pass\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe if there's comments in the\nbase classes, as comments may be removed.\n\nFor example, the fix would be marked as unsafe in the following case:\n```python\nclass Foo:\n pass\n\n\nclass Bar(\n Foo, # comment\n Foo,\n):\n pass\n```\n\n## References\n- [Python documentation: Class definitions](https://docs.python.org/3/reference/compound_stmts.html#class-definitions)\n",
|
|
705
|
+
"ruff/PLE0302": "## What it does\nChecks for \"special\" methods that have an unexpected method signature.\n\n## Why is this bad?\n\"Special\" methods, like `__len__`, are expected to adhere to a specific,\nstandard function signature. Implementing a \"special\" method using a\nnon-standard function signature can lead to unexpected and surprising\nbehavior for users of a given class.\n\n## Example\n```python\nclass Bookshelf:\n def __init__(self):\n self._books = [\"Foo\", \"Bar\", \"Baz\"]\n\n def __len__(self, index): # __len__ does not except an index parameter\n return len(self._books)\n\n def __getitem__(self, index):\n return self._books[index]\n```\n\nUse instead:\n```python\nclass Bookshelf:\n def __init__(self):\n self._books = [\"Foo\", \"Bar\", \"Baz\"]\n\n def __len__(self):\n return len(self._books)\n\n def __getitem__(self, index):\n return self._books[index]\n```\n\n## References\n- [Python documentation: Data model](https://docs.python.org/3/reference/datamodel.html)\n",
|
|
706
|
+
"ruff/PLE0303": "## What it does\nChecks for `__len__` implementations that return values that are not non-negative\nintegers.\n\n## Why is this bad?\nThe `__len__` method should return a non-negative integer. Returning a different\nvalue may cause unexpected behavior.\n\nNote: `bool` is a subclass of `int`, so it's technically valid for `__len__` to\nreturn `True` or `False`. However, for consistency with other rules, Ruff will\nstill emit a diagnostic when `__len__` returns a `bool`.\n\n## Example\n```python\nclass Foo:\n def __len__(self):\n return \"2\"\n```\n\nUse instead:\n```python\nclass Foo:\n def __len__(self):\n return 2\n```\n\n## References\n- [Python documentation: The `__len__` method](https://docs.python.org/3/reference/datamodel.html#object.__len__)\n",
|
|
707
|
+
"ruff/PLE0304": "## What it does\nChecks for `__bool__` implementations that return a type other than `bool`.\n\n## Why is this bad?\nThe `__bool__` method should return a `bool` object. Returning a different\ntype may cause unexpected behavior.\n\n## Example\n```python\nclass Foo:\n def __bool__(self):\n return 2\n```\n\nUse instead:\n```python\nclass Foo:\n def __bool__(self):\n return True\n```\n\n## References\n- [Python documentation: The `__bool__` method](https://docs.python.org/3/reference/datamodel.html#object.__bool__)\n",
|
|
708
|
+
"ruff/PLE0305": "## What it does\nChecks for `__index__` implementations that return non-integer values.\n\n## Why is this bad?\nThe `__index__` method should return an integer. Returning a different\ntype may cause unexpected behavior.\n\nNote: `bool` is a subclass of `int`, so it's technically valid for `__index__` to\nreturn `True` or `False`. However, a `DeprecationWarning` (`DeprecationWarning:\n__index__ returned non-int (type bool)`) for such cases was already introduced,\nthus this is a conscious difference between the original pylint rule and the\ncurrent ruff implementation.\n\n## Example\n```python\nclass Foo:\n def __index__(self):\n return \"2\"\n```\n\nUse instead:\n```python\nclass Foo:\n def __index__(self):\n return 2\n```\n\n## References\n- [Python documentation: The `__index__` method](https://docs.python.org/3/reference/datamodel.html#object.__index__)\n",
|
|
709
|
+
"ruff/PLE0307": "## What it does\nChecks for `__str__` implementations that return a type other than `str`.\n\n## Why is this bad?\nThe `__str__` method should return a `str` object. Returning a different\ntype may cause unexpected behavior.\n\n## Example\n```python\nclass Foo:\n def __str__(self):\n return True\n```\n\nUse instead:\n```python\nclass Foo:\n def __str__(self):\n return \"Foo\"\n```\n\n## References\n- [Python documentation: The `__str__` method](https://docs.python.org/3/reference/datamodel.html#object.__str__)\n",
|
|
710
|
+
"ruff/PLE0308": "## What it does\nChecks for `__bytes__` implementations that return types other than `bytes`.\n\n## Why is this bad?\nThe `__bytes__` method should return a `bytes` object. Returning a different\ntype may cause unexpected behavior.\n\n## Example\n```python\nclass Foo:\n def __bytes__(self):\n return 2\n```\n\nUse instead:\n```python\nclass Foo:\n def __bytes__(self):\n return b\"2\"\n```\n\n## References\n- [Python documentation: The `__bytes__` method](https://docs.python.org/3/reference/datamodel.html#object.__bytes__)\n",
|
|
711
|
+
"ruff/PLE0309": "## What it does\nChecks for `__hash__` implementations that return non-integer values.\n\n## Why is this bad?\nThe `__hash__` method should return an integer. Returning a different\ntype may cause unexpected behavior.\n\nNote: `bool` is a subclass of `int`, so it's technically valid for `__hash__` to\nreturn `True` or `False`. However, for consistency with other rules, Ruff will\nstill emit a diagnostic when `__hash__` returns a `bool`.\n\n## Example\n```python\nclass Foo:\n def __hash__(self):\n return \"2\"\n```\n\nUse instead:\n```python\nclass Foo:\n def __hash__(self):\n return 2\n```\n\n## References\n- [Python documentation: The `__hash__` method](https://docs.python.org/3/reference/datamodel.html#object.__hash__)\n",
|
|
712
|
+
"ruff/PLE0604": "## What it does\nChecks for the inclusion of invalid objects in `__all__`.\n\n## Why is this bad?\nIn Python, `__all__` should contain a sequence of strings that represent\nthe names of all \"public\" symbols exported by a module.\n\nAssigning anything other than a `tuple` or `list` of strings to `__all__`\nis invalid.\n\n## Example\n```python\n__all__ = [Foo, 1, None]\n```\n\nUse instead:\n```python\n__all__ = [\"Foo\", \"Bar\", \"Baz\"]\n```\n\n## References\n- [Python documentation: The `import` statement](https://docs.python.org/3/reference/simple_stmts.html#the-import-statement)\n",
|
|
713
|
+
"ruff/PLE0605": "## What it does\nChecks for invalid assignments to `__all__`.\n\n## Why is this bad?\nIn Python, `__all__` should contain a sequence of strings that represent\nthe names of all \"public\" symbols exported by a module.\n\nAssigning anything other than a `tuple` or `list` of strings to `__all__`\nis invalid.\n\n## Example\n```python\n__all__ = \"Foo\"\n```\n\nUse instead:\n```python\n__all__ = (\"Foo\",)\n```\n\n## References\n- [Python documentation: The `import` statement](https://docs.python.org/3/reference/simple_stmts.html#the-import-statement)\n",
|
|
714
|
+
"ruff/PLE0643": "## What it does\nChecks for hard-coded sequence accesses that are known to be out of bounds.\n\n## Why is this bad?\nAttempting to access a sequence with an out-of-bounds index will cause an\n`IndexError` to be raised at runtime. When the sequence and index are\ndefined statically (e.g., subscripts on `list` and `tuple` literals, with\ninteger indexes), such errors can be detected ahead of time.\n\n## Example\n```python\nprint([0, 1, 2][3])\n```\n",
|
|
715
|
+
"ruff/PLE0704": "## What it does\nChecks for bare `raise` statements outside of exception handlers.\n\n## Why is this bad?\nA bare `raise` statement without an exception object will re-raise the last\nexception that was active in the current scope, and is typically used\nwithin an exception handler to re-raise the caught exception.\n\nIf a bare `raise` is used outside of an exception handler, it will generate\nan error due to the lack of an active exception.\n\nNote that a bare `raise` within a `finally` block will work in some cases\n(namely, when the exception is raised within the `try` block), but should\nbe avoided as it can lead to confusing behavior.\n\n## Example\n```python\nfrom typing import Any\n\n\ndef is_some(obj: Any) -> bool:\n if obj is None:\n raise\n```\n\nUse instead:\n```python\nfrom typing import Any\n\n\ndef is_some(obj: Any) -> bool:\n if obj is None:\n raise ValueError(\"`obj` cannot be `None`\")\n```\n",
|
|
716
|
+
"ruff/PLE1132": "## What it does\nChecks for repeated keyword arguments in function calls.\n\n## Why is this bad?\nPython does not allow repeated keyword arguments in function calls. If a\nfunction is called with the same keyword argument multiple times, the\ninterpreter will raise an exception.\n\n## Example\n```python\nfunc(1, 2, c=3, **{\"c\": 4})\n```\n\n## References\n- [Python documentation: Argument](https://docs.python.org/3/glossary.html#term-argument)\n",
|
|
717
|
+
"ruff/PLE1141": "## What it does\nChecks for dictionary unpacking in a for loop without calling `.items()`.\n\n## Why is this bad?\nWhen iterating over a dictionary in a for loop, if a dictionary is unpacked\nwithout calling `.items()`, it could lead to a runtime error if the keys are not\na tuple of two elements.\n\nIt is likely that you're looking for an iteration over (key, value) pairs which\ncan only be achieved when calling `.items()`.\n\n## Example\n```python\ndata = {\"Paris\": 2_165_423, \"New York City\": 8_804_190, \"Tokyo\": 13_988_129}\n\nfor city, population in data:\n print(f\"{city} has population {population}.\")\n```\n\nUse instead:\n```python\ndata = {\"Paris\": 2_165_423, \"New York City\": 8_804_190, \"Tokyo\": 13_988_129}\n\nfor city, population in data.items():\n print(f\"{city} has population {population}.\")\n```\n\n## Known problems\nIf the dictionary key is a tuple, e.g.:\n\n```python\nd = {(1, 2): 3, (3, 4): 5}\nfor x, y in d:\n print(x, y)\n```\n\nThe tuple key is unpacked into `x` and `y` instead of the key and values. This means that\nthe suggested fix of using `d.items()` would result in different runtime behavior. Ruff\ncannot consistently infer the type of a dictionary's keys.\n\n## Fix safety\nDue to the known problem with tuple keys, this fix is unsafe.\n",
|
|
718
|
+
"ruff/PLE1142": "## What it does\nChecks for uses of `await` outside `async` functions.\n\n## Why is this bad?\nUsing `await` outside an `async` function is a syntax error.\n\n## Example\n```python\nimport asyncio\n\n\ndef foo():\n await asyncio.sleep(1)\n```\n\nUse instead:\n```python\nimport asyncio\n\n\nasync def foo():\n await asyncio.sleep(1)\n```\n\n## Notebook behavior\nAs an exception, `await` is allowed at the top level of a Jupyter notebook\n(see: [autoawait]).\n\n## References\n- [Python documentation: Await expression](https://docs.python.org/3/reference/expressions.html#await)\n- [PEP 492: Await Expression](https://peps.python.org/pep-0492/#await-expression)\n\n[autoawait]: https://ipython.readthedocs.io/en/stable/interactive/autoawait.html\n",
|
|
719
|
+
"ruff/PLE1205": "## What it does\nChecks for too many positional arguments for a `logging` format string.\n\n## Why is this bad?\nA `TypeError` will be raised if the statement is run.\n\n## Example\n```python\nimport logging\n\ntry:\n function()\nexcept Exception as e:\n logging.error(\"Error occurred: %s\", type(e), e)\n raise\n```\n\nUse instead:\n```python\nimport logging\n\ntry:\n function()\nexcept Exception as e:\n logging.error(\"%s error occurred: %s\", type(e), e)\n raise\n```\n\n## Options\n\n- `lint.logger-objects`\n",
|
|
720
|
+
"ruff/PLE1206": "## What it does\nChecks for too few positional arguments for a `logging` format string.\n\n## Why is this bad?\nA `TypeError` will be raised if the statement is run.\n\n## Example\n```python\nimport logging\n\ntry:\n function()\nexcept Exception as e:\n logging.error(\"%s error occurred: %s\", e)\n raise\n```\n\nUse instead:\n```python\nimport logging\n\ntry:\n function()\nexcept Exception as e:\n logging.error(\"%s error occurred: %s\", type(e), e)\n raise\n```\n\n## Options\n\n- `lint.logger-objects`\n",
|
|
721
|
+
"ruff/PLE1300": "## What it does\nChecks for unsupported format types in format strings.\n\n## Why is this bad?\nAn invalid format string character will result in an error at runtime.\n\n## Example\n```python\n# `z` is not a valid format type.\nprint(\"%z\" % \"1\")\n\nprint(\"{:z}\".format(\"1\"))\n```\n",
|
|
722
|
+
"ruff/PLE1307": "## What it does\nChecks for mismatched argument types in \"old-style\" format strings.\n\n## Why is this bad?\nThe format string is not checked at compile time, so it is easy to\nintroduce bugs by mistyping the format string.\n\n## Example\n```python\nprint(\"%d\" % \"1\")\n```\n\nUse instead:\n```python\nprint(\"%d\" % 1)\n```\n",
|
|
723
|
+
"ruff/PLE1310": "## What it does\nChecks duplicate characters in `str.strip` calls.\n\n## Why is this bad?\nAll characters in `str.strip` calls are removed from both the leading and\ntrailing ends of the string. Including duplicate characters in the call\nis redundant and often indicative of a mistake.\n\nIn Python 3.9 and later, you can use `str.removeprefix` and\n`str.removesuffix` to remove an exact prefix or suffix from a string,\nrespectively, which should be preferred when possible.\n\n## Example\n```python\n# Evaluates to \"foo\".\n\"bar foo baz\".strip(\"bar baz \")\n```\n\nUse instead:\n```python\n# Evaluates to \"foo\".\n\"bar foo baz\".strip(\"abrz \") # \"foo\"\n```\n\nOr:\n```python\n# Evaluates to \"foo\".\n\"bar foo baz\".removeprefix(\"bar \").removesuffix(\" baz\")\n```\n\n## Options\n- `target-version`\n\n## References\n- [Python documentation: `str.strip`](https://docs.python.org/3/library/stdtypes.html#str.strip)\n",
|
|
724
|
+
"ruff/PLE1507": "## What it does\nChecks for `os.getenv` calls with an invalid `key` argument.\n\n## Why is this bad?\n`os.getenv` only supports strings as the first argument (`key`).\n\nIf the provided argument is not a string, `os.getenv` will throw a\n`TypeError` at runtime.\n\n## Example\n```python\nimport os\n\nos.getenv(1)\n```\n\nUse instead:\n```python\nimport os\n\nos.getenv(\"1\")\n```\n",
|
|
725
|
+
"ruff/PLE1519": "## What it does\nChecks for methods decorated with `@singledispatch`.\n\n## Why is this bad?\nThe `@singledispatch` decorator is intended for use with functions, not methods.\n\nInstead, use the `@singledispatchmethod` decorator, or migrate the method to a\nstandalone function.\n\n## Example\n\n```python\nfrom functools import singledispatch\n\n\nclass Class:\n @singledispatch\n def method(self, arg): ...\n```\n\nUse instead:\n\n```python\nfrom functools import singledispatchmethod\n\n\nclass Class:\n @singledispatchmethod\n def method(self, arg): ...\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as migrating from `@singledispatch` to\n`@singledispatchmethod` may change the behavior of the code.\n\n## Options\n\nThis rule applies to regular, static, and class methods. You can customize how Ruff categorizes\nmethods with the following options:\n\n- `lint.pep8-naming.classmethod-decorators`\n- `lint.pep8-naming.staticmethod-decorators`\n",
|
|
726
|
+
"ruff/PLE1520": "## What it does\nChecks for non-method functions decorated with `@singledispatchmethod`.\n\n## Why is this bad?\nThe `@singledispatchmethod` decorator is intended for use with methods, not\nfunctions.\n\nInstead, use the `@singledispatch` decorator.\n\n## Example\n\n```python\nfrom functools import singledispatchmethod\n\n\n@singledispatchmethod\ndef func(arg): ...\n```\n\nUse instead:\n\n```python\nfrom functools import singledispatch\n\n\n@singledispatch\ndef func(arg): ...\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as migrating from `@singledispatchmethod` to\n`@singledispatch` may change the behavior of the code.\n",
|
|
727
|
+
"ruff/PLE1700": "## What it does\nChecks for uses of `yield from` in async functions.\n\n## Why is this bad?\nPython doesn't support the use of `yield from` in async functions, and will\nraise a `SyntaxError` in such cases.\n\nInstead, considering refactoring the code to use an `async for` loop instead.\n\n## Example\n```python\nasync def numbers():\n yield from [1, 2, 3, 4, 5]\n```\n\nUse instead:\n```python\nasync def numbers():\n async for number in [1, 2, 3, 4, 5]:\n yield number\n```\n",
|
|
728
|
+
"ruff/PLE2502": "## What it does\nChecks for bidirectional formatting characters.\n\n## Why is this bad?\nThe interaction between bidirectional formatting characters and the\nsurrounding code can be surprising to those that are unfamiliar\nwith right-to-left writing systems.\n\nIn some cases, bidirectional formatting characters can also be used to\nobfuscate code and introduce or mask security vulnerabilities.\n\n## Example\n```python\nexample = \"x\u200f\" * 100 # \"\u200fx\" is assigned\n```\n\nThe example uses two `RIGHT-TO-LEFT MARK`s to make the `100 * ` appear inside the comment.\nWithout the `RIGHT-TO-LEFT MARK`s, the code looks like this:\n\n```py\nexample = \"x\" * 100 # \"x\" is assigned\n```\n\n## References\n- [PEP 672: Bidirectional Marks, Embeddings, Overrides and Isolates](https://peps.python.org/pep-0672/#bidirectional-marks-embeddings-overrides-and-isolates)\n",
|
|
729
|
+
"ruff/PLE2510": "## What it does\nChecks for strings that contain the control character `BS`.\n\n## Why is this bad?\nControl characters are displayed differently by different text editors and\nterminals.\n\nBy using the `\\b` sequence in lieu of the `BS` control character, the\nstring will contain the same value, but will render visibly in all editors.\n\n## Example\n```python\nx = \"\"\n```\n\nUse instead:\n```python\nx = \"\\b\"\n```\n",
|
|
730
|
+
"ruff/PLE2512": "## What it does\nChecks for strings that contain the raw control character `SUB`.\n\n## Why is this bad?\nControl characters are displayed differently by different text editors and\nterminals.\n\nBy using the `\\x1a` sequence in lieu of the `SUB` control character, the\nstring will contain the same value, but will render visibly in all editors.\n\n## Example\n```python\nx = \"\"\n```\n\nUse instead:\n```python\nx = \"\\x1a\"\n```\n",
|
|
731
|
+
"ruff/PLE2513": "## What it does\nChecks for strings that contain the raw control character `ESC`.\n\n## Why is this bad?\nControl characters are displayed differently by different text editors and\nterminals.\n\nBy using the `\\x1b` sequence in lieu of the `ESC` control character, the\nstring will contain the same value, but will render visibly in all editors.\n\n## Example\n```python\nx = \"\"\n```\n\nUse instead:\n```python\nx = \"\\x1b\"\n```\n",
|
|
732
|
+
"ruff/PLE2514": "## What it does\nChecks for strings that contain the raw control character `NUL` (0 byte).\n\n## Why is this bad?\nControl characters are displayed differently by different text editors and\nterminals.\n\nBy using the `\\0` sequence in lieu of the `NUL` control character, the\nstring will contain the same value, but will render visibly in all editors.\n\n## Example\n```python\nx = \"\"\n```\n\nUse instead:\n```python\nx = \"\\0\"\n```\n",
|
|
733
|
+
"ruff/PLE2515": "## What it does\nChecks for strings that contain the zero width space character.\n\n## Why is this bad?\nThis character is rendered invisibly in some text editors and terminals.\n\nBy using the `\\u200B` sequence, the string will contain the same value,\nbut will render visibly in all editors.\n\n## Example\n```python\nx = \"Dear Sir/Madam\"\n```\n\nUse instead:\n```python\nx = \"Dear Sir\\u200b/\\u200bMadam\" # zero width space\n```\n",
|
|
734
|
+
"ruff/PLE4703": "## What it does\nChecks for loops in which a `set` is modified during iteration.\n\n## Why is this bad?\nIf a `set` is modified during iteration, it will cause a `RuntimeError`.\n\nIf you need to modify a `set` within a loop, consider iterating over a copy\nof the `set` instead.\n\n## Known problems\nThis rule favors false negatives over false positives. Specifically, it\nwill only detect variables that can be inferred to be a `set` type based on\nlocal type inference, and will only detect modifications that are made\ndirectly on the variable itself (e.g., `set.add()`), as opposed to\nmodifications within other function calls (e.g., `some_function(set)`).\n\n## Example\n```python\nnums = {1, 2, 3}\nfor num in nums:\n nums.add(num + 5)\n```\n\nUse instead:\n```python\nnums = {1, 2, 3}\nfor num in nums.copy():\n nums.add(num + 5)\n```\n\n## Fix safety\nThis fix is always unsafe because it changes the program\u2019s behavior. Replacing the\noriginal set with a copy during iteration allows code that would previously raise a\n`RuntimeError` to run without error.\n\n## References\n- [Python documentation: `set`](https://docs.python.org/3/library/stdtypes.html#set)\n",
|
|
735
|
+
"ruff/PLR0124": "## What it does\nChecks for operations that compare a name to itself.\n\n## Why is this bad?\nComparing a name to itself typically results in a truthy value, and is\nlikely a mistake.\n\n## Example\n```python\nfoo == foo\n```\n\nIn some cases, self-comparisons are used to determine whether a float is\nNaN. Instead, prefer `math.isnan`:\n```python\nimport math\n\nmath.isnan(foo)\n```\n\n## References\n- [Python documentation: Comparisons](https://docs.python.org/3/reference/expressions.html#comparisons)\n",
|
|
736
|
+
"ruff/PLR0133": "## What it does\nChecks for comparisons between constants.\n\n## Why is this bad?\nComparing two constants will always resolve to the same value, so the\ncomparison is redundant. Instead, the expression should be replaced\nwith the result of the comparison.\n\n## Example\n```python\nfoo = 1 == 1\n```\n\nUse instead:\n```python\nfoo = True\n```\n\n## References\n- [Python documentation: Comparisons](https://docs.python.org/3/reference/expressions.html#comparisons)\n",
|
|
737
|
+
"ruff/PLR0202": "## What it does\nChecks for the use of a classmethod being made without the decorator.\n\n## Why is this bad?\nWhen it comes to consistency and readability, it's preferred to use the decorator.\n\n## Example\n\n```python\nclass Foo:\n def bar(cls): ...\n\n bar = classmethod(bar)\n```\n\nUse instead:\n\n```python\nclass Foo:\n @classmethod\n def bar(cls): ...\n```\n",
|
|
738
|
+
"ruff/PLR0203": "## What it does\nChecks for the use of a staticmethod being made without the decorator.\n\n## Why is this bad?\nWhen it comes to consistency and readability, it's preferred to use the decorator.\n\n## Example\n\n```python\nclass Foo:\n def bar(arg1, arg2): ...\n\n bar = staticmethod(bar)\n```\n\nUse instead:\n\n```python\nclass Foo:\n @staticmethod\n def bar(arg1, arg2): ...\n```\n",
|
|
739
|
+
"ruff/PLR0206": "## What it does\nChecks for property definitions that accept function parameters.\n\n## Why is this bad?\nProperties cannot be called with parameters.\n\nIf you need to pass parameters to a property, create a method with the\ndesired parameters and call that method instead.\n\n## Example\n\n```python\nclass Cat:\n @property\n def purr(self, volume): ...\n```\n\nUse instead:\n\n```python\nclass Cat:\n @property\n def purr(self): ...\n\n def purr_volume(self, volume): ...\n```\n\n## Options\n\n- `lint.pydocstyle.property-decorators`\n\n## References\n- [Python documentation: `property`](https://docs.python.org/3/library/functions.html#property)\n",
|
|
740
|
+
"ruff/PLR0402": "## What it does\nChecks for submodule imports that are aliased to the submodule name.\n\n## Why is this bad?\nUsing the `from` keyword to import the submodule is more concise and\nreadable.\n\n## Example\n```python\nimport concurrent.futures as futures\n```\n\nUse instead:\n```python\nfrom concurrent import futures\n```\n\n## Options\n\nThis rule will not trigger on imports required by the `isort` configuration.\n\n- `lint.isort.required-imports`\n\n## References\n- [Python documentation: Submodules](https://docs.python.org/3/reference/import.html#submodules)\n",
|
|
741
|
+
"ruff/PLR0904": "## What it does\nChecks for classes with too many public methods\n\nBy default, this rule allows up to 20 public methods, as configured by\nthe [`lint.pylint.max-public-methods`] option.\n\n## Why is this bad?\nClasses with many public methods are harder to understand\nand maintain.\n\nInstead, consider refactoring the class into separate classes.\n\n## Example\nAssuming that `lint.pylint.max-public-methods` is set to 5:\n```python\nclass Linter:\n def __init__(self):\n pass\n\n def pylint(self):\n pass\n\n def pylint_settings(self):\n pass\n\n def flake8(self):\n pass\n\n def flake8_settings(self):\n pass\n\n def pydocstyle(self):\n pass\n\n def pydocstyle_settings(self):\n pass\n```\n\nUse instead:\n```python\nclass Linter:\n def __init__(self):\n self.pylint = Pylint()\n self.flake8 = Flake8()\n self.pydocstyle = Pydocstyle()\n\n def lint(self):\n pass\n\n\nclass Pylint:\n def lint(self):\n pass\n\n def settings(self):\n pass\n\n\nclass Flake8:\n def lint(self):\n pass\n\n def settings(self):\n pass\n\n\nclass Pydocstyle:\n def lint(self):\n pass\n\n def settings(self):\n pass\n```\n\n## Options\n- `lint.pylint.max-public-methods`\n",
|
|
742
|
+
"ruff/PLR0913": "## What it does\nChecks for function definitions that include too many arguments.\n\nBy default, this rule allows up to five arguments, as configured by the\n[`lint.pylint.max-args`] option.\n\nThis rule exempts methods decorated with [`@typing.override`][override].\nChanging the signature of a subclass method may cause type checkers to\ncomplain about a violation of the Liskov Substitution Principle if it\nmeans that the method now incompatibly overrides a method defined on a\nsuperclass. Explicitly decorating an overriding method with `@override`\nsignals to Ruff that the method is intended to override a superclass\nmethod and that a type checker will enforce that it does so; Ruff\ntherefore knows that it should not enforce rules about methods having\ntoo many arguments.\n\n## Why is this bad?\nFunctions with many arguments are harder to understand, maintain, and call.\nConsider refactoring functions with many arguments into smaller functions\nwith fewer arguments, or using objects to group related arguments.\n\n## Example\n```python\ndef calculate_position(x_pos, y_pos, z_pos, x_vel, y_vel, z_vel, time):\n new_x = x_pos + x_vel * time\n new_y = y_pos + y_vel * time\n new_z = z_pos + z_vel * time\n return new_x, new_y, new_z\n```\n\nUse instead:\n```python\nfrom typing import NamedTuple\n\n\nclass Vector(NamedTuple):\n x: float\n y: float\n z: float\n\n\ndef calculate_position(pos: Vector, vel: Vector, time: float) -> Vector:\n return Vector(*(p + v * time for p, v in zip(pos, vel)))\n```\n\n## Options\n- `lint.pylint.max-args`\n\n[override]: https://docs.python.org/3/library/typing.html#typing.override\n",
|
|
743
|
+
"ruff/PLR0916": "## What it does\nChecks for too many Boolean expressions in an `if` statement.\n\nBy default, this rule allows up to 5 expressions. This can be configured\nusing the [`lint.pylint.max-bool-expr`] option.\n\n## Why is this bad?\n`if` statements with many Boolean expressions are harder to understand\nand maintain. Consider assigning the result of the Boolean expression,\nor any of its sub-expressions, to a variable.\n\n## Example\n```python\nif a and b and c and d and e and f and g and h:\n ...\n```\n\n## Options\n- `lint.pylint.max-bool-expr`\n",
|
|
744
|
+
"ruff/PLR1701": "## Removed\nThis rule is identical to [SIM101] which should be used instead.\n\n## What it does\nChecks for repeated `isinstance` calls on the same object.\n\n## Why is this bad?\nRepeated `isinstance` calls on the same object can be merged into a\nsingle call.\n\n## Fix safety\nThis rule's fix is marked as unsafe on Python 3.10 and later, as combining\nmultiple `isinstance` calls with a binary operator (`|`) will fail at\nruntime if any of the operands are themselves tuples.\n\nFor example, given `TYPES = (dict, list)`, then\n`isinstance(None, TYPES | set | float)` will raise a `TypeError` at runtime,\nwhile `isinstance(None, set | float)` will not.\n\n## Example\n```python\ndef is_number(x):\n return isinstance(x, int) or isinstance(x, float) or isinstance(x, complex)\n```\n\nUse instead:\n```python\ndef is_number(x):\n return isinstance(x, (int, float, complex))\n```\n\nOr, for Python 3.10 and later:\n\n```python\ndef is_number(x):\n return isinstance(x, int | float | complex)\n```\n\n## Options\n- `target-version`\n\n## References\n- [Python documentation: `isinstance`](https://docs.python.org/3/library/functions.html#isinstance)\n\n[SIM101]: https://docs.astral.sh/ruff/rules/duplicate-isinstance-call/\n",
|
|
745
|
+
"ruff/PLR1702": "## What it does\nChecks for functions or methods with too many nested blocks.\n\nBy default, this rule allows up to five nested blocks.\nThis can be configured using the [`lint.pylint.max-nested-blocks`] option.\n\n## Why is this bad?\nFunctions or methods with too many nested blocks are harder to understand\nand maintain.\n\n## Options\n- `lint.pylint.max-nested-blocks`\n",
|
|
746
|
+
"ruff/PLR1704": "## What it does\nChecks for variables defined in `for`, `try`, `with` statements\nthat redefine function parameters.\n\n## Why is this bad?\nRedefined variables can cause unexpected behavior because of overridden function parameters.\nIf nested functions are declared, an inner function's body can override an outer function's parameters.\n\n## Example\n```python\ndef show(host_id=10.11):\n for host_id, host in [[12.13, \"Venus\"], [14.15, \"Mars\"]]:\n print(host_id, host)\n```\n\nUse instead:\n```python\ndef show(host_id=10.11):\n for inner_host_id, host in [[12.13, \"Venus\"], [14.15, \"Mars\"]]:\n print(host_id, inner_host_id, host)\n```\n\n## Options\n- `lint.dummy-variable-rgx`\n\n## References\n- [Pylint documentation](https://pylint.readthedocs.io/en/latest/user_guide/messages/refactor/redefined-argument-from-local.html)\n",
|
|
747
|
+
"ruff/PLR1706": "## Removal\nThis rule was removed from Ruff because it was common for it to introduce behavioral changes.\nSee [#9007](https://github.com/astral-sh/ruff/issues/9007) for more information.\n\n## What it does\nChecks for uses of the known pre-Python 2.5 ternary syntax.\n\n## Why is this bad?\nPrior to the introduction of the if-expression (ternary) operator in Python\n2.5, the only way to express a conditional expression was to use the `and`\nand `or` operators.\n\nThe if-expression construct is clearer and more explicit, and should be\npreferred over the use of `and` and `or` for ternary expressions.\n\n## Example\n```python\nx, y = 1, 2\nmaximum = x >= y and x or y\n```\n\nUse instead:\n```python\nx, y = 1, 2\nmaximum = x if x >= y else y\n```\n",
|
|
748
|
+
"ruff/PLR1708": "## What it does\nChecks for explicit `raise StopIteration` in generator functions.\n\n## Why is this bad?\nRaising `StopIteration` in a generator function causes a `RuntimeError`\nwhen the generator is iterated over.\n\nInstead of `raise StopIteration`, use `return` in generator functions.\n\n## Example\n```python\ndef my_generator():\n yield 1\n yield 2\n raise StopIteration # This causes RuntimeError at runtime\n```\n\nUse instead:\n```python\ndef my_generator():\n yield 1\n yield 2\n return # Use return instead\n```\n\n## References\n- [PEP 479](https://peps.python.org/pep-0479/)\n- [Python documentation](https://docs.python.org/3/library/exceptions.html#StopIteration)\n",
|
|
749
|
+
"ruff/PLR1711": "## What it does\nChecks for functions that end with an unnecessary `return` or\n`return None`, and contain no other `return` statements.\n\n## Why is this bad?\nPython implicitly assumes a `None` return at the end of a function, making\nit unnecessary to explicitly write `return None`.\n\n## Example\n```python\ndef f():\n print(5)\n return None\n```\n\nUse instead:\n```python\ndef f():\n print(5)\n```\n\n## Fix safety\nA trailing comment on the same line as the `return` statement is preserved.\nThe fix is marked as unsafe if it would delete any other comments, such as\ncomments inside a parenthesized return value.\n",
|
|
750
|
+
"ruff/PLR1712": "## What it does\nChecks for code that swaps two variables using a temporary variable.\n\n## Why is this bad?\nVariables can be swapped by using tuple unpacking instead of using a\ntemporary variable. That also makes the intention of the swapping logic\nmore clear.\n\n## Example\n```python\ndef function(x, y):\n if x > y:\n temp = x\n x = y\n y = temp\n assert x <= y\n```\n\nUse instead:\n```python\ndef function(x, y):\n if x > y:\n x, y = y, x\n assert x <= y\n```\n\n## Fix safety\nThe rule's fix is marked as safe, unless the replacement range contains comments\nthat would be removed.\n",
|
|
751
|
+
"ruff/PLR1714": "## What it does\nChecks for repeated equality comparisons that can be rewritten as a membership\ntest.\n\nThis rule will try to determine if the values are hashable\nand the fix will use a `set` if they are. If unable to determine, the fix\nwill use a `tuple` and suggest the use of a `set`.\n\n## Why is this bad?\nTo check if a variable is equal to one of many values, it is common to\nwrite a series of equality comparisons (e.g.,\n`foo == \"bar\" or foo == \"baz\"`).\n\nInstead, prefer to combine the values into a collection and use the `in`\noperator to check for membership, which is more performant and succinct.\nIf the items are hashable, use a `set` for efficiency; otherwise, use a\n`tuple`.\n\n## Fix safety\nThis rule is always unsafe since literal sets and tuples\nevaluate their members eagerly whereas `or` comparisons\nare short-circuited. It is therefore possible that a fix\nwill change behavior in the presence of side-effects.\n\n## Example\n```python\nfoo == \"bar\" or foo == \"baz\" or foo == \"qux\"\n```\n\nUse instead:\n```python\nfoo in {\"bar\", \"baz\", \"qux\"}\n```\n\n## References\n- [Python documentation: Comparisons](https://docs.python.org/3/reference/expressions.html#comparisons)\n- [Python documentation: Membership test operations](https://docs.python.org/3/reference/expressions.html#membership-test-operations)\n- [Python documentation: `set`](https://docs.python.org/3/library/stdtypes.html#set)\n",
|
|
752
|
+
"ruff/PLR1716": "## What it does\nCheck for chained boolean operations that can be simplified.\n\n## Why is this bad?\nRefactoring the code will improve readability for these cases.\n\n## Example\n\n```python\na = int(input())\nb = int(input())\nc = int(input())\nif a < b and b < c:\n pass\n```\n\nUse instead:\n\n```python\na = int(input())\nb = int(input())\nc = int(input())\nif a < b < c:\n pass\n```\n",
|
|
753
|
+
"ruff/PLR1722": "## What it does\nChecks for uses of the `exit()` and `quit()`.\n\n## Why is this bad?\n`exit` and `quit` come from the `site` module, which is typically imported\nautomatically during startup. However, it is not _guaranteed_ to be\nimported, and so using these functions may result in a `NameError` at\nruntime. Generally, these constants are intended to be used in an interactive\ninterpreter, and not in programs.\n\nPrefer `sys.exit()`, as the `sys` module is guaranteed to exist in all\ncontexts.\n\n## Fix safety\nThis fix is always unsafe. When replacing `exit` or `quit` with `sys.exit`,\nthe behavior can change in the following ways:\n\n1. If the code runs in an environment where the `site` module is not imported\n (e.g., with `python -S`), the original code would raise a `NameError`, while\n the fixed code would execute normally.\n\n2. `site.exit` and `sys.exit` handle tuple arguments differently. `site.exit`\n treats tuples as regular objects and always returns exit code 1, while `sys.exit`\n interprets tuple contents to determine the exit code: an empty tuple () results in\n exit code 0, and a single-element tuple like (2,) uses that element's value (2) as\n the exit code.\n\n## Example\n```python\nif __name__ == \"__main__\":\n exit()\n```\n\nUse instead:\n```python\nimport sys\n\nif __name__ == \"__main__\":\n sys.exit()\n```\n\n## References\n- [Python documentation: Constants added by the `site` module](https://docs.python.org/3/library/constants.html#constants-added-by-the-site-module)\n",
|
|
754
|
+
"ruff/PLR1730": "## What it does\nChecks for `if` statements that can be replaced with `min()` or `max()`\ncalls.\n\n## Why is this bad?\nAn `if` statement that selects the lesser or greater of two sub-expressions\ncan be replaced with a `min()` or `max()` call respectively. Where possible,\nprefer `min()` and `max()`, as they're more concise and readable than the\nequivalent `if` statements.\n\n## Example\n```python\nif score > highest_score:\n highest_score = score\n```\n\nUse instead:\n```python\nhighest_score = max(highest_score, score)\n```\n\n## Fix safety\nThis fix is marked unsafe if it would delete any comments within the replacement range.\n\nAn example to illustrate where comments are preserved and where they are not:\n\n```py\na, b = 0, 10\n\nif a >= b: # deleted comment\n # deleted comment\n a = b # preserved comment\n```\n\n## References\n- [Python documentation: `max`](https://docs.python.org/3/library/functions.html#max)\n- [Python documentation: `min`](https://docs.python.org/3/library/functions.html#min)\n",
|
|
755
|
+
"ruff/PLR1733": "## What it does\nChecks for key-based dict accesses during `.items()` iterations.\n\n## Why is this bad?\nWhen iterating over a dict via `.items()`, the current value is already\navailable alongside its key. Using the key to look up the value is\nunnecessary.\n\n## Example\n```python\nFRUITS = {\"apple\": 1, \"orange\": 10, \"berry\": 22}\n\nfor fruit_name, fruit_count in FRUITS.items():\n print(FRUITS[fruit_name])\n```\n\nUse instead:\n```python\nFRUITS = {\"apple\": 1, \"orange\": 10, \"berry\": 22}\n\nfor fruit_name, fruit_count in FRUITS.items():\n print(fruit_count)\n```\n",
|
|
756
|
+
"ruff/PLR1736": "## What it does\nChecks for index-based list accesses during `enumerate` iterations.\n\n## Why is this bad?\nWhen iterating over a list with `enumerate`, the current item is already\navailable alongside its index. Using the index to look up the item is\nunnecessary.\n\n## Example\n```python\nletters = [\"a\", \"b\", \"c\"]\n\nfor index, letter in enumerate(letters):\n print(letters[index])\n```\n\nUse instead:\n```python\nletters = [\"a\", \"b\", \"c\"]\n\nfor index, letter in enumerate(letters):\n print(letter)\n```\n",
|
|
757
|
+
"ruff/PLR2044": "## What it does\nChecks for a # symbol appearing on a line not followed by an actual comment.\n\n## Why is this bad?\nEmpty comments don't provide any clarity to the code, and just add clutter.\nEither add a comment or delete the empty comment.\n\n## Example\n```python\nclass Foo: #\n pass\n```\n\nUse instead:\n```python\nclass Foo:\n pass\n```\n\n## References\n- [Pylint documentation](https://pylint.pycqa.org/en/latest/user_guide/messages/refactor/empty-comment.html)\n",
|
|
758
|
+
"ruff/PLR5501": "## What it does\nChecks for `else` blocks that consist of a single `if` statement.\n\n## Why is this bad?\nIf an `else` block contains a single `if` statement, it can be collapsed\ninto an `elif`, thus reducing the indentation level.\n\n## Example\n```python\ndef check_sign(value: int) -> None:\n if value > 0:\n print(\"Number is positive.\")\n else:\n if value < 0:\n print(\"Number is negative.\")\n else:\n print(\"Number is zero.\")\n```\n\nUse instead:\n```python\ndef check_sign(value: int) -> None:\n if value > 0:\n print(\"Number is positive.\")\n elif value < 0:\n print(\"Number is negative.\")\n else:\n print(\"Number is zero.\")\n```\n\n## Fix safety\nThis fix is marked unsafe if the `else` line has a trailing comment (e.g., `else: # comment`),\nsince the fix deletes the comment.\n\n## References\n- [Python documentation: `if` Statements](https://docs.python.org/3/tutorial/controlflow.html#if-statements)\n",
|
|
759
|
+
"ruff/PLR6104": "## What it does\nChecks for assignments that can be replaced with augmented assignment\nstatements.\n\n## Why is this bad?\nIf the right-hand side of an assignment statement consists of a binary\noperation in which one operand is the same as the assignment target,\nit can be rewritten as an augmented assignment. For example, `x = x + 1`\ncan be rewritten as `x += 1`.\n\nWhen performing such an operation, an augmented assignment is more concise\nand idiomatic.\n\n## Known problems\nIn some cases, this rule will not detect assignments in which the target\nis on the right-hand side of a binary operation (e.g., `x = y + x`, as\nopposed to `x = x + y`), as such operations are not commutative for\ncertain data types, like strings.\n\nFor example, `x = \"prefix-\" + x` is not equivalent to `x += \"prefix-\"`,\nwhile `x = 1 + x` is equivalent to `x += 1`.\n\nIf the type of the left-hand side cannot be trivially inferred, the rule\nwill ignore the assignment.\n\n## Example\n```python\nx = x + 1\n```\n\nUse instead:\n```python\nx += 1\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as augmented assignments have\ndifferent semantics when the target is a mutable data type, like a list or\ndictionary.\n\nFor example, consider the following:\n\n```python\nfoo = [1]\nbar = foo\nfoo = foo + [2]\nassert (foo, bar) == ([1, 2], [1])\n```\n\nIf the assignment is replaced with an augmented assignment, the update\noperation will apply to both `foo` and `bar`, as they refer to the same\nobject:\n\n```python\nfoo = [1]\nbar = foo\nfoo += [2]\nassert (foo, bar) == ([1, 2], [1, 2])\n```\n\nAn augmented assignment can also fail where the plain form succeeds. NumPy\nwrites the result into the target's buffer, so `a *= b` raises where\n`a = a * b` would broadcast to a new shape or promote the dtype. The same\napplies to `a @= b`, which requires the product to have the target's shape.\n\nThe fix replaces the whole statement, so any comments inside it are lost.\n",
|
|
760
|
+
"ruff/PLR6201": "## What it does\nChecks for membership tests on `list` and `tuple` literals.\n\n## Why is this bad?\nWhen testing for membership in a static sequence, prefer a `set` literal\nover a `list` or `tuple`, as Python optimizes `set` membership tests.\n\n## Example\n```python\n1 in [1, 2, 3]\n```\n\nUse instead:\n```python\n1 in {1, 2, 3}\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as the use of a `set` literal will\nerror at runtime if either the element being tested for membership (the\nleft-hand side) or any element of the sequence (the right-hand side)\nis unhashable (like lists or dictionaries). While Ruff will attempt to\ninfer the hashability of both sides and skip the fix when it can determine\nthat either side is unhashable, it may not always be able to do so.\n\n## References\n- [What\u2019s New In Python 3.2](https://docs.python.org/3/whatsnew/3.2.html#optimizations)\n",
|
|
761
|
+
"ruff/PLR6301": "## What it does\nChecks for the presence of unused `self` parameter in methods definitions.\n\n## Why is this bad?\nUnused `self` parameters are usually a sign of a method that could be\nreplaced by a function, class method, or static method.\n\nThis rule exempts methods decorated with [`@typing.override`][override].\nConverting an instance method into a static method or class method may\ncause type checkers to complain about a violation of the Liskov\nSubstitution Principle if it means that the method now incompatibly\noverrides a method defined on a superclass. Explicitly decorating an\noverriding method with `@override` signals to Ruff that the method is\nintended to override a superclass method and that a type checker will\nenforce that it does so; Ruff therefore knows that it should not enforce\nrules about unused `self` parameters on such methods.\n\n## Example\n```python\nclass Person:\n def greeting(self):\n print(\"Greetings friend!\")\n```\n\nUse instead:\n```python\ndef greeting():\n print(\"Greetings friend!\")\n```\n\nor\n\n```python\nclass Person:\n @staticmethod\n def greeting():\n print(\"Greetings friend!\")\n```\n\n## Options\n\nThe rule will not trigger on methods that are already marked as static or class methods.\n\n- `lint.pep8-naming.classmethod-decorators`\n- `lint.pep8-naming.staticmethod-decorators`\n\n[override]: https://docs.python.org/3/library/typing.html#typing.override\n",
|
|
762
|
+
"ruff/PLW0108": "## What it does\nChecks for `lambda` definitions that consist of a single function call\nwith the same arguments as the `lambda` itself.\n\n## Why is this bad?\nWhen a `lambda` is used to wrap a function call, and merely propagates\nthe `lambda` arguments to that function, it can typically be replaced with\nthe function itself, removing a level of indirection.\n\n## Example\n```python\ndf.apply(lambda x: str(x))\n```\n\nUse instead:\n```python\ndf.apply(str)\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe for two primary reasons.\n\nFirst, the lambda body itself could contain an effect.\n\nFor example, replacing `lambda x, y: (func()(x, y))` with `func()` would\nlead to a change in behavior, as `func()` would be evaluated eagerly when\ndefining the lambda, rather than when the lambda is called.\n\nHowever, even when the lambda body itself is pure, the lambda may\nchange the argument names, which can lead to a change in behavior when\ncallers pass arguments by name.\n\nFor example:\n\n```python\ndef func(a, b):\n return a + b\n\n\nfoo = lambda x, y: func(x, y)\n```\n\nReplacing the assignment to `foo` with `foo = func` would be a breaking\nchange for callers that execute the lambda by passing arguments by name, as\nin: `foo(x=1, y=2)`. Since `func` does not define the arguments `x` and `y`,\nunlike the lambda, the call would raise a `TypeError`.\n",
|
|
763
|
+
"ruff/PLW0120": "## What it does\nChecks for `else` clauses on loops without a `break` statement.\n\n## Why is this bad?\nWhen a loop includes an `else` statement, the code inside the `else` clause\nwill be executed if the loop terminates \"normally\" (i.e., without a\n`break`).\n\nIf a loop _always_ terminates \"normally\" (i.e., does _not_ contain a\n`break`), then the `else` clause is redundant, as the code inside the\n`else` clause will always be executed.\n\nIn such cases, the code inside the `else` clause can be moved outside the\nloop entirely, and the `else` clause can be removed.\n\n## Example\n```python\nfor item in items:\n print(item)\nelse:\n print(\"All items printed\")\n```\n\nUse instead:\n```python\nfor item in items:\n print(item)\nprint(\"All items printed\")\n```\n\n## Fix safety\nThis fix is marked unsafe if the `else` line has a trailing comment (e.g., `else: # comment`),\nsince the fix deletes the comment.\n\n## References\n- [Python documentation: `break` and `continue` Statements, and `else` Clauses on Loops](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops)\n",
|
|
764
|
+
"ruff/PLW0127": "## What it does\nChecks for self-assignment of variables.\n\n## Why is this bad?\nSelf-assignment of variables is redundant and likely a mistake.\n\n## Example\n```python\ncountry = \"Poland\"\ncountry = country\n```\n\nUse instead:\n```python\ncountry = \"Poland\"\n```\n",
|
|
765
|
+
"ruff/PLW0128": "## What it does\nChecks for declared assignments to the same variable multiple times\nin the same assignment.\n\n## Why is this bad?\nAssigning a variable multiple times in the same assignment is redundant,\nas the final assignment to the variable is what the value will be.\n\n## Example\n```python\na, b, a = (1, 2, 3)\nprint(a) # 3\n```\n\nUse instead:\n```python\n# this is assuming you want to assign 3 to `a`\n_, b, a = (1, 2, 3)\nprint(a) # 3\n```\n\n## Options\n\nThe rule ignores assignments to dummy variables, as specified by:\n\n- `lint.dummy-variable-rgx`\n",
|
|
766
|
+
"ruff/PLW0129": "## What it does\nChecks for `assert` statements that use a string literal as the first\nargument.\n\n## Why is this bad?\nAn `assert` on a non-empty string literal will always pass, while an\n`assert` on an empty string literal will always fail.\n\n## Example\n```python\nassert \"always true\"\n```\n",
|
|
767
|
+
"ruff/PLW0131": "## What it does\nChecks for uses of named expressions (e.g., `a := 42`) that can be\nreplaced by regular assignment statements (e.g., `a = 42`).\n\n## Why is this bad?\nWhile a top-level named expression is syntactically and semantically valid,\nit's less clear than a regular assignment statement. Named expressions are\nintended to be used in comprehensions and generator expressions, where\nassignment statements are not allowed.\n\n## Example\n```python\n(a := 42)\n```\n\nUse instead:\n```python\na = 42\n```\n",
|
|
768
|
+
"ruff/PLW0133": "## What it does\nChecks for an exception that is not raised.\n\n## Why is this bad?\nIt's unnecessary to create an exception without raising it. For example,\n`ValueError(\"...\")` on its own will have no effect (unlike\n`raise ValueError(\"...\")`) and is likely a mistake.\n\n## Known problems\nThis rule only detects built-in exceptions, like `ValueError`, and does\nnot catch user-defined exceptions.\n\nIn [preview], this rule will also detect user-defined exceptions, but only\nthe ones defined in the file being checked.\n\n## Example\n```python\nValueError(\"...\")\n```\n\nUse instead:\n```python\nraise ValueError(\"...\")\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as converting a useless exception\nstatement to a `raise` statement will change the program's behavior.\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
769
|
+
"ruff/PLW0177": "## What it does\nChecks for comparisons against NaN values.\n\n## Why is this bad?\nComparing against a NaN value can lead to unexpected results. For example,\n`float(\"NaN\") == float(\"NaN\")` will return `False` and, in general,\n`x == float(\"NaN\")` will always return `False`, even if `x` is `NaN`.\n\nTo determine whether a value is `NaN`, use `math.isnan` or `np.isnan`\ninstead of comparing against `NaN` directly.\n\n## Example\n```python\nif x == float(\"NaN\"):\n pass\n```\n\nUse instead:\n```python\nimport math\n\nif math.isnan(x):\n pass\n```\n",
|
|
770
|
+
"ruff/PLW0211": "## What it does\nChecks for static methods that use `self` or `cls` as their first argument.\nThis rule also applies to `__new__` methods, which are implicitly static.\n\n## Why is this bad?\n[PEP 8] recommends the use of `self` and `cls` as the first arguments for\ninstance methods and class methods, respectively. Naming the first argument\nof a static method as `self` or `cls` can be misleading, as static methods\ndo not receive an instance or class reference as their first argument.\n\n## Example\n```python\nclass Wolf:\n @staticmethod\n def eat(self):\n pass\n```\n\nUse instead:\n```python\nclass Wolf:\n @staticmethod\n def eat(sheep):\n pass\n```\n\n## Options\n\n- `lint.pep8-naming.classmethod-decorators`\n- `lint.pep8-naming.staticmethod-decorators`\n\n[PEP 8]: https://peps.python.org/pep-0008/#function-and-method-arguments\n",
|
|
771
|
+
"ruff/PLW0244": "## What it does\nChecks for a re-defined slot in a subclass.\n\n## Why is this bad?\nIf a class defines a slot also defined in a base class, the\ninstance variable defined by the base class slot is inaccessible\n(except by retrieving its descriptor directly from the base class).\n\n## Example\n```python\nclass Base:\n __slots__ = (\"a\", \"b\")\n\n\nclass Subclass(Base):\n __slots__ = (\"a\", \"d\") # slot \"a\" redefined\n```\n\nUse instead:\n```python\nclass Base:\n __slots__ = (\"a\", \"b\")\n\n\nclass Subclass(Base):\n __slots__ = \"d\"\n```\n",
|
|
772
|
+
"ruff/PLW0245": "## What it does\nDetects attempts to use `super` without parentheses.\n\n## Why is this bad?\nThe [`super()` callable](https://docs.python.org/3/library/functions.html#super)\ncan be used inside method definitions to create a proxy object that\ndelegates attribute access to a superclass of the current class. Attempting\nto access attributes on `super` itself, however, instead of the object\nreturned by a call to `super()`, will raise `AttributeError`.\n\n## Example\n```python\nclass Animal:\n @staticmethod\n def speak():\n return \"This animal says something.\"\n\n\nclass Dog(Animal):\n @staticmethod\n def speak():\n original_speak = super.speak() # ERROR: `super.speak()`\n return f\"{original_speak} But as a dog, it barks!\"\n```\n\nUse instead:\n```python\nclass Animal:\n @staticmethod\n def speak():\n return \"This animal says something.\"\n\n\nclass Dog(Animal):\n @staticmethod\n def speak():\n original_speak = super().speak() # Correct: `super().speak()`\n return f\"{original_speak} But as a dog, it barks!\"\n```\n\n## Options\n\nThis rule applies to regular, static, and class methods. You can customize how Ruff categorizes\nmethods with the following options:\n\n- `lint.pep8-naming.classmethod-decorators`\n- `lint.pep8-naming.staticmethod-decorators`\n",
|
|
773
|
+
"ruff/PLW0406": "## What it does\nChecks for import statements that import the current module.\n\n## Why is this bad?\nImporting a module from itself is a circular dependency and results\nin an `ImportError` exception.\n\n## Example\n\n```python\n# file: this_file.py\nfrom this_file import foo\n\n\ndef foo(): ...\n```\n",
|
|
774
|
+
"ruff/PLW0602": "## What it does\nChecks for `global` variables that are not assigned a value in the current\nscope.\n\n## Why is this bad?\nThe `global` keyword allows an inner scope to modify a variable declared\nin the outer scope. If the variable is not modified within the inner scope,\nthere is no need to use `global`.\n\n## Example\n```python\nDEBUG = True\n\n\ndef foo():\n global DEBUG\n if DEBUG:\n print(\"foo() called\")\n ...\n```\n\nUse instead:\n```python\nDEBUG = True\n\n\ndef foo():\n if DEBUG:\n print(\"foo() called\")\n ...\n```\n\n## References\n- [Python documentation: The `global` statement](https://docs.python.org/3/reference/simple_stmts.html#the-global-statement)\n",
|
|
775
|
+
"ruff/PLW0603": "## What it does\nChecks for the use of `global` statements to update identifiers.\n\n## Why is this bad?\nPylint discourages the use of `global` variables as global mutable\nstate is a common source of bugs and confusing behavior.\n\n## Example\n```python\nvar = 1\n\n\ndef foo():\n global var # [global-statement]\n var = 10\n print(var)\n\n\nfoo()\nprint(var)\n```\n\nUse instead:\n```python\nvar = 1\n\n\ndef foo():\n var = 10\n print(var)\n return var\n\n\nvar = foo()\nprint(var)\n```\n",
|
|
776
|
+
"ruff/PLW0604": "## What it does\nChecks for uses of the `global` keyword at the module level.\n\n## Why is this bad?\nThe `global` keyword is used within functions to indicate that a name\nrefers to a global variable, rather than a local variable.\n\nAt the module level, all names are global by default, so the `global`\nkeyword is redundant.\n",
|
|
777
|
+
"ruff/PLW0642": "## What it does\nChecks for assignment of `self` and `cls` in instance and class methods respectively.\n\nThis check also applies to `__new__` even though this is technically\na static method.\n\n## Why is this bad?\nThe identifiers `self` and `cls` are conventional in Python for the first parameter of instance\nmethods and class methods, respectively. Assigning new values to these variables can be\nconfusing for others reading your code; using a different variable name can lead to clearer\ncode.\n\n## Example\n\n```python\nclass Version:\n def add(self, other):\n self = self + other\n return self\n\n @classmethod\n def superclass(cls):\n cls = cls.__mro__[-1]\n return cls\n```\n\nUse instead:\n```python\nclass Version:\n def add(self, other):\n new_version = self + other\n return new_version\n\n @classmethod\n def superclass(cls):\n supercls = cls.__mro__[-1]\n return supercls\n```\n\n## Options\n\n- `lint.pep8-naming.classmethod-decorators`\n- `lint.pep8-naming.staticmethod-decorators`\n",
|
|
778
|
+
"ruff/PLW0711": "## What it does\nChecks for `except` clauses that attempt to catch multiple\nexceptions with a binary operation (`and` or `or`).\n\n## Why is this bad?\nA binary operation will not catch multiple exceptions. Instead, the binary\noperation will be evaluated first, and the result of _that_ operation will\nbe caught (for an `or` operation, this is typically the first exception in\nthe list). This is almost never the desired behavior.\n\n## Example\n```python\ntry:\n pass\nexcept A or B:\n pass\n```\n\nUse instead:\n```python\ntry:\n pass\nexcept (A, B):\n pass\n```\n",
|
|
779
|
+
"ruff/PLW0717": "## What it does\nChecks for try clauses with too many statements.\n\nBy default, this rule allows up to 5 statements, as configured by the\n[`lint.pylint.max-statements-in-try`] option.\n\n## Why is this bad?\nTry clauses with many statements make unexpected exceptions harder\nto detect and debug.\n\nInstead, consider narrowing the try clause to only encompass code that\nmay raise exceptions you can anticipate or know about, moving all other\nstatements either before or after the try clause, or factoring out a helper function.\n\n## Example\n```python\nfrom random import randint\n\n\ndef random_ratio() -> float:\n try:\n a = randint(-100, 100)\n b = randint(-100, 100)\n c = randint(-100, 100)\n d = randint(-100, 100)\n scale = randint(1, 5)\n res = scale * (a + b) / (c + d)\n except ZeroDivisionError:\n return random_ratio()\n else:\n return res\n```\n\nUse instead:\n```python\nfrom random import randint\n\n\ndef random_ratio() -> float:\n a = randint(-100, 100)\n b = randint(-100, 100)\n c = randint(-100, 100)\n d = randint(-100, 100)\n scale = randint(1, 5)\n try:\n # every statement that cannot raise was moved outside the try clause\n res = scale * (a + b) / (c + d)\n except ZeroDivisionError:\n return random_ratio()\n else:\n return res\n```\n\n## Options\n- `lint.pylint.max-statements-in-try`\n\n## References\n\n[Pylint's reference implementation](https://pylint.pycqa.org/en/latest/user_guide/configuration/all-options.html#broad-try-clause-checker)\nuses a different default setting.\nTo replicate it exactly, set `lint.pylint.max-statements-in-try` to 1.\n",
|
|
780
|
+
"ruff/PLW1501": "## What it does\nCheck for an invalid `mode` argument in `open` calls.\n\n## Why is this bad?\nThe `open` function accepts a `mode` argument that specifies how the file\nshould be opened (e.g., read-only, write-only, append-only, etc.).\n\nPython supports a variety of open modes: `r`, `w`, `a`, and `x`, to control\nreading, writing, appending, and creating, respectively, along with\n`b` (binary mode), `+` (read and write), and `U` (universal newlines),\nthe latter of which is only valid alongside `r`. This rule detects both\ninvalid combinations of modes and invalid characters in the mode string\nitself.\n\n## Example\n```python\nwith open(\"file\", \"rwx\") as f:\n content = f.read()\n```\n\nUse instead:\n\n```python\nwith open(\"file\", \"r\") as f:\n content = f.read()\n```\n\n## References\n- [Python documentation: `open`](https://docs.python.org/3/library/functions.html#open)\n",
|
|
781
|
+
"ruff/PLW1507": "## What it does\nCheck for shallow `os.environ` copies.\n\n## Why is this bad?\n`os.environ` is not a `dict` object, but rather, a proxy object. As such, mutating a shallow\ncopy of `os.environ` will also mutate the original object.\n\nSee [BPO 15373] for more information.\n\n## Example\n```python\nimport copy\nimport os\n\nenv = copy.copy(os.environ)\n```\n\nUse instead:\n```python\nimport os\n\nenv = os.environ.copy()\n```\n\n## Fix safety\n\nThis rule's fix is marked as unsafe because replacing a shallow copy with a deep copy can lead\nto unintended side effects. If the program modifies the shallow copy at some point, changing it\nto a deep copy may prevent those modifications from affecting the original data, potentially\naltering the program's behavior.\n\n## References\n- [Python documentation: `copy` \u2014 Shallow and deep copy operations](https://docs.python.org/3/library/copy.html)\n- [Python documentation: `os.environ`](https://docs.python.org/3/library/os.html#os.environ)\n\n[BPO 15373]: https://bugs.python.org/issue15373\n",
|
|
782
|
+
"ruff/PLW1508": "## What it does\nChecks for `os.getenv` calls with invalid default values.\n\n## Why is this bad?\nIf an environment variable is set, `os.getenv` will return its value as\na string. If the environment variable is _not_ set, `os.getenv` will\nreturn `None`, or the default value if one is provided.\n\nIf the default value is not a string or `None`, then it will be\ninconsistent with the return type of `os.getenv`, which can lead to\nconfusing behavior.\n\n## Example\n```python\nimport os\n\nint(os.getenv(\"FOO\", 1))\n```\n\nUse instead:\n```python\nimport os\n\nint(os.getenv(\"FOO\", \"1\"))\n```\n",
|
|
783
|
+
"ruff/PLW1509": "## What it does\nChecks for uses of `subprocess.Popen` with a `preexec_fn` argument.\n\n## Why is this bad?\nThe `preexec_fn` argument is unsafe within threads as it can lead to\ndeadlocks. Furthermore, `preexec_fn` is [targeted for deprecation].\n\nInstead, consider using task-specific arguments such as `env`,\n`start_new_session`, and `process_group`. These are not prone to deadlocks\nand are more explicit.\n\n## Example\n```python\nimport os, subprocess\n\nsubprocess.Popen(foo, preexec_fn=os.setsid)\nsubprocess.Popen(bar, preexec_fn=os.setpgid(0, 0))\n```\n\nUse instead:\n```python\nimport subprocess\n\nsubprocess.Popen(foo, start_new_session=True)\nsubprocess.Popen(bar, process_group=0) # Introduced in Python 3.11\n```\n\n## References\n- [Python documentation: `subprocess.Popen`](https://docs.python.org/3/library/subprocess.html#popen-constructor)\n- [Why `preexec_fn` in `subprocess.Popen` may lead to deadlock?](https://discuss.python.org/t/why-preexec-fn-in-subprocess-popen-may-lead-to-deadlock/16908/2)\n\n[targeted for deprecation]: https://github.com/python/cpython/issues/82616\n",
|
|
784
|
+
"ruff/PLW1510": "## What it does\nChecks for uses of `subprocess.run` without an explicit `check` argument.\n\n## Why is this bad?\nBy default, `subprocess.run` does not check the return code of the process\nit runs. This can lead to silent failures.\n\nInstead, consider using `check=True` to raise an exception if the process\nfails, or set `check=False` explicitly to mark the behavior as intentional.\n\n## Example\n```python\nimport subprocess\n\nsubprocess.run([\"ls\", \"nonexistent\"]) # No exception raised.\n```\n\nUse instead:\n```python\nimport subprocess\n\nsubprocess.run([\"ls\", \"nonexistent\"], check=True) # Raises exception.\n```\n\nOr:\n```python\nimport subprocess\n\nsubprocess.run([\"ls\", \"nonexistent\"], check=False) # Explicitly no check.\n```\n\n## Fix safety\n\nThis rule's fix is marked as display-only because it's not clear whether the\npotential exception was meant to be ignored by setting `check=False` or if\nthe author simply forgot to include `check=True`. The fix adds\n`check=False`, making the existing behavior explicit but possibly masking\nthe original intention.\n\n## References\n- [Python documentation: `subprocess.run`](https://docs.python.org/3/library/subprocess.html#subprocess.run)\n",
|
|
785
|
+
"ruff/PLW1514": "## What it does\nChecks for uses of `open` and related calls without an explicit `encoding`\nargument.\n\n## Why is this bad?\nUsing `open` in text mode without an explicit encoding can lead to\nnon-portable code, with differing behavior across platforms. While readers\nmay assume that UTF-8 is the default encoding, in reality, the default\nis locale-specific.\n\nInstead, consider using the `encoding` parameter to enforce a specific\nencoding. [PEP 597] recommends the use of `encoding=\"utf-8\"` as a default,\nand suggests that it may become the default in future versions of Python.\n\nIf a locale-specific encoding is intended, use `encoding=\"locale\"` on\nPython 3.10 and later, or `locale.getpreferredencoding()` on earlier versions,\nto make the encoding explicit.\n\n## Fix safety\nThis fix is always unsafe and may change the program's behavior. It forces\n`encoding=\"utf-8\"` as the default, regardless of the platform\u2019s actual default\nencoding, which may cause `UnicodeDecodeError` on non-UTF-8 systems.\n```python\nwith open(\"test.txt\") as f:\n print(f.read()) # before fix (on UTF-8 systems): \u4f60\u597d\uff0c\u4e16\u754c\uff01\nwith open(\"test.txt\", encoding=\"utf-8\") as f:\n print(f.read()) # after fix (on Windows): UnicodeDecodeError\n```\n\n## Example\n```python\nopen(\"file.txt\")\n```\n\nUse instead:\n```python\nopen(\"file.txt\", encoding=\"utf-8\")\n```\n\n## References\n- [Python documentation: `open`](https://docs.python.org/3/library/functions.html#open)\n\n[PEP 597]: https://peps.python.org/pep-0597/\n",
|
|
786
|
+
"ruff/PLW1641": "## What it does\nChecks for classes that implement `__eq__` but not `__hash__`.\n\n## Why is this bad?\nA class that implements `__eq__` but not `__hash__` will have its hash\nmethod implicitly set to `None`, regardless of if a superclass defines\n`__hash__`. This will cause the class to be unhashable, which will in turn\ncause issues when using instances of the class as keys in a dictionary or\nmembers of a set.\n\n## Example\n\n```python\nclass Person:\n def __init__(self):\n self.name = \"monty\"\n\n def __eq__(self, other):\n return isinstance(other, Person) and other.name == self.name\n```\n\nUse instead:\n\n```python\nclass Person:\n def __init__(self):\n self.name = \"monty\"\n\n def __eq__(self, other):\n return isinstance(other, Person) and other.name == self.name\n\n def __hash__(self):\n return hash(self.name)\n```\n\nIn general, it is unsound to inherit a `__hash__` implementation from a parent class while\noverriding the `__eq__` implementation because the two must be kept in sync. However, an easy\nway to resolve this error in cases where it _is_ sound is to explicitly set `__hash__` to the\nparent class's implementation:\n\n```python\nclass Developer(Person):\n def __init__(self): ...\n\n def __eq__(self, other): ...\n\n __hash__ = Person.__hash__\n```\n\n## References\n- [Python documentation: `object.__hash__`](https://docs.python.org/3/reference/datamodel.html#object.__hash__)\n- [Python glossary: hashable](https://docs.python.org/3/glossary.html#term-hashable)\n",
|
|
787
|
+
"ruff/PLW2101": "## What it does\nChecks for lock objects that are created and immediately discarded in\n`with` statements.\n\n## Why is this bad?\nCreating a lock (via `threading.Lock` or similar) in a `with` statement\nhas no effect, as locks are only relevant when shared between threads.\n\nInstead, assign the lock to a variable outside the `with` statement,\nand share that variable between threads.\n\n## Example\n```python\nimport threading\n\ncounter = 0\n\n\ndef increment():\n global counter\n\n with threading.Lock():\n counter += 1\n```\n\nUse instead:\n```python\nimport threading\n\ncounter = 0\nlock = threading.Lock()\n\n\ndef increment():\n global counter\n\n with lock:\n counter += 1\n```\n\n## References\n- [Python documentation: `Lock Objects`](https://docs.python.org/3/library/threading.html#lock-objects)\n",
|
|
788
|
+
"ruff/PLW2901": "## What it does\nChecks for variables defined in `for` loops and `with` statements that\nget overwritten within the body, for example by another `for` loop or\n`with` statement or by direct assignment.\n\n## Why is this bad?\nRedefinition of a loop variable inside the loop's body causes its value\nto differ from the original loop iteration for the remainder of the\nblock, in a way that will likely cause bugs.\n\nIn Python, unlike many other languages, `for` loops and `with`\nstatements don't define their own scopes. Therefore, a nested loop that\nuses the same target variable name as an outer loop will reuse the same\nactual variable, and the value from the last iteration will \"leak out\"\ninto the remainder of the enclosing loop.\n\nWhile this mistake is easy to spot in small examples, it can be hidden\nin larger blocks of code, where the definition and redefinition of the\nvariable may not be visible at the same time.\n\n## Example\n```python\nfor i in range(10):\n i = 9\n print(i) # prints 9 every iteration\n\nfor i in range(10):\n for i in range(10): # original value overwritten\n pass\n print(i) # also prints 9 every iteration\n\nwith path1.open() as f:\n with path2.open() as f:\n f = path2.open()\n print(f.readline()) # prints a line from path2\n```\n\n## Options\n\nThe rule ignores assignments to dummy variables, as specified by:\n\n- `lint.dummy-variable-rgx`\n",
|
|
789
|
+
"ruff/PLW3201": "## What it does\nChecks for dunder methods that have no special meaning in Python 3.\n\n## Why is this bad?\nMisspelled or no longer supported dunder name methods may cause your code to not function\nas expected.\n\nSince dunder methods are associated with customizing the behavior\nof a class in Python, introducing a dunder method such as `__foo__`\nthat diverges from standard Python dunder methods could potentially\nconfuse someone reading the code.\n\nThis rule will detect all methods starting and ending with at least\none underscore (e.g., `_str_`), but ignores known dunder methods (like\n`__init__`), as well as methods that are marked with [`@override`][override].\n\nAdditional dunder methods names can be allowed via the\n[`lint.pylint.allow-dunder-method-names`] setting.\n\n## Example\n\n```python\nclass Foo:\n def __init_(self): ...\n```\n\nUse instead:\n\n```python\nclass Foo:\n def __init__(self): ...\n```\n\n## Options\n- `lint.pylint.allow-dunder-method-names`\n\n[override]: https://docs.python.org/3/library/typing.html#typing.override\n",
|
|
790
|
+
"ruff/PLW3301": "## What it does\nChecks for nested `min` and `max` calls.\n\n## Why is this bad?\nNested `min` and `max` calls can be flattened into a single call to improve\nreadability.\n\n## Example\n\n```python\nminimum = min(1, 2, min(3, 4, 5))\nmaximum = max(1, 2, max(3, 4, 5))\ndiff = maximum - minimum\n```\n\nUse instead:\n\n```python\nminimum = min(1, 2, 3, 4, 5)\nmaximum = max(1, 2, 3, 4, 5)\ndiff = maximum - minimum\n```\n\n## Known issues\n\nThe resulting code may be slower and use more memory, especially for nested iterables. For\nexample, this code:\n\n```python\niterable = range(3)\nmin(1, min(iterable))\n```\n\nwill be fixed to:\n\n```python\niterable = range(3)\nmin(1, *iterable)\n```\n\nAt least on current versions of CPython, this allocates a collection for the whole iterable\nbefore calling `min` and could cause performance regressions, at least for large iterables.\n\n## Fix safety\n\nThis fix is always unsafe and may change the program's behavior for types without full\nequivalence relations, such as float comparisons involving `NaN`.\n\n```python\nprint(min(2.0, min(float(\"nan\"), 1.0))) # before fix: 2.0\nprint(min(2.0, float(\"nan\"), 1.0)) # after fix: 1.0\n\nprint(max(1.0, max(float(\"nan\"), 2.0))) # before fix: 1.0\nprint(max(1.0, float(\"nan\"), 2.0)) # after fix: 2.0\n```\n\nThe fix will also remove any comments within the outer call.\n\n## References\n- [Python documentation: `min`](https://docs.python.org/3/library/functions.html#min)\n- [Python documentation: `max`](https://docs.python.org/3/library/functions.html#max)\n",
|
|
791
|
+
"ruff/UP001": "## What it does\nChecks for the use of `__metaclass__ = type` in class definitions.\n\n## Why is this bad?\nSince Python 3, `__metaclass__ = type` is implied and can thus be omitted.\n\n## Example\n\n```python\nclass Foo:\n __metaclass__ = type\n```\n\nUse instead:\n\n```python\nclass Foo: ...\n```\n\n## References\n- [PEP 3115 \u2013 Metaclasses in Python 3000](https://peps.python.org/pep-3115/)\n",
|
|
792
|
+
"ruff/UP003": "## What it does\nChecks for uses of `type` that take a primitive as an argument.\n\n## Why is this bad?\n`type()` returns the type of a given object. A type of a primitive can\nalways be known in advance and accessed directly, which is more concise\nand explicit than using `type()`.\n\n## Example\n```python\ntype(1)\n```\n\nUse instead:\n```python\nint\n```\n\n## References\n- [Python documentation: `type()`](https://docs.python.org/3/library/functions.html#type)\n- [Python documentation: Built-in types](https://docs.python.org/3/library/stdtypes.html)\n",
|
|
793
|
+
"ruff/UP004": "## What it does\nChecks for classes that inherit from `object`.\n\n## Why is this bad?\nSince Python 3, all classes inherit from `object` by default, so `object` can\nbe omitted from the list of base classes.\n\n## Example\n\n```python\nclass Foo(object): ...\n```\n\nUse instead:\n\n```python\nclass Foo: ...\n```\n\n## Fix safety\nThis fix is unsafe if it would cause comments to be deleted.\n\n## References\n- [PEP 3115 \u2013 Metaclasses in Python 3000](https://peps.python.org/pep-3115/)\n",
|
|
794
|
+
"ruff/UP005": "## What it does\nChecks for uses of deprecated methods from the `unittest` module.\n\n## Why is this bad?\nThe `unittest` module has deprecated aliases for some of its methods.\nThe deprecated aliases were removed in Python 3.12. Instead of aliases,\nuse their non-deprecated counterparts.\n\n## Example\n```python\nfrom unittest import TestCase\n\n\nclass SomeTest(TestCase):\n def test_something(self):\n self.assertEquals(1, 1)\n```\n\nUse instead:\n```python\nfrom unittest import TestCase\n\n\nclass SomeTest(TestCase):\n def test_something(self):\n self.assertEqual(1, 1)\n```\n\n## References\n- [Python 3.11 documentation: Deprecated aliases](https://docs.python.org/3.11/library/unittest.html#deprecated-aliases)\n",
|
|
795
|
+
"ruff/UP006": "## What it does\nChecks for the use of generics that can be replaced with standard library\nvariants based on [PEP 585].\n\n## Why is this bad?\n[PEP 585] enabled collections in the Python standard library (like `list`)\nto be used as generics directly, instead of importing analogous members\nfrom the `typing` module (like `typing.List`).\n\nWhen available, the [PEP 585] syntax should be used instead of importing\nmembers from the `typing` module, as it's more concise and readable.\nImporting those members from `typing` is considered deprecated as of [PEP\n585].\n\nThis rule is enabled when targeting Python 3.9 or later (see:\n[`target-version`]). By default, it's _also_ enabled for earlier Python\nversions if `from __future__ import annotations` is present, as\n`__future__` annotations are not evaluated at runtime. If your code relies\non runtime type annotations (either directly or via a library like\nPydantic), you can disable this behavior for Python versions prior to 3.9\nby setting [`lint.pyupgrade.keep-runtime-typing`] to `true`.\n\n## Example\n```python\nfrom typing import List\n\nfoo: List[int] = [1, 2, 3]\n```\n\nUse instead:\n```python\nfoo: list[int] = [1, 2, 3]\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as it may lead to runtime errors when\nalongside libraries that rely on runtime type annotations, like Pydantic,\non Python versions prior to Python 3.9.\n\nIn [preview], this rule can also add its own `__future__` import on Python\n3.9 and earlier, if the [`lint.future-annotations`] setting is enabled. This\nalso makes the fix unsafe.\n\n## Options\n- `target-version`\n- `lint.pyupgrade.keep-runtime-typing`\n- `lint.future-annotations`\n\n[PEP 585]: https://peps.python.org/pep-0585/\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
796
|
+
"ruff/UP007": "## What it does\nCheck for type annotations that can be rewritten based on [PEP 604] syntax.\n\n## Why is this bad?\n[PEP 604] introduced a new syntax for union type annotations based on the\n`|` operator. This syntax is more concise and readable than the previous\n`typing.Union` and `typing.Optional` syntaxes.\n\nThis rule is enabled when targeting Python 3.10 or later (see:\n[`target-version`]). By default, it's _also_ enabled for earlier Python\nversions if `from __future__ import annotations` is present, as\n`__future__` annotations are not evaluated at runtime. If your code relies\non runtime type annotations (either directly or via a library like\nPydantic), you can disable this behavior for Python versions prior to 3.10\nby setting [`lint.pyupgrade.keep-runtime-typing`] to `true`.\n\n## Example\n```python\nfrom typing import Union\n\nfoo: Union[int, str] = 1\n```\n\nUse instead:\n```python\nfoo: int | str = 1\n```\n\nNote that this rule only checks for usages of `typing.Union`,\nwhile `UP045` checks for `typing.Optional`.\n\n## Fix safety\nThis rule's fix is marked as unsafe on Python versions prior to 3.10 because\nusing the PEP-604 syntax may lead to runtime errors in libraries that rely\non runtime type annotations, like Pydantic, or in unusual and likely\nincorrect type annotations where the type does not support the `|`\noperator. The fix is also marked as unsafe when it would remove comments\npresent within the type annotation being rewritten.\n\nIn [preview], this rule can also add its own `__future__` import on Python\n3.9 and earlier, if the [`lint.future-annotations`] setting is enabled. This\nalso makes the fix unsafe.\n\n## Options\n- `target-version`\n- `lint.pyupgrade.keep-runtime-typing`\n- `lint.future-annotations`\n\n[PEP 604]: https://peps.python.org/pep-0604/\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
797
|
+
"ruff/UP008": "## What it does\nChecks for `super` calls that pass redundant arguments.\n\n## Why is this bad?\nIn Python 3, `super` can be invoked without any arguments when: (1) the\nfirst argument is `__class__`, and (2) the second argument is equivalent to\nthe first argument of the enclosing method.\n\nWhen possible, omit the arguments to `super` to make the code more concise\nand maintainable.\n\n## Example\n```python\nclass A:\n def foo(self):\n pass\n\n\nclass B(A):\n def bar(self):\n super(B, self).foo()\n```\n\nUse instead:\n```python\nclass A:\n def foo(self):\n pass\n\n\nclass B(A):\n def bar(self):\n super().foo()\n```\n\n## Fix safety\n\nThis rule's fix is marked as unsafe because removing the arguments from a call\nmay delete comments that are attached to the arguments.\n\n## References\n- [Python documentation: `super`](https://docs.python.org/3/library/functions.html#super)\n- [super/MRO, Python's most misunderstood feature.](https://www.youtube.com/watch?v=X1PQ7zzltz4)\n",
|
|
798
|
+
"ruff/UP009": "## What it does\nChecks for unnecessary UTF-8 encoding declarations.\n\n## Why is this bad?\n[PEP 3120] makes UTF-8 the default encoding, so a UTF-8 encoding\ndeclaration is unnecessary.\n\n## Example\n```python\n# -*- coding: utf-8 -*-\nprint(\"Hello, world!\")\n```\n\nUse instead:\n```python\nprint(\"Hello, world!\")\n```\n\n[PEP 3120]: https://peps.python.org/pep-3120/\n",
|
|
799
|
+
"ruff/UP010": "## What it does\nChecks for unnecessary `__future__` imports.\n\n## Why is this bad?\nThe `__future__` module is used to enable features that are not yet\navailable in the current Python version. If a feature is already\navailable in the minimum supported Python version, importing it\nfrom `__future__` is unnecessary and should be removed to avoid\nconfusion.\n\n## Example\n```python\nfrom __future__ import print_function\n\nprint(\"Hello, world!\")\n```\n\nUse instead:\n```python\nprint(\"Hello, world!\")\n```\n\n## Fix safety\nThis fix is marked unsafe if applying it would delete a comment.\n\n## Options\n- `target-version`\n\n## References\n- [Python documentation: `__future__` \u2014 Future statement definitions](https://docs.python.org/3/library/__future__.html)\n",
|
|
800
|
+
"ruff/UP011": "## What it does\nChecks for unnecessary parentheses on `functools.lru_cache` decorators.\n\n## Why is this bad?\nSince Python 3.8, `functools.lru_cache` can be used as a decorator without\ntrailing parentheses, as long as no arguments are passed to it.\n\n## Example\n\n```python\nimport functools\n\n\n@functools.lru_cache()\ndef foo(): ...\n```\n\nUse instead:\n\n```python\nimport functools\n\n\n@functools.lru_cache\ndef foo(): ...\n```\n\n## Options\n- `target-version`\n\n## References\n- [Python documentation: `@functools.lru_cache`](https://docs.python.org/3/library/functools.html#functools.lru_cache)\n- [Let lru_cache be used as a decorator with no arguments](https://github.com/python/cpython/issues/80953)\n",
|
|
801
|
+
"ruff/UP012": "## What it does\nChecks for unnecessary calls to `encode` as UTF-8 and unnecessary explicit\nUTF-8 encoding arguments.\n\n## Why is this bad?\nUTF-8 is the default encoding in Python, so there is no need to pass an\nexplicit UTF-8 encoding to `encode`. For ASCII literals, use a bytes literal\ninstead; for other strings, omit the explicit encoding argument.\n\n## Example\n```python\n\"foo\".encode(\"utf-8\")\n\"unicode text\u00a9\".encode(encoding=\"utf-8\")\n```\n\nUse instead:\n```python\nb\"foo\"\n\"unicode text\u00a9\".encode()\n```\n\n## References\n- [Python documentation: `str.encode`](https://docs.python.org/3/library/stdtypes.html#str.encode)\n",
|
|
802
|
+
"ruff/UP013": "## What it does\nChecks for `TypedDict` declarations that use functional syntax.\n\n## Why is this bad?\n`TypedDict` types can be defined either through a functional syntax\n(`Foo = TypedDict(...)`) or a class syntax (`class Foo(TypedDict): ...`).\n\nThe class syntax is more readable and generally preferred over the\nfunctional syntax.\n\nNonetheless, there are some situations in which it is impossible to use\nthe class-based syntax. This rule will not apply to those cases. Namely,\nit is impossible to use the class-based syntax if any `TypedDict` fields are:\n- Not valid [python identifiers] (for example, `@x`)\n- [Python keywords] such as `in`\n- [Private names] such as `__id` that would undergo [name mangling] at runtime\n if the class-based syntax was used\n- [Dunder names] such as `__int__` that can confuse type checkers if they're used\n with the class-based syntax.\n\n## Example\n```python\nfrom typing import TypedDict\n\nFoo = TypedDict(\"Foo\", {\"a\": int, \"b\": str})\n```\n\nUse instead:\n```python\nfrom typing import TypedDict\n\n\nclass Foo(TypedDict):\n a: int\n b: str\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe if there are any comments within the\nrange of the `TypedDict` definition, as these will be dropped by the\nautofix.\n\n## References\n- [Python documentation: `typing.TypedDict`](https://docs.python.org/3/library/typing.html#typing.TypedDict)\n\n[Private names]: https://docs.python.org/3/tutorial/classes.html#private-variables\n[name mangling]: https://docs.python.org/3/reference/expressions.html#private-name-mangling\n[python identifiers]: https://docs.python.org/3/reference/lexical_analysis.html#identifiers\n[Python keywords]: https://docs.python.org/3/reference/lexical_analysis.html#keywords\n[Dunder names]: https://docs.python.org/3/reference/lexical_analysis.html#reserved-classes-of-identifiers\n",
|
|
803
|
+
"ruff/UP014": "## What it does\nChecks for `NamedTuple` declarations that use functional syntax.\n\n## Why is this bad?\n`NamedTuple` subclasses can be defined either through a functional syntax\n(`Foo = NamedTuple(...)`) or a class syntax (`class Foo(NamedTuple): ...`).\n\nThe class syntax is more readable and generally preferred over the\nfunctional syntax, which exists primarily for backwards compatibility\nwith `collections.namedtuple`.\n\n## Example\n```python\nfrom typing import NamedTuple\n\nFoo = NamedTuple(\"Foo\", [(\"a\", int), (\"b\", str)])\n```\n\nUse instead:\n```python\nfrom typing import NamedTuple\n\n\nclass Foo(NamedTuple):\n a: int\n b: str\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe if there are any comments within the\nrange of the `NamedTuple` definition, as these will be dropped by the\nautofix.\n\n## References\n- [Python documentation: `typing.NamedTuple`](https://docs.python.org/3/library/typing.html#typing.NamedTuple)\n",
|
|
804
|
+
"ruff/UP015": "## What it does\nChecks for redundant `open` mode arguments.\n\n## Why is this bad?\nRedundant `open` mode arguments are unnecessary and should be removed to\navoid confusion.\n\n## Example\n```python\nwith open(\"foo.txt\", \"r\") as f:\n ...\n```\n\nUse instead:\n```python\nwith open(\"foo.txt\") as f:\n ...\n```\n\n## References\n- [Python documentation: `open`](https://docs.python.org/3/library/functions.html#open)\n",
|
|
805
|
+
"ruff/UP017": "## What it does\nChecks for uses of `datetime.timezone.utc`.\n\n## Why is this bad?\nAs of Python 3.11, `datetime.UTC` is an alias for `datetime.timezone.utc`.\nThe alias is more readable and generally preferred over the full path.\n\n## Example\n```python\nimport datetime\n\ndatetime.timezone.utc\n```\n\nUse instead:\n```python\nimport datetime\n\ndatetime.UTC\n```\n\n## Fix safety\nThis rule's fix is marked as safe, unless the expression contains comments.\n\n## Options\n- `target-version`\n\n## References\n- [Python documentation: `datetime.UTC`](https://docs.python.org/3/library/datetime.html#datetime.UTC)\n",
|
|
806
|
+
"ruff/UP018": "## What it does\nChecks for unnecessary calls to `str`, `bytes`, `int`, `float`, `bool`, and `complex`.\n\n## Why is this bad?\nThe mentioned constructors can be replaced with their respective literal\nforms, which are more readable and idiomatic.\n\n## Example\n```python\nstr(\"foo\")\n```\n\nUse instead:\n```python\n\"foo\"\n```\n\n## Fix safety\nThe fix is marked as unsafe if it might remove comments.\n\n## References\n- [Python documentation: `str`](https://docs.python.org/3/library/stdtypes.html#str)\n- [Python documentation: `bytes`](https://docs.python.org/3/library/stdtypes.html#bytes)\n- [Python documentation: `int`](https://docs.python.org/3/library/functions.html#int)\n- [Python documentation: `float`](https://docs.python.org/3/library/functions.html#float)\n- [Python documentation: `bool`](https://docs.python.org/3/library/functions.html#bool)\n- [Python documentation: `complex`](https://docs.python.org/3/library/functions.html#complex)\n",
|
|
807
|
+
"ruff/UP019": "## What it does\nChecks for uses of `typing.Text` and `typing_extensions.Text`.\n\n## Why is this bad?\n`typing.Text` is an alias for `str`, and only exists for Python 2\ncompatibility. As of Python 3.11, `typing.Text` is deprecated. Use `str`\ninstead.\n\n## Example\n```python\nfrom typing import Text\n\nfoo: Text = \"bar\"\n```\n\nUse instead:\n```python\nfoo: str = \"bar\"\n```\n\n## References\n- [Python documentation: `typing.Text`](https://docs.python.org/3/library/typing.html#typing.Text)\n",
|
|
808
|
+
"ruff/UP020": "## What it does\nChecks for uses of `io.open`.\n\n## Why is this bad?\nIn Python 3, `io.open` is an alias for `open`. Prefer using `open` directly,\nas it is more idiomatic.\n\n## Example\n```python\nimport io\n\nwith io.open(\"file.txt\") as f:\n ...\n```\n\nUse instead:\n```python\nwith open(\"file.txt\") as f:\n ...\n```\n## Fix safety\nThis rule's fix is marked as safe, unless the expression contains comments.\n\n## References\n- [Python documentation: `io.open`](https://docs.python.org/3/library/io.html#io.open)\n",
|
|
809
|
+
"ruff/UP021": "## What it does\nChecks for uses of `subprocess.run` that set the `universal_newlines`\nkeyword argument.\n\n## Why is this bad?\nAs of Python 3.7, the `universal_newlines` keyword argument has been\nrenamed to `text`, and now exists for backwards compatibility. The\n`universal_newlines` keyword argument may be removed in a future version of\nPython. Prefer `text`, which is more explicit and readable.\n\n## Example\n```python\nimport subprocess\n\nsubprocess.run([\"foo\"], universal_newlines=True)\n```\n\nUse instead:\n```python\nimport subprocess\n\nsubprocess.run([\"foo\"], text=True)\n```\n\n## References\n- [Python 3.7 release notes](https://docs.python.org/3/whatsnew/3.7.html#subprocess)\n- [Python documentation: `subprocess.run`](https://docs.python.org/3/library/subprocess.html#subprocess.run)\n",
|
|
810
|
+
"ruff/UP022": "## What it does\nChecks for uses of `subprocess.run` that send `stdout` and `stderr` to a\npipe.\n\n## Why is this bad?\nAs of Python 3.7, `subprocess.run` has a `capture_output` keyword argument\nthat can be set to `True` to capture `stdout` and `stderr` outputs. This is\nequivalent to setting `stdout` and `stderr` to `subprocess.PIPE`, but is\nmore explicit and readable.\n\n## Example\n```python\nimport subprocess\n\nsubprocess.run([\"foo\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n```\n\nUse instead:\n```python\nimport subprocess\n\nsubprocess.run([\"foo\"], capture_output=True)\n```\n\n## Fix safety\n\nThis rule's fix is marked as unsafe because replacing `stdout=subprocess.PIPE` and\n`stderr=subprocess.PIPE` with `capture_output=True` may delete comments attached\nto the original arguments.\n\n## References\n- [Python 3.7 release notes](https://docs.python.org/3/whatsnew/3.7.html#subprocess)\n- [Python documentation: `subprocess.run`](https://docs.python.org/3/library/subprocess.html#subprocess.run)\n",
|
|
811
|
+
"ruff/UP023": "## What it does\nChecks for uses of the `xml.etree.cElementTree` module.\n\n## Why is this bad?\nIn Python 3.3, `xml.etree.cElementTree` was deprecated in favor of\n`xml.etree.ElementTree`.\n\n## Example\n```python\nfrom xml.etree import cElementTree as ET\n```\n\nUse instead:\n```python\nfrom xml.etree import ElementTree as ET\n```\n\n## References\n- [Python documentation: `xml.etree.ElementTree`](https://docs.python.org/3/library/xml.etree.elementtree.html)\n",
|
|
812
|
+
"ruff/UP024": "## What it does\nChecks for uses of exceptions that alias `OSError`.\n\n## Why is this bad?\n`OSError` is the builtin error type used for exceptions that relate to the\noperating system.\n\nIn Python 3.3, a variety of other exceptions, like `WindowsError` were\naliased to `OSError`. These aliases remain in place for compatibility with\nolder versions of Python, but may be removed in future versions.\n\nPrefer using `OSError` directly, as it is more idiomatic and future-proof.\n\n## Example\n```python\nraise IOError\n```\n\nUse instead:\n```python\nraise OSError\n```\n\n## References\n- [Python documentation: `OSError`](https://docs.python.org/3/library/exceptions.html#OSError)\n",
|
|
813
|
+
"ruff/UP025": "## What it does\nChecks for uses of the Unicode kind prefix (`u`) in strings.\n\n## Why is this bad?\nIn Python 3, all strings are Unicode by default. The Unicode kind prefix is\nunnecessary and should be removed to avoid confusion.\n\n## Example\n```python\nu\"foo\"\n```\n\nUse instead:\n```python\n\"foo\"\n```\n\n## References\n- [Python documentation: Unicode HOWTO](https://docs.python.org/3/howto/unicode.html)\n",
|
|
814
|
+
"ruff/UP026": "## What it does\nChecks for imports of the `mock` module that should be replaced with\n`unittest.mock`.\n\n## Why is this bad?\nSince Python 3.3, `mock` has been a part of the standard library as\n`unittest.mock`. The `mock` package is deprecated; use `unittest.mock`\ninstead.\n\n## Example\n```python\nimport mock\n```\n\nUse instead:\n```python\nfrom unittest import mock\n```\n\n## Options\n\nThis rule will not trigger if the `mock` import is required by the `isort` configuration.\n\n- `lint.isort.required-imports`\n\n## References\n- [Python documentation: `unittest.mock`](https://docs.python.org/3/library/unittest.mock.html)\n- [PyPI: `mock`](https://pypi.org/project/mock/)\n",
|
|
815
|
+
"ruff/UP027": "## Removed\nThere's no [evidence](https://github.com/astral-sh/ruff/issues/12754) that generators are\nmeaningfully faster than list comprehensions when combined with unpacking.\n\n## What it does\nChecks for list comprehensions that are immediately unpacked.\n\n## Why is this bad?\nThere is no reason to use a list comprehension if the result is immediately\nunpacked. Instead, use a generator expression, which avoids allocating\nan intermediary list.\n\n## Example\n```python\na, b, c = [foo(x) for x in items]\n```\n\nUse instead:\n```python\na, b, c = (foo(x) for x in items)\n```\n\n## References\n- [Python documentation: Generator expressions](https://docs.python.org/3/reference/expressions.html#generator-expressions)\n- [Python documentation: List comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions)\n",
|
|
816
|
+
"ruff/UP028": "## What it does\nChecks for `for` loops that can be replaced with `yield from` expressions.\n\n## Why is this bad?\nIf a `for` loop only contains a `yield` statement, it can be replaced with a\n`yield from` expression, which is more concise and idiomatic.\n\n## Example\n```python\ndef bar():\n for x in foo:\n yield x\n\n global y\n for y in foo:\n yield y\n```\n\nUse instead:\n```python\ndef bar():\n yield from foo\n\n for _element in foo:\n y = _element\n yield y\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as converting a `for` loop to a `yield\nfrom` expression can change the behavior of the program in rare cases.\nFor example, if a generator is being sent values via `send`, then rewriting\nto a `yield from` could lead to an attribute error if the underlying\ngenerator does not implement the `send` method.\n\nAdditionally, if at least one target is `global` or `nonlocal`,\nno fix will be offered.\n\nIn most cases, however, the fix is safe, and such a modification should have\nno effect on the behavior of the program.\n\n## References\n- [Python documentation: The `yield` statement](https://docs.python.org/3/reference/simple_stmts.html#the-yield-statement)\n- [PEP 380 \u2013 Syntax for Delegating to a Subgenerator](https://peps.python.org/pep-0380/)\n",
|
|
817
|
+
"ruff/UP029": "## What it does\nChecks for imports of Python 3 builtins from Python 2 compatibility shims\nsuch as `python-future` and `six`.\n\n## Why is this bad?\nThese shims existed to access Python 3 builtins from code that also ran on\nPython 2. On Python 3-only code, the imports are redundant.\n\n## Example\n```python\nfrom builtins import str\n\nstr(1)\n```\n\nUse instead:\n```python\nstr(1)\n```\n\n## Fix safety\nThis fix is marked as unsafe because it will remove comments attached to the unused import.\n\n## Options\n\nThis rule will not trigger on imports required by the `isort` configuration.\n\n- `lint.isort.required-imports`\n\n## References\n- [Python documentation: The Python Standard Library](https://docs.python.org/3/library/index.html)\n",
|
|
818
|
+
"ruff/UP030": "## What it does\nChecks for unnecessary positional indices in format strings.\n\n## Why is this bad?\nIn Python 3.1 and later, format strings can use implicit positional\nreferences. For example, `\"{0}, {1}\".format(\"Hello\", \"World\")` can be\nrewritten as `\"{}, {}\".format(\"Hello\", \"World\")`.\n\nIf the positional indices appear exactly in-order, they can be omitted\nin favor of automatic indices to improve readability.\n\n## Example\n```python\n\"{0}, {1}\".format(\"Hello\", \"World\") # \"Hello, World\"\n```\n\nUse instead:\n```python\n\"{}, {}\".format(\"Hello\", \"World\") # \"Hello, World\"\n```\n\nThis fix is marked as unsafe because:\n- Comments attached to arguments are not moved, which can cause comments to mismatch the actual arguments.\n- If arguments have side effects (e.g., print), reordering may change program behavior.\n\n## References\n- [Python documentation: Format String Syntax](https://docs.python.org/3/library/string.html#format-string-syntax)\n- [Python documentation: `str.format`](https://docs.python.org/3/library/stdtypes.html#str.format)\n",
|
|
819
|
+
"ruff/UP031": "## What it does\nChecks for `printf`-style string formatting, and offers to replace it with\n`str.format` calls.\n\n## Why is this bad?\n`printf`-style string formatting has a number of quirks, and leads to less\nreadable code than using `str.format` calls or f-strings. In general, prefer\nthe newer `str.format` and f-strings constructs over `printf`-style string\nformatting.\n\n## Example\n\n```python\n\"%s, %s\" % (\"Hello\", \"World\") # \"Hello, World\"\n```\n\nUse instead:\n\n```python\n\"{}, {}\".format(\"Hello\", \"World\") # \"Hello, World\"\n```\n\n```python\nf\"{'Hello'}, {'World'}\" # \"Hello, World\"\n```\n\n## Fix safety\n\nIn cases where the format string contains a single generic format specifier\n(e.g. `%s`), and the right-hand side is an ambiguous expression,\nwe cannot offer a safe fix.\n\nFor example, given:\n\n```python\n\"%s\" % val\n```\n\n`val` could be a single-element tuple, _or_ a single value (not\ncontained in a tuple). Both of these would resolve to the same\nformatted string when using `printf`-style formatting, but\nresolve differently when using f-strings:\n\n```python\nval = 1\nprint(\"%s\" % val) # \"1\"\nprint(\"{}\".format(val)) # \"1\"\n\nval = (1,)\nprint(\"%s\" % val) # \"1\"\nprint(\"{}\".format(val)) # \"(1,)\"\n```\n\n## References\n- [Python documentation: `printf`-style String Formatting](https://docs.python.org/3/library/stdtypes.html#old-string-formatting)\n- [Python documentation: `str.format`](https://docs.python.org/3/library/stdtypes.html#str.format)\n",
|
|
820
|
+
"ruff/UP032": "## What it does\nChecks for `str.format` calls that can be replaced with f-strings.\n\n## Why is this bad?\nf-strings are more readable and generally preferred over `str.format`\ncalls.\n\n## Example\n```python\n\"{}\".format(foo)\n```\n\nUse instead:\n```python\nf\"{foo}\"\n```\n\n## References\n- [Python documentation: f-strings](https://docs.python.org/3/reference/lexical_analysis.html#f-strings)\n",
|
|
821
|
+
"ruff/UP033": "## What it does\nChecks for uses of `functools.lru_cache` that set `maxsize=None`.\n\n## Why is this bad?\nSince Python 3.9, `functools.cache` can be used as a drop-in replacement\nfor `functools.lru_cache(maxsize=None)`. When possible, prefer\n`functools.cache` as it is more readable and idiomatic.\n\n## Example\n\n```python\nimport functools\n\n\n@functools.lru_cache(maxsize=None)\ndef foo(): ...\n```\n\nUse instead:\n\n```python\nimport functools\n\n\n@functools.cache\ndef foo(): ...\n```\n\n## Options\n- `target-version`\n\n## Fix safety\nThis rule's fix is marked as safe, unless the expression contains comments.\n\n## References\n- [Python documentation: `@functools.cache`](https://docs.python.org/3/library/functools.html#functools.cache)\n",
|
|
822
|
+
"ruff/UP034": "## What it does\nChecks for extraneous parentheses.\n\n## Why is this bad?\nExtraneous parentheses are redundant, and can be removed to improve\nreadability while retaining identical semantics.\n\n## Example\n```python\nprint((\"Hello, world\"))\n```\n\nUse instead:\n```python\nprint(\"Hello, world\")\n```\n",
|
|
823
|
+
"ruff/UP035": "## What it does\nChecks for uses of deprecated imports based on the minimum supported\nPython version.\n\n## Why is this bad?\nDeprecated imports may be removed in future versions of Python, and\nshould be replaced with their new equivalents.\n\nNote that, in some cases, it may be preferable to continue importing\nmembers from `typing_extensions` even after they're added to the Python\nstandard library, as `typing_extensions` can backport bugfixes and\noptimizations from later Python versions. This rule thus avoids flagging\nimports from `typing_extensions` in such cases.\n\n## Example\n```python\nfrom collections import Sequence\n```\n\nUse instead:\n```python\nfrom collections.abc import Sequence\n```\n\n## Fix safety\nThis fix is marked unsafe if the import statement contains comments, since\nrewriting the import may delete them.\n",
|
|
824
|
+
"ruff/UP036": "## What it does\nChecks for conditional blocks gated on `sys.version_info` comparisons\nthat are outdated for the minimum supported Python version.\n\n## Why is this bad?\nIn Python, code can be conditionally executed based on the active\nPython version by comparing against the `sys.version_info` tuple.\n\nIf a code block is only executed for Python versions older than the\nminimum supported version, it should be removed.\n\n## Example\n```python\nimport sys\n\nif sys.version_info < (3, 0):\n print(\"py2\")\nelse:\n print(\"py3\")\n```\n\nUse instead:\n```python\nprint(\"py3\")\n```\n\n## Options\n- `target-version`\n\n## Fix safety\nThis rule's fix is marked as unsafe because it will remove all code,\ncomments, and annotations within unreachable version blocks.\n\n## References\n- [Python documentation: `sys.version_info`](https://docs.python.org/3/library/sys.html#sys.version_info)\n",
|
|
825
|
+
"ruff/UP037": "## What it does\nChecks for the presence of unnecessary quotes in type annotations.\n\n## Why is this bad?\nIn Python, type annotations can be quoted to avoid forward references.\n\nHowever, if `from __future__ import annotations` is present, Python\nwill always evaluate type annotations in a deferred manner, making\nthe quotes unnecessary.\n\nSimilarly, if the annotation is located in a typing-only context and\nwon't be evaluated by Python at runtime, the quotes will also be\nconsidered unnecessary. For example, Python does not evaluate type\nannotations on assignments in function bodies.\n\n## Example\n\nGiven:\n\n```python\nfrom __future__ import annotations\n\n\ndef foo(bar: \"Bar\") -> \"Bar\": ...\n```\n\nUse instead:\n\n```python\nfrom __future__ import annotations\n\n\ndef foo(bar: Bar) -> Bar: ...\n```\n\nGiven:\n\n```python\ndef foo() -> None:\n bar: \"Bar\"\n```\n\nUse instead:\n\n```python\ndef foo() -> None:\n bar: Bar\n```\n\n## Preview\n\nWhen [preview] is enabled, if [`lint.future-annotations`] is set to `true`,\n`from __future__ import annotations` will be added if doing so would allow an annotation to be\nunquoted.\n\n## Fix safety\n\nThe rule's fix is marked as safe, unless [preview] and\n[`lint.future-annotations`] are enabled and a `from __future__ import\nannotations` import is added. Such an import may change the behavior of all annotations in the\nfile.\n\n## Options\n- `lint.future-annotations`\n\n## See also\n- [`quoted-annotation-in-stub`][PYI020]: A rule that\n removes all quoted annotations from stub files\n- [`quoted-type-alias`][TC008]: A rule that removes unnecessary quotes\n from type aliases.\n\n## References\n- [PEP 563 \u2013 Postponed Evaluation of Annotations](https://peps.python.org/pep-0563/)\n- [Python documentation: `__future__`](https://docs.python.org/3/library/__future__.html#module-__future__)\n\n[PYI020]: https://docs.astral.sh/ruff/rules/quoted-annotation-in-stub/\n[TC008]: https://docs.astral.sh/ruff/rules/quoted-type-alias/\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
826
|
+
"ruff/UP038": "## Removed\nThis rule was removed as using [PEP 604] syntax in `isinstance` and `issubclass` calls\nisn't recommended practice, and it incorrectly suggests that other typing syntaxes like [PEP 695]\nwould be supported by `isinstance` and `issubclass`. Using the [PEP 604] syntax\nis also slightly slower.\n\n## What it does\nChecks for uses of `isinstance` and `issubclass` that take a tuple\nof types for comparison.\n\n## Why is this bad?\nSince Python 3.10, `isinstance` and `issubclass` can be passed a\n`|`-separated union of types, which is consistent\nwith the union operator introduced in [PEP 604].\n\nNote that this results in slower code. Ignore this rule if the\nperformance of an `isinstance` or `issubclass` check is a\nconcern, e.g., in a hot loop.\n\n## Example\n```python\nisinstance(x, (int, float))\n```\n\nUse instead:\n```python\nisinstance(x, int | float)\n```\n\n## Options\n- `target-version`\n\n## References\n- [Python documentation: `isinstance`](https://docs.python.org/3/library/functions.html#isinstance)\n- [Python documentation: `issubclass`](https://docs.python.org/3/library/functions.html#issubclass)\n\n[PEP 604]: https://peps.python.org/pep-0604/\n[PEP 695]: https://peps.python.org/pep-0695/\n",
|
|
827
|
+
"ruff/UP039": "## What it does\nChecks for class definitions that include unnecessary parentheses after\nthe class name.\n\n## Why is this bad?\nIf a class definition doesn't have any bases, the parentheses are\nunnecessary.\n\n## Example\n```python\nclass Foo():\n ...\n```\n\nUse instead:\n```python\nclass Foo:\n ...\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe if it would delete any comments\nwithin the parentheses range.\n",
|
|
828
|
+
"ruff/UP040": "## What it does\nChecks for use of `TypeAlias` annotations and `TypeAliasType` assignments\nfor declaring type aliases.\n\n## Why is this bad?\nThe `type` keyword was introduced in Python 3.12 by [PEP 695] for defining\ntype aliases. The `type` keyword is easier to read and provides cleaner\nsupport for generics.\n\n## Known problems\n\nUnlike type aliases that use simple assignments, definitions created using\n[PEP 695] `type` statements cannot be used as drop-in replacements at\nruntime for the value on the right-hand side of the statement. This means\nthat while for some simple old-style type aliases you can use them as the\nsecond argument to an `isinstance()` call (for example), doing the same\nwith a [PEP 695] `type` statement will always raise `TypeError` at\nruntime.\n\n## Example\n```python\nfrom typing import Annotated, TypeAlias, TypeAliasType\nfrom annotated_types import Gt\n\nListOfInt: TypeAlias = list[int]\nPositiveInt = TypeAliasType(\"PositiveInt\", Annotated[int, Gt(0)])\n```\n\nUse instead:\n```python\nfrom typing import Annotated\nfrom annotated_types import Gt\n\ntype ListOfInt = list[int]\ntype PositiveInt = Annotated[int, Gt(0)]\n```\n\n## Fix safety\n\nThis fix is always marked unsafe because it can change runtime behavior, as described above.\nIt may also remove comments.\n\nThe rule also cannot inspect type variables defined in another module. For `TypeAlias`\nannotations, this means the fix may fail to convert legacy type variables to type parameters,\nproducing code that will be rejected by type checkers. For `TypeAliasType`, legacy type\nvariables are recognized via the explicit `type_params` argument, but the type variable's\ndefinition cannot be resolved to preserve its bounds, constraints, defaults, or even kind,\nproducing unconstrained `TypeVar`s.\n\n## See also\n\nThis rule only applies to `TypeAlias`es and `TypeAliasType`s. See\n[`non-pep695-generic-class`][UP046] and [`non-pep695-generic-function`][UP047] for similar\ntransformations for generic classes and functions.\n\nThis rule replaces standalone type variables in aliases but doesn't remove the corresponding\ntype variables even if they are unused after the fix. See [`unused-private-type-var`][PYI018]\nfor a rule to clean up unused private type variables.\n\nThis rule will not rename private type variables to remove leading underscores, even though the\nnew type parameters are restricted in scope to their associated aliases. See\n[`private-type-parameter`][UP049] for a rule to update these names.\n\n## Options\n\n- `target-version`\n\n[PEP 695]: https://peps.python.org/pep-0695/\n[PYI018]: https://docs.astral.sh/ruff/rules/unused-private-type-var/\n[UP046]: https://docs.astral.sh/ruff/rules/non-pep695-generic-class/\n[UP047]: https://docs.astral.sh/ruff/rules/non-pep695-generic-function/\n[UP049]: https://docs.astral.sh/ruff/rules/private-type-parameter/\n",
|
|
829
|
+
"ruff/UP041": "## What it does\nChecks for uses of exceptions that alias `TimeoutError`.\n\n## Why is this bad?\n`TimeoutError` is the builtin error type used for exceptions when a system\nfunction timed out at the system level.\n\nIn Python 3.10, `socket.timeout` was aliased to `TimeoutError`. In Python\n3.11, `asyncio.TimeoutError` was aliased to `TimeoutError`.\n\nThese aliases remain in place for compatibility with older versions of\nPython, but may be removed in future versions.\n\nPrefer using `TimeoutError` directly, as it is more idiomatic and future-proof.\n\n## Example\n```python\nimport asyncio\n\nraise asyncio.TimeoutError\n```\n\nUse instead:\n```python\nraise TimeoutError\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe if it would delete any comments\nwithin the exception expression range.\n\n## References\n- [Python documentation: `TimeoutError`](https://docs.python.org/3/library/exceptions.html#TimeoutError)\n",
|
|
830
|
+
"ruff/UP042": "## What it does\nChecks for classes that inherit from both `str` and `enum.Enum`.\n\n## Why is this bad?\nPython 3.11 introduced `enum.StrEnum`, which is preferred over inheriting\nfrom both `str` and `enum.Enum`.\n\n## Example\n\n```python\nimport enum\n\n\nclass Foo(str, enum.Enum): ...\n```\n\nUse instead:\n\n```python\nimport enum\n\n\nclass Foo(enum.StrEnum): ...\n```\n\n## Fix safety\n\nPython 3.11 introduced a [breaking change] for enums that inherit from both\n`str` and `enum.Enum`. Consider the following enum:\n\n```python\nfrom enum import Enum\n\n\nclass Foo(str, Enum):\n BAR = \"bar\"\n```\n\nIn Python 3.11, the formatted representation of `Foo.BAR` changed as\nfollows:\n\n```python\n# Python 3.10\nf\"{Foo.BAR}\" # > bar\n# Python 3.11\nf\"{Foo.BAR}\" # > Foo.BAR\n```\n\nMigrating from `str` and `enum.Enum` to `enum.StrEnum` will restore the\nprevious behavior, such that:\n\n```python\nfrom enum import StrEnum\n\n\nclass Foo(StrEnum):\n BAR = \"bar\"\n\n\nf\"{Foo.BAR}\" # > bar\n```\n\nAs such, migrating to `enum.StrEnum` will introduce a behavior change for\ncode that relies on the Python 3.11 behavior.\n\n## Options\n\n- `target-version`\n\n## References\n- [enum.StrEnum](https://docs.python.org/3/library/enum.html#enum.StrEnum)\n\n[breaking change]: https://blog.pecar.me/python-enum\n",
|
|
831
|
+
"ruff/UP043": "## What it does\nChecks for unnecessary default type arguments for `Generator` and\n`AsyncGenerator` on Python 3.13+.\n\n## Why is this bad?\nPython 3.13 introduced the ability for type parameters to specify default\nvalues. Following this change, several standard-library classes were\nupdated to add default values for some of their type parameters. For\nexample, `Generator[int]` is now equivalent to\n`Generator[int, None, None]`, as the second and third type parameters of\n`Generator` now default to `None`.\n\nOmitting type arguments that match the default values can make the code\nmore concise and easier to read.\n\n## Example\n\n```python\nfrom collections.abc import Generator, AsyncGenerator\n\n\ndef sync_gen() -> Generator[int, None, None]:\n yield 42\n\n\nasync def async_gen() -> AsyncGenerator[int, None]:\n yield 42\n```\n\nUse instead:\n\n```python\nfrom collections.abc import Generator, AsyncGenerator\n\n\ndef sync_gen() -> Generator[int]:\n yield 42\n\n\nasync def async_gen() -> AsyncGenerator[int]:\n yield 42\n```\n\n## Fix safety\nThis rule's fix is marked as safe, unless the type annotation contains comments.\n\n## Options\n- `target-version`\n\n## References\n- [PEP 696 \u2013 Type Defaults for Type Parameters](https://peps.python.org/pep-0696/)\n- [Annotating generators and coroutines](https://docs.python.org/3/library/typing.html#annotating-generators-and-coroutines)\n- [Python documentation: `typing.Generator`](https://docs.python.org/3/library/typing.html#typing.Generator)\n- [Python documentation: `typing.AsyncGenerator`](https://docs.python.org/3/library/typing.html#typing.AsyncGenerator)\n",
|
|
832
|
+
"ruff/UP044": "## What it does\nChecks for uses of `Unpack[]` on Python 3.11 and above, and suggests\nusing `*` instead.\n\n## Why is this bad?\n[PEP 646] introduced a new syntax for unpacking sequences based on the `*`\noperator. This syntax is more concise and readable than the previous\n`Unpack[]` syntax.\n\n## Example\n```python\nfrom typing import Unpack\n\n\ndef foo(*args: Unpack[tuple[int, ...]]) -> None:\n pass\n```\n\nUse instead:\n```python\ndef foo(*args: *tuple[int, ...]) -> None:\n pass\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as `Unpack[T]` and `*T` are considered\ndifferent values when introspecting types at runtime. However, in most cases,\nthe fix should be safe to apply.\n\n## Options\n\n- `target-version`\n\n[PEP 646]: https://peps.python.org/pep-0646/\n",
|
|
833
|
+
"ruff/UP045": "## What it does\nCheck for `typing.Optional` annotations that can be rewritten based on [PEP 604] syntax.\n\n## Why is this bad?\n[PEP 604] introduced a new syntax for union type annotations based on the\n`|` operator. This syntax is more concise and readable than the previous\n`typing.Optional` syntax.\n\nThis rule is enabled when targeting Python 3.10 or later (see:\n[`target-version`]). By default, it's _also_ enabled for earlier Python\nversions if `from __future__ import annotations` is present, as\n`__future__` annotations are not evaluated at runtime. If your code relies\non runtime type annotations (either directly or via a library like\nPydantic), you can disable this behavior for Python versions prior to 3.10\nby setting [`lint.pyupgrade.keep-runtime-typing`] to `true`.\n\n## Example\n```python\nfrom typing import Optional\n\nfoo: Optional[int] = None\n```\n\nUse instead:\n```python\nfoo: int | None = None\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe on Python versions prior to 3.10 because\nusing the PEP-604 syntax may lead to runtime errors in libraries that rely\non runtime type annotations, like Pydantic, or in unusual and likely\nincorrect type annotations where the type does not support the `|`\noperator. The fix is also marked as unsafe when it would remove comments\npresent within the type annotation being rewritten.\n\nIn [preview], this rule can also add its own `__future__` import on Python\n3.9 and earlier, if the [`lint.future-annotations`] setting is enabled. This\nalso makes the fix unsafe.\n\n## Options\n- `target-version`\n- `lint.pyupgrade.keep-runtime-typing`\n- `lint.future-annotations`\n\n[PEP 604]: https://peps.python.org/pep-0604/\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
834
|
+
"ruff/UP046": "## What it does\n\nChecks for use of standalone type variables and parameter specifications in generic classes.\n\n## Why is this bad?\n\nSpecial type parameter syntax was introduced in Python 3.12 by [PEP 695] for defining generic\nclasses. This syntax is easier to read and provides cleaner support for generics.\n\nIn particular, old-style `TypeVar` variables are typically allocated at module scope, but their\nsemantic meaning is only valid within the context of a generic class, function, or type alias.\n[PEP 695] eliminates this [source of confusion] by declaring type parameters at their point of\nuse.\n\n## Known problems\n\nThe rule currently skips generic classes nested inside of other functions or classes. It also\nskips type parameters with the `default` argument introduced in [PEP 696] and implemented in\nPython 3.13.\n\nThis rule can only offer a fix if all of the generic types in the class definition are defined\nin the current module. For external type parameters, a diagnostic is emitted without a suggested\nfix.\n\nNot all type checkers fully support PEP 695 yet, so even valid fixes suggested by this rule may\ncause type checking to [fail].\n\n## Fix safety\n\nThis fix is marked as unsafe, as [PEP 695] uses inferred variance for type parameters, instead\nof the `covariant` and `contravariant` keywords used by `TypeVar` variables. As such, replacing\na `TypeVar` variable with an inline type parameter may change its variance.\n\n## Examples\n\n```python\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\n\n\nclass GenericClass(Generic[T]):\n var: T\n```\n\nUse instead:\n\n```python\nclass GenericClass[T]:\n var: T\n```\n\nIn cases where you've intentionally defined a reusable `TypeVar` to share\nthe bounds across multiple uses:\n\n```python\nfrom typing import Generic, TypeVar\n\nReusableT = TypeVar(\"ReusableT\", bound=int | str | dict[int, str])\n\n\nclass GenericClass1(Generic[ReusableT]): ...\n\n\nclass GenericClass2(Generic[ReusableT]): ...\n\n\nclass GenericClass3(Generic[ReusableT]): ...\n```\n\nYou can instead extract the bound as a [type alias] to retain both the\nbenefits of the PEP 695 syntax and the reuse of the bound:\n\n```python\ntype ReusableTBound = int | str | dict[int, str]\n\n\nclass GenericClass1[ReusableT: ReusableTBound]: ...\n\n\nclass GenericClass2[ReusableT: ReusableTBound]: ...\n\n\nclass GenericClass3[ReusableT: ReusableTBound]: ...\n```\n\n## See also\n\nThis rule replaces standalone type variables in classes but doesn't remove\nthe corresponding type variables even if they are unused after the fix. See\n[`unused-private-type-var`][PYI018] for a rule to clean up unused\nprivate type variables.\n\nThis rule will not rename private type variables to remove leading underscores, even though the\nnew type parameters are restricted in scope to their associated class. See\n[`private-type-parameter`][UP049] for a rule to update these names.\n\nThis rule will correctly handle classes with multiple base classes, as long as the single\n`Generic` base class is at the end of the argument list, as checked by\n[`generic-not-last-base-class`][PYI059]. If a `Generic` base class is\nfound outside of the last position, a diagnostic is emitted without a suggested fix.\n\nThis rule only applies to generic classes and does not include generic functions. See\n[`non-pep695-generic-function`][UP047] for the function version.\n\n## Options\n\n- `target-version`\n\n[PEP 695]: https://peps.python.org/pep-0695/\n[PEP 696]: https://peps.python.org/pep-0696/\n[PYI018]: https://docs.astral.sh/ruff/rules/unused-private-type-var/\n[PYI059]: https://docs.astral.sh/ruff/rules/generic-not-last-base-class/\n[UP047]: https://docs.astral.sh/ruff/rules/non-pep695-generic-function/\n[UP049]: https://docs.astral.sh/ruff/rules/private-type-parameter/\n[fail]: https://github.com/python/mypy/issues/18507\n[source of confusion]: https://peps.python.org/pep-0695/#points-of-confusion\n[type alias]: https://docs.python.org/3/reference/simple_stmts.html#type-aliases\n",
|
|
835
|
+
"ruff/UP047": "## What it does\n\nChecks for use of standalone type variables and parameter specifications in generic functions.\n\n## Why is this bad?\n\nSpecial type parameter syntax was introduced in Python 3.12 by [PEP 695] for defining generic\nfunctions. This syntax is easier to read and provides cleaner support for generics.\n\n## Known problems\n\nThe rule currently skips generic functions nested inside of other functions or classes and those\nwith type parameters containing the `default` argument introduced in [PEP 696] and implemented\nin Python 3.13.\n\nNot all type checkers fully support PEP 695 yet, so even valid fixes suggested by this rule may\ncause type checking to [fail].\n\n## Fix safety\n\nThis fix is marked unsafe because the rule may be unable to determine whether a parameter\nannotation corresponds to a type variable (e.g. for a type imported from another module). In\nthat case, the fix does not add the type to the generic type parameter list. This causes the\nfunction to have a mix of old-style type variables and new-style generic type parameters, which\nwill be rejected by type checkers.\n\n## Example\n\n```python\nfrom typing import TypeVar\n\nT = TypeVar(\"T\")\n\n\ndef generic_function(var: T) -> T:\n return var\n```\n\nUse instead:\n\n```python\ndef generic_function[T](var: T) -> T:\n return var\n```\n\n## See also\n\nThis rule replaces standalone type variables in function signatures but doesn't remove\nthe corresponding type variables even if they are unused after the fix. See\n[`unused-private-type-var`][PYI018] for a rule to clean up unused\nprivate type variables.\n\nThis rule will not rename private type variables to remove leading underscores, even though the\nnew type parameters are restricted in scope to their associated function. See\n[`private-type-parameter`][UP049] for a rule to update these names.\n\nThis rule only applies to generic functions and does not include generic classes. See\n[`non-pep695-generic-class`][UP046] for the class version.\n\n## Options\n\n- `target-version`\n\n[PEP 695]: https://peps.python.org/pep-0695/\n[PEP 696]: https://peps.python.org/pep-0696/\n[PYI018]: https://docs.astral.sh/ruff/rules/unused-private-type-var/\n[UP046]: https://docs.astral.sh/ruff/rules/non-pep695-generic-class/\n[UP049]: https://docs.astral.sh/ruff/rules/private-type-parameter/\n[fail]: https://github.com/python/mypy/issues/18507\n",
|
|
836
|
+
"ruff/UP048": "## What it does\nChecks for `while` loops that use `1` as their condition.\n\n## Why is this bad?\n`while 1:` is a Python 2 idiom, where `True` was a global that could be\nrebound and so had to be loaded and tested on every iteration. In Python 3\n`True` is a keyword, so both spellings compile to the same bytecode and\n`while True:` is clearer about the loop being infinite.\n\n## Example\n```python\nwhile 1:\n print(\"Hello, world!\")\n```\n\nUse instead:\n```python\nwhile True:\n print(\"Hello, world!\")\n```\n\n## References\n- [Python documentation: `while`](https://docs.python.org/3/reference/compound_stmts.html#the-while-statement)\n- [PEP 285 \u2013 Adding a bool type](https://peps.python.org/pep-0285/)\n",
|
|
837
|
+
"ruff/UP049": "## What it does\n\nChecks for use of [PEP 695] type parameters with leading underscores in generic classes and\nfunctions.\n\n## Why is this bad?\n\n[PEP 695] type parameters are already restricted in scope to the class or function in which they\nappear, so leading underscores just hurt readability without the usual privacy benefits.\n\nHowever, neither a diagnostic nor a fix will be emitted for \"sunder\" (`_T_`) or \"dunder\"\n(`__T__`) type parameter names as these are not considered private.\n\n## Example\n\n```python\nclass GenericClass[_T]:\n var: _T\n\n\ndef generic_function[_T](var: _T) -> list[_T]:\n return var[0]\n```\n\nUse instead:\n\n```python\nclass GenericClass[T]:\n var: T\n\n\ndef generic_function[T](var: T) -> list[T]:\n return var[0]\n```\n\n## Fix availability\n\nIf the name without an underscore would shadow a builtin or another variable, would be a\nkeyword, or would otherwise be an invalid identifier, a fix will not be available. In these\nsituations, you can consider using a trailing underscore or a different name entirely to satisfy\nthe lint rule.\n\n## See also\n\nThis rule renames private [PEP 695] type parameters but doesn't convert pre-[PEP 695] generics\nto the new format. See [`non-pep695-generic-function`][UP047] and\n[`non-pep695-generic-class`][UP046] for rules that will make this transformation.\nThose rules do not remove unused type variables after their changes,\nso you may also want to consider enabling [`unused-private-type-var`][PYI018] to complete\nthe transition to [PEP 695] generics.\n\n[PEP 695]: https://peps.python.org/pep-0695/\n[UP047]: https://docs.astral.sh/ruff/rules/non-pep695-generic-function\n[UP046]: https://docs.astral.sh/ruff/rules/non-pep695-generic-class\n[PYI018]: https://docs.astral.sh/ruff/rules/unused-private-type-var\n",
|
|
838
|
+
"ruff/UP050": "## What it does\nChecks for `metaclass=type` in class definitions.\n\n## Why is this bad?\nSince Python 3, the default metaclass is `type`, so specifying it explicitly is redundant.\n\nEven though `__prepare__` is not required, the default metaclass (`type`) implements it,\nfor the convenience of subclasses calling it via `super()`.\n## Example\n\n```python\nclass Foo(metaclass=type): ...\n```\n\nUse instead:\n\n```python\nclass Foo: ...\n```\n\n## References\n- [PEP 3115 \u2013 Metaclasses in Python 3000](https://peps.python.org/pep-3115/)\n",
|
|
839
|
+
"ruff/UP051": "## What it does\nChecks for uses of `abstractclassmethod`, `abstractstaticmethod`, `abstractproperty`.\n\n## Why is this bad?\nThese have been deprecated since Python 3.3 and are expected to be removed in a future version\nof Python.\n\n## Example\n\n```python\nimport abc\n\n\nclass Foo(abc.ABC):\n @abc.abstractclassmethod\n def class_method(cls, arg1): ...\n\n @abc.abstractstaticmethod\n def static_method(arg1): ...\n\n @abc.abstractproperty\n def prop(self): ...\n```\n\nUse instead:\n\n```python\nimport abc\n\n\nclass Foo(abc.ABC):\n @classmethod\n @abc.abstractmethod\n def class_method(cls, arg1): ...\n\n @staticmethod\n @abc.abstractmethod\n def static_method(arg1): ...\n\n @property\n @abc.abstractmethod\n def prop(self): ...\n```\n",
|
|
840
|
+
"ruff/UP052": "## What it does\nChecks for generator-based context managers annotated with `Iterator` or\n`AsyncIterator` instead of `Generator` or `AsyncGenerator`.\n\n## Why is this bad?\n`contextlib.contextmanager` and `contextlib.asynccontextmanager` require\ngenerators, which support methods such as `throw` that are not guaranteed\nby the iterator protocols. The iterator overloads of these decorators are\ndeprecated in [typeshed](https://github.com/python/typeshed/blob/main/stdlib/contextlib.pyi).\n\n## Example\n\n```python\nfrom collections.abc import Iterator\nfrom contextlib import contextmanager\n\n\n@contextmanager\ndef example() -> Iterator[int]:\n yield 1\n```\n\nUse instead:\n\n```python\nfrom collections.abc import Generator\nfrom contextlib import contextmanager\n\n\n@contextmanager\ndef example() -> Generator[int, None, None]:\n yield 1\n```\n\nOn Python 3.13 and later, the fix omits the default type arguments and uses\n`Generator[int]` or `AsyncGenerator[int]`.\n\n## Fix safety\nThe fix is unsafe because it changes the function's runtime annotations\nand may add an import, introducing a new name in the module. For a generator\nthat returns a value, the fix uses `object` as the return type to accommodate\nany return value.\n\n## Known limitations\nThe rule checks functions whose innermost decorator is a contextlib\ncontext manager and whose bodies contain a `yield` or `yield from`.\n\n## Options\n- `target-version`\n\n## References\n- [Python documentation: `contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager)\n- [Python documentation: `contextlib.asynccontextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.asynccontextmanager)\n",
|
|
841
|
+
"ruff/FURB101": "## What it does\nChecks for uses of `open` and `read` that can be replaced by `pathlib`\nmethods, like `Path.read_text` and `Path.read_bytes`.\n\n## Why is this bad?\nWhen reading the entire contents of a file into a variable, it's simpler\nand more concise to use `pathlib` methods like `Path.read_text` and\n`Path.read_bytes` instead of `open` and `read` calls via `with` statements.\n\n## Example\n```python\nwith open(\"file.txt\") as f:\n contents = f.read()\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\ncontents = Path(\"file.txt\").read_text()\n```\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\n\n## References\n- [Python documentation: `Path.read_bytes`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.read_bytes)\n- [Python documentation: `Path.read_text`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.read_text)\n",
|
|
842
|
+
"ruff/FURB103": "## What it does\nChecks for uses of `open` and `write` that can be replaced by `pathlib`\nmethods, like `Path.write_text` and `Path.write_bytes`.\n\n## Why is this bad?\nWhen writing a single string to a file, it's simpler and more concise\nto use `pathlib` methods like `Path.write_text` and `Path.write_bytes`\ninstead of `open` and `write` calls via `with` statements.\n\n## Example\n```python\nwith open(\"file.txt\", \"w\") as f:\n f.write(\"some text\")\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nPath(\"file.txt\").write_text(\"some text\")\n```\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the original expression.\n\n## References\n- [Python documentation: `Path.write_bytes`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.write_bytes)\n- [Python documentation: `Path.write_text`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.write_text)\n",
|
|
843
|
+
"ruff/FURB105": "## What it does\nChecks for `print` calls with unnecessary empty strings as positional\narguments and unnecessary `sep` keyword arguments.\n\n## Why is this bad?\nPrefer calling `print` without any positional arguments, which is\nequivalent and more concise.\n\nSimilarly, when printing one or fewer items, the `sep` keyword argument,\n(used to define the string that separates the `print` arguments) can be\nomitted, as it's redundant when there are no items to separate.\n\n## Example\n```python\nprint(\"\")\n```\n\nUse instead:\n```python\nprint()\n```\n\n## Fix safety\nThis fix is marked as unsafe if it removes comments or an unused `sep` keyword argument\nthat is not known to be a valid separator. Removing such arguments may change the\nprogram's behavior by skipping their evaluation or hiding a `TypeError`.\n\n## References\n- [Python documentation: `print`](https://docs.python.org/3/library/functions.html#print)\n",
|
|
844
|
+
"ruff/FURB110": "## What it does\nChecks for ternary `if` expressions that can be replaced with the `or`\noperator.\n\n## Why is this bad?\nTernary `if` expressions are more verbose than `or` expressions while\nproviding the same functionality.\n\n## Example\n```python\nx, y = 1, 2\n\nz = x if x else y\n```\n\nUse instead:\n```python\nx, y = 1, 2\n\nz = x or y\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe in the event that the body of the\n`if` expression contains side effects or comments.\n\nFor example, `foo` will be called twice in `foo() if foo() else bar()`\n(assuming `foo()` returns a truthy value), but only once in\n`foo() or bar()`.\n",
|
|
845
|
+
"ruff/FURB113": "## What it does\nChecks for consecutive calls to `append`.\n\n## Why is this bad?\nConsecutive calls to `append` can be less efficient than batching them into\na single `extend`. Each `append` resizes the list individually, whereas an\n`extend` can resize the list once for all elements.\n\n## Known problems\nThis rule is prone to false negatives due to type inference limitations,\nas it will only detect lists that are instantiated as literals or annotated\nwith a type annotation.\n\n## Example\n```python\nnums = [1, 2, 3]\n\nnums.append(4)\nnums.append(5)\nnums.append(6)\n```\n\nUse instead:\n```python\nnums = [1, 2, 3]\n\nnums.extend((4, 5, 6))\n```\n\n## References\n- [Python documentation: More on Lists](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)\n",
|
|
846
|
+
"ruff/FURB116": "## What it does\nChecks for uses of `bin(...)[2:]` (or `hex`, or `oct`) to convert\nan integer into a string.\n\n## Why is this bad?\nWhen converting an integer to a baseless binary, hexadecimal, or octal\nstring, using f-strings is more concise and readable than using the\n`bin`, `hex`, or `oct` functions followed by a slice.\n\n## Example\n```python\nprint(bin(1337)[2:])\n```\n\nUse instead:\n```python\nprint(f\"{1337:b}\")\n```\n\n## Fix safety\nThe fix is only marked as safe for integer literals, all other cases\nare display-only, as they may change the runtime behavior of the program\nor introduce syntax errors. The fix for integer literals is also marked as unsafe\nif the expression contains comments that would be removed by the fix.\n",
|
|
847
|
+
"ruff/FURB118": "## What it does\nChecks for lambda expressions and function definitions that can be replaced with a function from\nthe `operator` module.\n\n## Why is this bad?\nThe `operator` module provides functions that implement the same functionality as the\ncorresponding operators. For example, `operator.add` is often equivalent to `lambda x, y: x + y`.\nUsing the functions from the `operator` module is more concise and communicates the intent of\nthe code more clearly.\n\n## Example\n```python\nimport functools\n\nnums = [1, 2, 3]\ntotal = functools.reduce(lambda x, y: x + y, nums)\n```\n\nUse instead:\n```python\nimport functools\nimport operator\n\nnums = [1, 2, 3]\ntotal = functools.reduce(operator.add, nums)\n```\n\n## Fix safety\nThe fix offered by this rule is always marked as unsafe. While the changes the fix would make\nwould rarely break your code, there are two ways in which functions from the `operator` module\ndiffer from user-defined functions. It would be non-trivial for Ruff to detect whether or not\nthese differences would matter in a specific situation where Ruff is emitting a diagnostic for\nthis rule.\n\nThe first difference is that `operator` functions cannot be called with keyword arguments, but\nmost user-defined functions can. If an `add` function is defined as `add = lambda x, y: x + y`,\nreplacing this function with `operator.add` will cause the later call to raise `TypeError` if\nthe function is later called with keyword arguments, e.g. `add(x=1, y=2)`.\n\nThe second difference is that user-defined functions are [descriptors], but this is not true of\nthe functions defined in the `operator` module. Practically speaking, this means that defining\na function in a class body (either by using a `def` statement or assigning a `lambda` function\nto a variable) is a valid way of defining an instance method on that class; monkeypatching a\nuser-defined function onto a class after the class has been created also has the same effect.\nThe same is not true of an `operator` function: assigning an `operator` function to a variable\nin a class body or monkeypatching one onto a class will not create a valid instance method.\nRuff will refrain from emitting diagnostics for this rule on function definitions in class\nbodies; however, it does not currently have sophisticated enough type inference to avoid\nemitting this diagnostic if a user-defined function is being monkeypatched onto a class after\nthe class has been constructed.\n\n[descriptors]: https://docs.python.org/3/howto/descriptor.html\n",
|
|
848
|
+
"ruff/FURB122": "## What it does\nChecks for the use of `IOBase.write` in a for loop.\n\n## Why is this bad?\nWhen writing a batch of elements, it's more idiomatic to use a single method call to\n`IOBase.writelines`, rather than write elements one by one.\n\n## Example\n```python\nfrom pathlib import Path\n\nwith Path(\"file\").open(\"w\") as f:\n for line in lines:\n f.write(line)\n\nwith Path(\"file\").open(\"wb\") as f_b:\n for line_b in lines_b:\n f_b.write(line_b.encode())\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\nwith Path(\"file\").open(\"w\") as f:\n f.writelines(lines)\n\nwith Path(\"file\").open(\"wb\") as f_b:\n f_b.writelines(line_b.encode() for line_b in lines_b)\n```\n\n## Fix safety\nThis fix is marked as unsafe if it would cause comments to be deleted.\n\n## References\n- [Python documentation: `io.IOBase.writelines`](https://docs.python.org/3/library/io.html#io.IOBase.writelines)\n",
|
|
849
|
+
"ruff/FURB129": "## What it does\nChecks for uses of `readlines()` when iterating over a file line-by-line.\n\n## Why is this bad?\nRather than iterating over all lines in a file by calling `readlines()`,\nit's more convenient and performant to iterate over the file object\ndirectly.\n\n## Example\n```python\nwith open(\"file.txt\") as fp:\n for line in fp.readlines():\n ...\n```\n\nUse instead:\n```python\nwith open(\"file.txt\") as fp:\n for line in fp:\n ...\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe if there's comments in the\n`readlines()` call, as comments may be removed.\n\nFor example, the fix would be marked as unsafe in the following case:\n```python\nwith open(\"file.txt\") as fp:\n for line in ( # comment\n fp.readlines() # comment\n ):\n ...\n```\n\n## References\n- [Python documentation: `io.IOBase.readlines`](https://docs.python.org/3/library/io.html#io.IOBase.readlines)\n",
|
|
850
|
+
"ruff/FURB131": "## What it does\nChecks for `del` statements that delete the entire slice of a list.\n\n## Why is this bad?\nIt is faster and more succinct to remove all items via the `clear()`\nmethod.\n\n## Known problems\nThis rule is prone to false negatives due to type inference limitations,\nas it will only detect lists that are instantiated as literals or annotated\nwith a type annotation.\n\n## Example\n```python\nnums = [1, 2, 3]\n\ndel nums[:]\n```\n\nUse instead:\n```python\nnums = [1, 2, 3]\n\nnums.clear()\n```\n\n## References\n- [Python documentation: Mutable Sequence Types](https://docs.python.org/3/library/stdtypes.html#typesseq-mutable)\n- [Python documentation: `list.clear()`](https://docs.python.org/3/library/stdtypes.html#sequence.clear)\n",
|
|
851
|
+
"ruff/FURB132": "## What it does\nChecks for uses of `set.remove` that can be replaced with `set.discard`.\n\n## Why is this bad?\nIf an element should be removed from a set if it is present, it is more\nsuccinct and idiomatic to use `discard`.\n\n## Known problems\nThis rule is prone to false negatives due to type inference limitations,\nas it will only detect sets that are instantiated as literals or annotated\nwith a type annotation.\n\n## Example\n```python\nnums = {123, 456}\n\nif 123 in nums:\n nums.remove(123)\n```\n\nUse instead:\n```python\nnums = {123, 456}\n\nnums.discard(123)\n```\n\n## References\n- [Python documentation: `set.discard()`](https://docs.python.org/3/library/stdtypes.html#set.discard)\n",
|
|
852
|
+
"ruff/FURB136": "## What it does\nChecks for `if` expressions that can be replaced with `min()` or `max()`\ncalls.\n\n## Why is this bad?\nAn `if` expression that selects the lesser or greater of two\nsub-expressions can be replaced with a `min()` or `max()` call\nrespectively. When possible, prefer `min()` and `max()`, as they're more\nconcise and readable than the equivalent `if` expression.\n\n## Example\n```python\nscore1, score2 = 4, 5\n\nhighest_score = score1 if score1 > score2 else score2\n```\n\nUse instead:\n```python\nscore1, score2 = 4, 5\n\nhighest_score = max(score2, score1)\n```\n\n## Fix safety\nThis rule's fix is marked as safe, unless the expression contains comments.\n\n## References\n- [Python documentation: `min`](https://docs.python.org/3/library/functions.html#min)\n- [Python documentation: `max`](https://docs.python.org/3/library/functions.html#max)\n",
|
|
853
|
+
"ruff/FURB140": "## What it does\nChecks for generator expressions, list and set comprehensions that can\nbe replaced with `itertools.starmap`.\n\n## Why is this bad?\nWhen unpacking values from iterators to pass them directly to\na function, prefer `itertools.starmap`.\n\nUsing `itertools.starmap` is more concise and readable. Furthermore, it is\nmore efficient than generator expressions, and in some versions of Python,\nit is more efficient than comprehensions.\n\n## Known problems\nSince Python 3.12, `itertools.starmap` is less efficient than\ncomprehensions ([#7771]). This is due to [PEP 709], which made\ncomprehensions faster.\n\n## Example\n```python\nall(predicate(a, b) for a, b in some_iterable)\n```\n\nUse instead:\n```python\nfrom itertools import starmap\n\n\nall(starmap(predicate, some_iterable))\n```\n\n## Fix safety\nThis rule's fix is marked as safe, unless the expression contains comments.\n\n## References\n- [Python documentation: `itertools.starmap`](https://docs.python.org/3/library/itertools.html#itertools.starmap)\n\n[PEP 709]: https://peps.python.org/pep-0709/\n[#7771]: https://github.com/astral-sh/ruff/issues/7771\n",
|
|
854
|
+
"ruff/FURB142": "## What it does\nChecks for code that updates a set with the contents of an iterable by\nusing a `for` loop to call `.add()` or `.discard()` on each element\nseparately.\n\n## Why is this bad?\nWhen adding or removing a batch of elements to or from a set, it's more\nidiomatic to use a single method call rather than adding or removing\nelements one by one.\n\n## Example\n```python\ns = set()\n\nfor x in (1, 2, 3):\n s.add(x)\n\nfor x in (1, 2, 3):\n s.discard(x)\n```\n\nUse instead:\n```python\ns = set()\n\ns.update((1, 2, 3))\ns.difference_update((1, 2, 3))\n```\n\n## Fix safety\nThe fix will be marked as unsafe if applying the fix would delete any comments.\nOtherwise, it is marked as safe.\n\n## References\n- [Python documentation: `set`](https://docs.python.org/3/library/stdtypes.html#set)\n",
|
|
855
|
+
"ruff/FURB145": "## What it does\nChecks for unbounded slice expressions to copy a list.\n\n## Why is this bad?\nThe `list.copy` method is more readable and consistent with copying other\ntypes.\n\n## Known problems\nThis rule is prone to false negatives due to type inference limitations,\nas it will only detect lists that are instantiated as literals or annotated\nwith a type annotation.\n\n## Example\n```python\na = [1, 2, 3]\nb = a[:]\n```\n\nUse instead:\n```python\na = [1, 2, 3]\nb = a.copy()\n```\n\n## Fix safety\nThis rule's fix is marked as safe, unless the slice expression contains comments.\n\n## References\n- [Python documentation: Mutable Sequence Types](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types)\n",
|
|
856
|
+
"ruff/FURB148": "## What it does\nChecks for uses of `enumerate` that discard either the index or the value\nwhen iterating over a sequence.\n\n## Why is this bad?\nThe built-in `enumerate` function is useful when you need both the index and\nvalue of a sequence.\n\nIf you only need the index or values of a sequence, you should iterate over\n`range(len(...))` or the sequence itself, respectively, instead. This is\nmore efficient and communicates the intent of the code more clearly.\n\n## Known problems\nThis rule is prone to false negatives due to type inference limitations;\nnamely, it will only suggest a fix using the `len` builtin function if the\nsequence passed to `enumerate` is an instantiated as a list, set, dict, or\ntuple literal, or annotated as such with a type annotation.\n\nThe `len` builtin function is not defined for all object types (such as\ngenerators), and so refactoring to use `len` over `enumerate` is not always\nsafe.\n\n## Example\n```python\nfor index, _ in enumerate(sequence):\n print(index)\n\nfor _, value in enumerate(sequence):\n print(value)\n```\n\nUse instead:\n```python\nfor index in range(len(sequence)):\n print(index)\n\nfor value in sequence:\n print(value)\n```\n\n## References\n- [Python documentation: `enumerate`](https://docs.python.org/3/library/functions.html#enumerate)\n- [Python documentation: `range`](https://docs.python.org/3/library/stdtypes.html#range)\n- [Python documentation: `len`](https://docs.python.org/3/library/functions.html#len)\n",
|
|
857
|
+
"ruff/FURB152": "## What it does\nChecks for literals that are similar to constants in `math` module.\n\n## Why is this bad?\nHard-coding mathematical constants like \u03c0 increases code duplication,\nreduces readability, and may lead to a lack of precision.\n\n## Example\n```python\nA = 3.141592 * r**2\n```\n\nUse instead:\n```python\nA = math.pi * r**2\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as replacing a literal with the constant\ncan change the result of a calculation.\n\n## References\n- [Python documentation: `math` constants](https://docs.python.org/3/library/math.html#constants)\n",
|
|
858
|
+
"ruff/FURB154": "## What it does\nChecks for consecutive `global` (or `nonlocal`) statements.\n\n## Why is this bad?\nThe `global` and `nonlocal` keywords accepts multiple comma-separated names.\nInstead of using multiple `global` (or `nonlocal`) statements for separate\nvariables, you can use a single statement to declare multiple variables at\nonce.\n\n## Example\n```python\ndef func():\n global x\n global y\n\n print(x, y)\n```\n\nUse instead:\n```python\ndef func():\n global x, y\n\n print(x, y)\n```\n\n## Fix safety\nThis rule's fix is marked as safe, unless the statements contain comments.\n\n## References\n- [Python documentation: the `global` statement](https://docs.python.org/3/reference/simple_stmts.html#the-global-statement)\n- [Python documentation: the `nonlocal` statement](https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement)\n",
|
|
859
|
+
"ruff/FURB156": "## What it does\nChecks for uses of hardcoded charsets, which are defined in Python string module.\n\n## Why is this bad?\nUsage of named charsets from the standard library is more readable and less error-prone.\n\n## Example\n```python\nx = \"0123456789\"\ny in \"abcdefghijklmnopqrstuvwxyz\"\n```\n\nUse instead\n```python\nimport string\n\nx = string.digits\ny in string.ascii_lowercase\n```\n\n## References\n- [Python documentation: String constants](https://docs.python.org/3/library/string.html#string-constants)\n",
|
|
860
|
+
"ruff/FURB157": "## What it does\nChecks for unnecessary string literal or float casts in `Decimal`\nconstructors.\n\n## Why is this bad?\nThe `Decimal` constructor accepts a variety of arguments, including\nintegers, floats, and strings. However, it's not necessary to cast\ninteger literals to strings when passing them to the `Decimal`.\n\nSimilarly, `Decimal` accepts `inf`, `-inf`, and `nan` as string literals,\nso there's no need to wrap those values in a `float` call when passing\nthem to the `Decimal` constructor.\n\nPrefer the more concise form of argument passing for `Decimal`\nconstructors, as it's more readable and idiomatic.\n\nNote that this rule does not flag quoted float literals such as `Decimal(\"0.1\")`, which will\nproduce a more precise `Decimal` value than the unquoted `Decimal(0.1)`.\n\n## Example\n```python\nfrom decimal import Decimal\n\nDecimal(\"0\")\nDecimal(float(\"Infinity\"))\n```\n\nUse instead:\n```python\nfrom decimal import Decimal\n\nDecimal(0)\nDecimal(\"Infinity\")\n```\n\n## Fix safety\nThis rule's fix is marked as safe, unless the expression contains comments.\n\n## References\n- [Python documentation: `decimal`](https://docs.python.org/3/library/decimal.html)\n",
|
|
861
|
+
"ruff/FURB161": "## What it does\nChecks for uses of `bin(...).count(\"1\")` to perform a population count.\n\n## Why is this bad?\nIn Python 3.10, a `bit_count()` method was added to the `int` class,\nwhich is more concise and efficient than converting to a binary\nrepresentation via `bin(...)`.\n\n## Example\n```python\nx = bin(123).count(\"1\")\ny = bin(0b1111011).count(\"1\")\n```\n\nUse instead:\n```python\nx = (123).bit_count()\ny = 0b1111011.bit_count()\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe unless the argument to `bin` can be inferred as\nan instance of a type that implements the `__index__` and `bit_count` methods because this can\nchange the exception raised at runtime for an invalid argument.\n\n## Options\n- `target-version`\n\n## References\n- [Python documentation:`int.bit_count`](https://docs.python.org/3/library/stdtypes.html#int.bit_count)\n",
|
|
862
|
+
"ruff/FURB162": "## What it does\nChecks for `datetime.fromisoformat()` calls\nwhere the only argument is an inline replacement\nof `Z` with a zero offset timezone.\n\n## Why is this bad?\nOn Python 3.11 and later, `datetime.fromisoformat()` can handle most [ISO 8601][iso-8601]\nformats including ones affixed with `Z`, so such an operation is unnecessary.\n\nMore information on unsupported formats\ncan be found in [the official documentation][fromisoformat].\n\n## Example\n\n```python\nfrom datetime import datetime\n\n\ndate = \"2025-01-01T00:00:00Z\"\n\ndatetime.fromisoformat(date.replace(\"Z\", \"+00:00\"))\ndatetime.fromisoformat(date[:-1] + \"-00\")\ndatetime.fromisoformat(date.strip(\"Z\", \"-0000\"))\ndatetime.fromisoformat(date.rstrip(\"Z\", \"-00:00\"))\n```\n\nUse instead:\n\n```python\nfrom datetime import datetime\n\n\ndate = \"2025-01-01T00:00:00Z\"\n\ndatetime.fromisoformat(date)\n```\n\n## Fix safety\nThe fix is always marked as unsafe,\nas it might change the program's behaviour.\n\nFor example, working code might become non-working:\n\n```python\nd = \"Z2025-01-01T00:00:00Z\" # Note the leading `Z`\n\ndatetime.fromisoformat(d.strip(\"Z\") + \"+00:00\") # Fine\ndatetime.fromisoformat(d) # Runtime error\n```\n\n## References\n* [What\u2019s New In Python 3.11 § `datetime`](https://docs.python.org/3/whatsnew/3.11.html#datetime)\n* [`fromisoformat`](https://docs.python.org/3/library/datetime.html#datetime.date.fromisoformat)\n\n[iso-8601]: https://www.iso.org/obp/ui/#iso:std:iso:8601\n[fromisoformat]: https://docs.python.org/3/library/datetime.html#datetime.date.fromisoformat\n",
|
|
863
|
+
"ruff/FURB163": "## What it does\nChecks for `math.log` calls with a redundant base.\n\n## Why is this bad?\nThe default base of `math.log` is `e`, so specifying it explicitly is\nredundant.\n\nInstead of passing 2 or 10 as the base, use `math.log2` or `math.log10`\nrespectively, as these dedicated variants are typically more accurate\nthan `math.log`.\n\n## Example\n```python\nimport math\n\nmath.log(4, math.e)\nmath.log(4, 2)\nmath.log(4, 10)\n```\n\nUse instead:\n```python\nimport math\n\nmath.log(4)\nmath.log2(4)\nmath.log10(4)\n```\n\n## Fix safety\nThis fix is marked unsafe when the argument is a starred expression, as this changes\nthe call semantics and may raise runtime errors. It is also unsafe if comments are\npresent within the call, as they will be removed. Additionally, `math.log(x, base)`\nand `math.log2(x)` / `math.log10(x)` may differ due to floating-point rounding, so\nthe fix is also unsafe when making this transformation.\n\n## References\n- [Python documentation: `math.log`](https://docs.python.org/3/library/math.html#math.log)\n- [Python documentation: `math.log2`](https://docs.python.org/3/library/math.html#math.log2)\n- [Python documentation: `math.log10`](https://docs.python.org/3/library/math.html#math.log10)\n- [Python documentation: `math.e`](https://docs.python.org/3/library/math.html#math.e)\n",
|
|
864
|
+
"ruff/FURB164": "## What it does\nChecks for unnecessary `from_float` and `from_decimal` usages to construct\n`Decimal` and `Fraction` instances.\n\n## Why is this bad?\nSince Python 3.2, the `Fraction` and `Decimal` classes can be constructed\nby passing float or decimal instances to the constructor directly. As such,\nthe use of `from_float` and `from_decimal` methods is unnecessary, and\nshould be avoided in favor of the more concise constructor syntax.\n\nHowever, there are important behavioral differences between the `from_*` methods\nand the constructors:\n- The `from_*` methods validate their argument types and raise `TypeError` for invalid types\n- The constructors accept broader argument types without validation\n- The `from_*` methods have different parameter names than the constructors\n\n## Example\n```python\nfrom decimal import Decimal\nfrom fractions import Fraction\n\nDecimal.from_float(4.2)\nDecimal.from_float(float(\"inf\"))\nFraction.from_float(4.2)\nFraction.from_decimal(Decimal(\"4.2\"))\n```\n\nUse instead:\n```python\nfrom decimal import Decimal\nfrom fractions import Fraction\n\nDecimal(4.2)\nDecimal(\"inf\")\nFraction(4.2)\nFraction(Decimal(\"4.2\"))\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe by default because:\n- The `from_*` methods provide type validation that the constructors don't\n- Removing type validation can change program behavior\n- The parameter names are different between methods and constructors\n- The fix may remove comments attached to the original expression\n\nThe fix is marked as safe only when:\n- The argument type is known to be valid for the target constructor\n- No keyword arguments are used, or they match the constructor's parameters\n\n## References\n- [Python documentation: `decimal`](https://docs.python.org/3/library/decimal.html)\n- [Python documentation: `fractions`](https://docs.python.org/3/library/fractions.html)\n",
|
|
865
|
+
"ruff/FURB166": "## What it does\nChecks for uses of `int` with an explicit base in which a string expression\nis stripped of its leading prefix (i.e., `0b`, `0o`, or `0x`).\n\n## Why is this bad?\nGiven an integer string with a prefix (e.g., `0xABC`), Python can automatically\ndetermine the base of the integer by the prefix without needing to specify\nit explicitly.\n\nInstead of `int(num[2:], 16)`, use `int(num, 0)`, which will automatically\ndeduce the base based on the prefix.\n\n## Example\n```python\nnum = \"0xABC\"\n\nif num.startswith(\"0b\"):\n i = int(num[2:], 2)\nelif num.startswith(\"0o\"):\n i = int(num[2:], 8)\nelif num.startswith(\"0x\"):\n i = int(num[2:], 16)\n\nprint(i)\n```\n\nUse instead:\n```python\nnum = \"0xABC\"\n\ni = int(num, 0)\n\nprint(i)\n```\n\n## Fix safety\nThe rule's fix is marked as unsafe, as Ruff cannot guarantee that the\nargument to `int` will remain valid when its base is included in the\nfunction call.\n\n## References\n- [Python documentation: `int`](https://docs.python.org/3/library/functions.html#int)\n",
|
|
866
|
+
"ruff/FURB167": "## What it does\nChecks for the use of shorthand aliases for regular expression flags\n(e.g., `re.I` instead of `re.IGNORECASE`).\n\n## Why is this bad?\nThe regular expression module provides descriptive names for each flag,\nalong with single-letter aliases. Prefer the descriptive names, as they\nare more readable and self-documenting.\n\n## Example\n```python\nimport re\n\nif re.search(\"^hello\", \"hello world\", re.I):\n ...\n```\n\nUse instead:\n```python\nimport re\n\nif re.search(\"^hello\", \"hello world\", re.IGNORECASE):\n ...\n```\n",
|
|
867
|
+
"ruff/FURB168": "## What it does\nChecks for uses of `isinstance` that check if an object is of type `None`.\n\n## Why is this bad?\nThere is only ever one instance of `None`, so it is more efficient and\nreadable to use the `is` operator to check if an object is `None`.\n\n## Example\n```python\nisinstance(obj, type(None))\n```\n\nUse instead:\n```python\nobj is None\n```\n\n## Fix safety\nThe fix will be marked as unsafe if there are any comments within the call.\n\n## References\n- [Python documentation: `isinstance`](https://docs.python.org/3/library/functions.html#isinstance)\n- [Python documentation: `None`](https://docs.python.org/3/library/constants.html#None)\n- [Python documentation: `type`](https://docs.python.org/3/library/functions.html#type)\n- [Python documentation: Identity comparisons](https://docs.python.org/3/reference/expressions.html#is-not)\n",
|
|
868
|
+
"ruff/FURB169": "## What it does\nChecks for uses of `type` that compare the type of an object to the type of `None`.\n\n## Why is this bad?\nThere is only ever one instance of `None`, so it is more efficient and\nreadable to use the `is` operator to check if an object is `None`.\n\n## Example\n```python\ntype(obj) is type(None)\n```\n\nUse instead:\n```python\nobj is None\n```\n\n## Fix safety\nIf the fix might remove comments, it will be marked as unsafe.\n\n## References\n- [Python documentation: `isinstance`](https://docs.python.org/3/library/functions.html#isinstance)\n- [Python documentation: `None`](https://docs.python.org/3/library/constants.html#None)\n- [Python documentation: `type`](https://docs.python.org/3/library/functions.html#type)\n- [Python documentation: Identity comparisons](https://docs.python.org/3/reference/expressions.html#is-not)\n",
|
|
869
|
+
"ruff/FURB171": "## What it does\nChecks for membership tests against single-item containers.\n\n## Why is this bad?\nPerforming a membership test against a container (like a `list` or `set`)\nwith a single item is less readable and less efficient than comparing\nagainst the item directly.\n\n## Example\n```python\n1 in [1]\n```\n\nUse instead:\n```python\n1 == 1\n```\n\n## Fix safety\nThe fix is always marked as unsafe.\n\nWhen the right-hand side is a string, this fix can change the behavior of your program.\nThis is because `c in \"a\"` is true both when `c` is `\"a\"` and when `c` is the empty string.\n\nAdditionally, converting `in`/`not in` against a single-item container to `==`/`!=` can\nchange runtime behavior: `in` may consider identity (e.g., `NaN`) and always\nyields a `bool`.\n\nComments within the replacement range will also be removed.\n\n## References\n- [Python documentation: Comparisons](https://docs.python.org/3/reference/expressions.html#comparisons)\n- [Python documentation: Membership test operations](https://docs.python.org/3/reference/expressions.html#membership-test-operations)\n",
|
|
870
|
+
"ruff/FURB177": "## What it does\nChecks for current-directory lookups using `Path().resolve()`.\n\n## Why is this bad?\nWhen looking up the current directory, prefer `Path.cwd()` over\n`Path().resolve()`, as `Path.cwd()` is more explicit in its intent.\n\n## Example\n```python\nfrom pathlib import Path\n\ncwd = Path().resolve()\n```\n\nUse instead:\n```python\nfrom pathlib import Path\n\ncwd = Path.cwd()\n```\n\n## References\n- [Python documentation: `Path.cwd`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.cwd)\n",
|
|
871
|
+
"ruff/FURB180": "## What it does\nChecks for uses of `metaclass=abc.ABCMeta` to define abstract base classes\n(ABCs).\n\n## Why is this bad?\n\nInstead of `class C(metaclass=abc.ABCMeta): ...`, use `class C(ABC): ...`\nto define an abstract base class. Inheriting from the `ABC` wrapper class\nis semantically identical to setting `metaclass=abc.ABCMeta`, but more\nsuccinct.\n\n## Example\n```python\nimport abc\n\n\nclass C(metaclass=abc.ABCMeta):\n pass\n```\n\nUse instead:\n```python\nimport abc\n\n\nclass C(abc.ABC):\n pass\n```\n\n## Fix safety\nThe rule's fix is unsafe if the class has base classes. This is because the base classes might\nbe validating the class's other base classes (e.g., `typing.Protocol` does this) or otherwise\nalter runtime behavior if more base classes are added.\nThe rule's fix will also be marked as unsafe if the class has\ncomments in its argument list that could be deleted.\n\n\n## References\n- [Python documentation: `abc.ABC`](https://docs.python.org/3/library/abc.html#abc.ABC)\n- [Python documentation: `abc.ABCMeta`](https://docs.python.org/3/library/abc.html#abc.ABCMeta)\n",
|
|
872
|
+
"ruff/FURB181": "## What it does\nChecks for the use of `.digest().hex()` on a hashlib hash, like `sha512`.\n\n## Why is this bad?\nWhen generating a hex digest from a hash, it's preferable to use the\n`.hexdigest()` method, rather than calling `.digest()` and then `.hex()`,\nas the former is more concise and readable.\n\n## Example\n```python\nfrom hashlib import sha512\n\nhashed = sha512(b\"some data\").digest().hex()\n```\n\nUse instead:\n```python\nfrom hashlib import sha512\n\nhashed = sha512(b\"some data\").hexdigest()\n```\n\n## Fix safety\nThis rule's fix is marked as safe, unless the expression contains comments.\n\n## References\n- [Python documentation: `hashlib`](https://docs.python.org/3/library/hashlib.html)\n",
|
|
873
|
+
"ruff/FURB187": "## What it does\nChecks for list reversals that can be performed in-place in lieu of\ncreating a new list.\n\n## Why is this bad?\nWhen reversing a list, it's more efficient to use the in-place method\n`.reverse()` instead of creating a new list, if the original list is\nno longer needed.\n\n## Example\n```python\nl = [1, 2, 3]\nl = reversed(l)\n\nl = [1, 2, 3]\nl = list(reversed(l))\n\nl = [1, 2, 3]\nl = l[::-1]\n```\n\nUse instead:\n```python\nl = [1, 2, 3]\nl.reverse()\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as calling `.reverse()` on a list\nwill mutate the list in-place, unlike `reversed`, which creates a new list\nand leaves the original list unchanged.\n\nIf the list is referenced elsewhere, this could lead to unexpected\nbehavior.\n\n## References\n- [Python documentation: More on Lists](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)\n",
|
|
874
|
+
"ruff/FURB188": "## What it does\nChecks for code that could be written more idiomatically using\n[`str.removeprefix()`](https://docs.python.org/3/library/stdtypes.html#str.removeprefix)\nor [`str.removesuffix()`](https://docs.python.org/3/library/stdtypes.html#str.removesuffix).\n\nSpecifically, the rule flags code that conditionally removes a prefix or suffix\nusing a slice operation following an `if` test that uses `str.startswith()` or `str.endswith()`.\n\nThe rule is only applied if your project targets Python 3.9 or later.\n\n## Why is this bad?\nThe methods [`str.removeprefix()`](https://docs.python.org/3/library/stdtypes.html#str.removeprefix)\nand [`str.removesuffix()`](https://docs.python.org/3/library/stdtypes.html#str.removesuffix),\nintroduced in Python 3.9, have the same behavior while being more readable and efficient.\n\n## Example\n```python\ndef example(filename: str, text: str):\n filename = filename[:-4] if filename.endswith(\".txt\") else filename\n\n if text.startswith(\"pre\"):\n text = text[3:]\n```\n\nUse instead:\n```python\ndef example(filename: str, text: str):\n filename = filename.removesuffix(\".txt\")\n text = text.removeprefix(\"pre\")\n```\n\n## Fix safety\nThis rule's fix is marked as safe, unless the expression contains comments.\n",
|
|
875
|
+
"ruff/FURB189": "## What it does\nChecks for subclasses of `dict`, `list` or `str`.\n\n## Why is this bad?\nBuilt-in types don't consistently use their own dunder methods. For example,\n`dict.__init__` and `dict.update()` bypass `__setitem__`, making inheritance unreliable.\n\nUse the `UserDict`, `UserList`, and `UserString` objects from the `collections` module\ninstead.\n\nThis rule does not apply to stub files, which should faithfully represent the runtime\nimplementation and may be out of the author's control.\n\n## Example\n\n```python\nclass UppercaseDict(dict):\n def __setitem__(self, key, value):\n super().__setitem__(key.upper(), value)\n\n\nd = UppercaseDict({\"a\": 1, \"b\": 2}) # Bypasses __setitem__\nprint(d) # {'a': 1, 'b': 2}\n```\n\nUse instead:\n\n```python\nfrom collections import UserDict\n\n\nclass UppercaseDict(UserDict):\n def __setitem__(self, key, value):\n super().__setitem__(key.upper(), value)\n\n\nd = UppercaseDict({\"a\": 1, \"b\": 2}) # Uses __setitem__\nprint(d) # {'A': 1, 'B': 2}\n```\n\n## Fix safety\nThis fix is marked as unsafe because `isinstance()` checks for `dict`,\n`list`, and `str` types will fail when using the corresponding User class.\nIf you need to pass custom `dict` or `list` objects to code you don't\ncontrol, ignore this check. If you do control the code, consider using\nthe following type checks instead:\n\n* `dict` -> `collections.abc.MutableMapping`\n* `list` -> `collections.abc.MutableSequence`\n* `str` -> No such conversion exists\n\n## References\n\n- [Python documentation: `collections`](https://docs.python.org/3/library/collections.html)\n",
|
|
876
|
+
"ruff/FURB192": "## What it does\nChecks for uses of `sorted()` to retrieve the minimum or maximum value in\na sequence.\n\n## Why is this bad?\nUsing `sorted()` to compute the minimum or maximum value in a sequence is\ninefficient and less readable than using `min()` or `max()` directly.\n\n## Example\n```python\nnums = [3, 1, 4, 1, 5]\nlowest = sorted(nums)[0]\nhighest = sorted(nums)[-1]\nhighest = sorted(nums, reverse=True)[0]\n```\n\nUse instead:\n```python\nnums = [3, 1, 4, 1, 5]\nlowest = min(nums)\nhighest = max(nums)\n```\n\n## Fix safety\nIn some cases, migrating to `min` or `max` can lead to a change in behavior,\nnotably when breaking ties.\n\nAs an example, `sorted(data, key=itemgetter(0), reverse=True)[0]` will return\nthe _last_ \"minimum\" element in the list, if there are multiple elements with\nthe same key. However, `min(data, key=itemgetter(0))` will return the _first_\n\"minimum\" element in the list in the same scenario.\n\nThe fix also changes which exception is raised for an empty sequence:\n`sorted([])[0]` raises `IndexError`, but `min([])` and `max([])` raise\n`ValueError`. Code that catches one specific exception type will need to\nbe updated after the fix is applied.\n\nAs such, this rule's fix is marked as unsafe.\n\n## References\n- [Python documentation: `min`](https://docs.python.org/3/library/functions.html#min)\n- [Python documentation: `max`](https://docs.python.org/3/library/functions.html#max)\n",
|
|
877
|
+
"ruff/RUF001": "## What it does\nChecks for ambiguous Unicode characters in strings.\n\n## Why is this bad?\nSome Unicode characters are visually similar to ASCII characters, but have\ndifferent code points. For example, `GREEK CAPITAL LETTER ALPHA` (`U+0391`)\nis visually similar, but not identical, to the ASCII character `A`.\n\nThe use of ambiguous Unicode characters can confuse readers, cause subtle\nbugs, and even make malicious code look harmless.\n\nIn [preview], this rule will also flag Unicode characters that are\nconfusable with other, non-preferred Unicode characters. For example, the\nspec recommends `GREEK CAPITAL LETTER OMEGA` over `OHM SIGN`.\n\nYou can omit characters from being flagged as ambiguous via the\n[`lint.allowed-confusables`] setting.\n\n## Example\n```python\nprint(\"\u0397ello, world!\") # \"\u0397\" is the Greek eta (`U+0397`).\n```\n\nUse instead:\n```python\nprint(\"Hello, world!\") # \"H\" is the Latin capital H (`U+0048`).\n```\n\n## Options\n- `lint.allowed-confusables`\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
878
|
+
"ruff/RUF002": "## What it does\nChecks for ambiguous Unicode characters in docstrings.\n\n## Why is this bad?\nSome Unicode characters are visually similar to ASCII characters, but have\ndifferent code points. For example, `GREEK CAPITAL LETTER ALPHA` (`U+0391`)\nis visually similar, but not identical, to the ASCII character `A`.\n\nThe use of ambiguous Unicode characters can confuse readers, cause subtle\nbugs, and even make malicious code look harmless.\n\nIn [preview], this rule will also flag Unicode characters that are\nconfusable with other, non-preferred Unicode characters. For example, the\nspec recommends `GREEK CAPITAL LETTER OMEGA` over `OHM SIGN`.\n\nYou can omit characters from being flagged as ambiguous via the\n[`lint.allowed-confusables`] setting.\n\n## Example\n```python\n\"\"\"A lovely docstring (with a `U+FF09` parenthesis\uff09.\"\"\"\n```\n\nUse instead:\n```python\n\"\"\"A lovely docstring (with no strange parentheses).\"\"\"\n```\n\n## Options\n- `lint.allowed-confusables`\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
879
|
+
"ruff/RUF003": "## What it does\nChecks for ambiguous Unicode characters in comments.\n\n## Why is this bad?\nSome Unicode characters are visually similar to ASCII characters, but have\ndifferent code points. For example, `GREEK CAPITAL LETTER ALPHA` (`U+0391`)\nis visually similar, but not identical, to the ASCII character `A`.\n\nThe use of ambiguous Unicode characters can confuse readers, cause subtle\nbugs, and even make malicious code look harmless.\n\nIn [preview], this rule will also flag Unicode characters that are\nconfusable with other, non-preferred Unicode characters. For example, the\nspec recommends `GREEK CAPITAL LETTER OMEGA` over `OHM SIGN`.\n\nYou can omit characters from being flagged as ambiguous via the\n[`lint.allowed-confusables`] setting.\n\n## Example\n```python\nfoo() # n\u043eqa # \"\u043e\" is Cyrillic (`U+043E`)\n```\n\nUse instead:\n```python\nfoo() # noqa # \"o\" is Latin (`U+006F`)\n```\n\n## Options\n- `lint.allowed-confusables`\n\n[preview]: https://docs.astral.sh/ruff/preview/\n",
|
|
880
|
+
"ruff/RUF005": "## What it does\nChecks for uses of the `+` operator to concatenate collections.\n\n## Why is this bad?\nIn Python, the `+` operator can be used to concatenate collections (e.g.,\n`x + y` to concatenate the lists `x` and `y`).\n\nHowever, collections can be concatenated more efficiently using the\nunpacking operator (e.g., `[*x, *y]` to concatenate `x` and `y`).\n\nPrefer the unpacking operator to concatenate collections, as it is more\nreadable and flexible. The `*` operator can unpack any iterable, whereas\n `+` operates only on particular sequences which, in many cases, must be of\nthe same type.\n\n## Example\n```python\nfoo = [2, 3, 4]\nbar = [1] + foo + [5, 6]\n```\n\nUse instead:\n```python\nfoo = [2, 3, 4]\nbar = [1, *foo, 5, 6]\n```\n\n## Fix safety\n\nThe fix is always marked as unsafe because the `+` operator uses the `__add__` magic method and\n`*`-unpacking uses the `__iter__` magic method. Both of these could have custom\nimplementations, causing the fix to change program behaviour.\n\n## References\n- [PEP 448 \u2013 Additional Unpacking Generalizations](https://peps.python.org/pep-0448/)\n- [Python documentation: Sequence Types \u2014 `list`, `tuple`, `range`](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range)\n",
|
|
881
|
+
"ruff/RUF006": "## What it does\nChecks for `asyncio.create_task` and `asyncio.ensure_future` calls\nthat do not store a reference to the returned result.\n\n## Why is this bad?\nPer the `asyncio` documentation, the event loop only retains a weak\nreference to tasks. If the task returned by `asyncio.create_task` and\n`asyncio.ensure_future` is not stored in a variable, or a collection,\nor otherwise referenced, it may be garbage collected at any time. This\ncan lead to unexpected and inconsistent behavior, as your tasks may or\nmay not run to completion.\n\n## Example\n```python\nimport asyncio\n\nfor i in range(10):\n # This creates a weak reference to the task, which may be garbage\n # collected at any time.\n asyncio.create_task(some_coro(param=i))\n```\n\nUse instead:\n```python\nimport asyncio\n\nbackground_tasks = set()\n\nfor i in range(10):\n task = asyncio.create_task(some_coro(param=i))\n\n # Add task to the set. This creates a strong reference.\n background_tasks.add(task)\n\n # To prevent keeping references to finished tasks forever,\n # make each task remove its own reference from the set after\n # completion:\n task.add_done_callback(background_tasks.discard)\n```\n\nOr, for Python 3.11 and later, use structured concurrency with\n`asyncio.TaskGroup` when the tasks should be awaited as part of the current\noperation:\n```python\nimport asyncio\n\n\nasync def main() -> None:\n async with asyncio.TaskGroup() as tg:\n for i in range(10):\n tg.create_task(some_coro(param=i))\n```\n\n## References\n- [_The Heisenbug lurking in your async code_](https://textual.textualize.io/blog/2023/02/11/the-heisenbug-lurking-in-your-async-code/)\n- [Python documentation: `asyncio.create_task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task)\n- [Python documentation: `asyncio.TaskGroup`](https://docs.python.org/3/library/asyncio-task.html#asyncio.TaskGroup)\n",
|
|
882
|
+
"ruff/RUF007": "## What it does\nChecks for use of `zip()` to iterate over successive pairs of elements.\n\n## Why is this bad?\nWhen iterating over successive pairs of elements, prefer\n`itertools.pairwise()` over `zip()`.\n\n`itertools.pairwise()` is more readable and conveys the intent of the code\nmore clearly.\n\n## Example\n```python\nletters = \"ABCD\"\nzip(letters, letters[1:]) # (\"A\", \"B\"), (\"B\", \"C\"), (\"C\", \"D\")\n```\n\nUse instead:\n```python\nfrom itertools import pairwise\n\nletters = \"ABCD\"\npairwise(letters) # (\"A\", \"B\"), (\"B\", \"C\"), (\"C\", \"D\")\n```\n\n## Fix safety\n\nThe fix is always marked unsafe because it assumes that slicing an object\n(e.g., `obj[1:]`) produces a value with the same type and iteration behavior\nas the original object, which is not guaranteed for user-defined types that\noverride `__getitem__` without properly handling slices. Moreover, the fix\ncould delete comments.\n\n## References\n- [Python documentation: `itertools.pairwise`](https://docs.python.org/3/library/itertools.html#itertools.pairwise)\n",
|
|
883
|
+
"ruff/RUF008": "## What it does\nChecks for mutable default values in dataclass attributes.\n\n## Why is this bad?\nMutable default values share state across all instances of the dataclass.\nThis can lead to bugs when the attributes are changed in one instance, as\nthose changes will unexpectedly affect all other instances.\n\nInstead of sharing mutable defaults, use the `field(default_factory=...)`\npattern.\n\nIf the default value is intended to be mutable, it must be annotated with\n`typing.ClassVar`; otherwise, a `ValueError` will be raised.\n\nIn [preview](https://docs.astral.sh/ruff/preview/) this rule also detects mutable defaults passed via the `default` keyword\nargument in `field()` (for stdlib dataclasses), `attrs.field()`, `attr.ib()`,\nand `attr.attrib()` calls.\n\n## Example\n```python\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass A:\n # A list without a `default_factory` or `ClassVar` annotation\n # will raise a `ValueError`.\n mutable_default: list[int] = []\n```\n\nUse instead:\n```python\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass A:\n mutable_default: list[int] = field(default_factory=list)\n```\n\nOr:\n```python\nfrom dataclasses import dataclass\nfrom typing import ClassVar\n\n\n@dataclass\nclass A:\n mutable_default: ClassVar[list[int]] = []\n```\n",
|
|
884
|
+
"ruff/RUF009": "## What it does\nChecks for function calls in dataclass attribute defaults.\n\n## Why is this bad?\nFunction calls are only performed once, at definition time. The returned\nvalue is then reused by all instances of the dataclass. This can lead to\nunexpected behavior when the function call returns a mutable object, as\nchanges to the object will be shared across all instances.\n\nIf a field needs to be initialized with a mutable object, use the\n`field(default_factory=...)` pattern.\n\nAttributes whose default arguments are `NewType` calls\nwhere the original type is immutable are ignored.\n\n## Example\n```python\nfrom dataclasses import dataclass\n\n\ndef simple_list() -> list[int]:\n return [1, 2, 3, 4]\n\n\n@dataclass\nclass A:\n mutable_default: list[int] = simple_list()\n```\n\nUse instead:\n```python\nfrom dataclasses import dataclass, field\n\n\ndef creating_list() -> list[int]:\n return [1, 2, 3, 4]\n\n\n@dataclass\nclass A:\n mutable_default: list[int] = field(default_factory=creating_list)\n```\n\n## Options\n- `lint.flake8-bugbear.extend-immutable-calls`\n",
|
|
885
|
+
"ruff/RUF010": "## What it does\nChecks for uses of `str()`, `repr()`, and `ascii()` as explicit type\nconversions within f-strings.\n\n## Why is this bad?\nf-strings support dedicated conversion flags for these types, which are\nmore succinct and idiomatic.\n\nNote that, in many cases, calling `str()` within an f-string is\nunnecessary and can be removed entirely, as the value will be converted\nto a string automatically, the notable exception being for classes that\nimplement a custom `__format__` method.\n\n## Example\n```python\na = \"some string\"\nf\"{repr(a)}\"\n```\n\nUse instead:\n```python\na = \"some string\"\nf\"{a!r}\"\n```\n\n## Fix safety\n\nThis rule's fix is marked as unsafe if the call expression contains\ncomments that would be deleted by applying the fix.\n",
|
|
886
|
+
"ruff/RUF011": "## Removed\nThis rule was implemented in `flake8-bugbear` and has been remapped to [B035]\n\n## What it does\nChecks for dictionary comprehensions that use a static key, like a string\nliteral or a variable defined outside the comprehension.\n\n## Why is this bad?\nUsing a static key (like a string literal) in a dictionary comprehension\nis usually a mistake, as it will result in a dictionary with only one key,\ndespite the comprehension iterating over multiple values.\n\n## Example\n```python\ndata = [\"some\", \"Data\"]\n{\"key\": value.upper() for value in data}\n```\n\nUse instead:\n```python\ndata = [\"some\", \"Data\"]\n{value: value.upper() for value in data}\n```\n\n[B035]: https://docs.astral.sh/ruff/rules/static-key-dict-comprehension/\n",
|
|
887
|
+
"ruff/RUF013": "## What it does\nChecks for the use of implicit `Optional` in type annotations when the\ndefault parameter value is `None`.\n\nIf [`lint.future-annotations`] is set to `true`, `from __future__ import\nannotations` will be added if doing so would allow using the `|` operator on\na Python version before 3.10.\n\n## Why is this bad?\nImplicit `Optional` is prohibited by [PEP 484]. It is confusing and\ninconsistent with the rest of the type system.\n\nIt's recommended to use `Optional[T]` instead. For Python 3.10 and later,\nyou can also use `T | None`.\n\n## Example\n```python\ndef foo(arg: int = None):\n pass\n```\n\nUse instead:\n```python\nfrom typing import Optional\n\n\ndef foo(arg: Optional[int] = None):\n pass\n```\n\nOr, for Python 3.10 and later:\n```python\ndef foo(arg: int | None = None):\n pass\n```\n\nIf you want to use the `|` operator in Python 3.9 and earlier, you can\nuse future imports:\n```python\nfrom __future__ import annotations\n\n\ndef foo(arg: int | None = None):\n pass\n```\n\n## Limitations\n\nType aliases and other user-defined types are not supported and could\nresult in false negatives. For example, the following code will not be\nflagged:\n\n```python\nText = str | bytes\n\n\nclass Custom: ...\n\n\ndef foo(text_arg: Text = None, custom_arg: Custom = None):\n pass\n```\n\n## Options\n- `target-version`\n- `lint.future-annotations`\n\n## Fix safety\n\nThis fix is always marked as unsafe because it can change the behavior of code that relies on\ntype hints, and it assumes the default value is always appropriate\u2014which might not be the case.\n\n[PEP 484]: https://peps.python.org/pep-0484/#union-types\n",
|
|
888
|
+
"ruff/RUF015": "## What it does\nChecks the following constructs, all of which can be replaced by\n`next(iter(...))`:\n\n- `list(...)[0]`\n- `tuple(...)[0]`\n- `list(i for i in ...)[0]`\n- `[i for i in ...][0]`\n- `list(...).pop(0)`\n\n## Why is this bad?\nCalling e.g. `list(...)` will create a new list of the entire collection,\nwhich can be very expensive for large collections. If you only need the\nfirst element of the collection, you can use `next(...)` or\n`next(iter(...)` to lazily fetch the first element. The same is true for\nthe other constructs.\n\n## Example\n```python\nhead = list(x)[0]\nhead = [x * x for x in range(10)][0]\n```\n\nUse instead:\n```python\nhead = next(iter(x))\nhead = next(x * x for x in range(10))\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as migrating from (e.g.) `list(...)[0]`\nto `next(iter(...))` can change the behavior of your program in two ways:\n\n1. First, all above-mentioned constructs will eagerly evaluate the entire\n collection, while `next(iter(...))` will only evaluate the first\n element. As such, any side effects that occur during iteration will be\n delayed.\n2. Second, accessing members of a collection via square bracket notation\n `[0]` or the `pop()` function will raise `IndexError` if the collection\n is empty, while `next(iter(...))` will raise `StopIteration`.\n\n## References\n- [Iterators and Iterables in Python: Run Efficient Iterations](https://realpython.com/python-iterators-iterables/#when-to-use-an-iterator-in-python)\n",
|
|
889
|
+
"ruff/RUF016": "## What it does\nChecks for indexed access to lists, strings, tuples, bytes, and comprehensions\nusing a type other than an integer or slice.\n\n## Why is this bad?\nOnly integers or slices can be used as indices to these types. Using\nother types will result in a `TypeError` at runtime and a `SyntaxWarning` at\nimport time.\n\n## Example\n```python\nvar = [1, 2, 3][\"x\"]\n```\n\nUse instead:\n```python\nvar = [1, 2, 3][0]\n```\n",
|
|
890
|
+
"ruff/RUF017": "## What it does\nChecks for the use of `sum()` to flatten lists of lists, which has\nquadratic complexity.\n\n## Why is this bad?\nThe use of `sum()` to flatten lists of lists is quadratic in the number of\nlists, as `sum()` creates a new list for each element in the summation.\n\nInstead, consider using another method of flattening lists to avoid\nquadratic complexity. The following methods are all linear in the number of\nlists:\n\n- `[*sublist for sublist in lists]` (Python 3.15+)\n- `functools.reduce(operator.iadd, lists, [])`\n- `list(itertools.chain.from_iterable(lists))`\n- `[item for sublist in lists for item in sublist]`\n\nWhen fixing relevant violations, Ruff uses the starred-list-comprehension\nform on Python 3.15 and later. On older Python versions, Ruff falls back to\nthe `functools.reduce` form, which outperforms the other pre-3.15\nalternatives in [microbenchmarks].\n\n## Example\n```python\nlists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\njoined = sum(lists, [])\n```\n\nOn Python 3.14 and earlier, use instead:\n```python\nimport functools\nimport operator\n\nlists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\njoined = functools.reduce(operator.iadd, lists, [])\n```\n\nOn Python 3.15 and later, use instead:\n```python\nlists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\njoined = [*sublist for sublist in lists]\n```\n\n## Fix safety\n\nThis fix is always marked as unsafe because the replacement may accept any\niterable where `sum` previously required lists. On Python 3.15 and later,\nRuff uses iterable unpacking within a list comprehension; on older Python\nversions, Ruff uses `operator.iadd`. In both cases, code that previously\nraised an error may silently succeed. Moreover, the fix could remove\ncomments from the original code.\n\n## References\n- [_How Not to Flatten a List of Lists in Python_](https://mathieularose.com/how-not-to-flatten-a-list-of-lists-in-python)\n- [_How do I make a flat list out of a list of lists?_](https://stackoverflow.com/questions/952914/how-do-i-make-a-flat-list-out-of-a-list-of-lists/953097#953097)\n\n[microbenchmarks]: https://github.com/astral-sh/ruff/issues/5073#issuecomment-1591836349\n",
|
|
891
|
+
"ruff/RUF018": "## What it does\nChecks for named assignment expressions (e.g., `x := 0`) in `assert`\nstatements.\n\n## Why is this bad?\nNamed assignment expressions (also known as \"walrus operators\") are used to\nassign a value to a variable as part of a larger expression.\n\nNamed assignments are syntactically valid in `assert` statements. However,\nwhen the Python interpreter is run under the `-O` flag, `assert` statements\nare not executed. In this case, the named assignment will also be ignored,\nwhich may result in unexpected behavior (e.g., undefined variable\naccesses).\n\n## Example\n```python\nassert (x := 0) == 0\nprint(x)\n```\n\nUse instead:\n```python\nx = 0\nassert x == 0\nprint(x)\n```\n\nThe rule avoids flagging named expressions that define variables which are\nonly referenced from inside `assert` statements; the following will not\ntrigger the rule:\n```python\nassert (x := y**2) > 42, f\"Expected >42 but got {x}\"\n```\n\nNor will this:\n```python\nassert (x := y**2) > 42\nassert x < 1_000_000\n```\n\n## References\n- [Python documentation: `-O`](https://docs.python.org/3/using/cmdline.html#cmdoption-O)\n",
|
|
892
|
+
"ruff/RUF019": "## What it does\nChecks for unnecessary key checks prior to accessing a dictionary.\n\n## Why is this bad?\nWhen working with dictionaries, the `get` can be used to access a value\nwithout having to check if the dictionary contains the relevant key,\nreturning `None` if the key is not present.\n\n## Example\n```python\nif \"key\" in dct and dct[\"key\"]:\n ...\n```\n\nUse instead:\n```python\nif dct.get(\"key\"):\n ...\n```\n\n## Fix safety\nThis rule's fix is marked as safe, unless the expression contains comments\nor may have side effects.\n",
|
|
893
|
+
"ruff/RUF020": "## What it does\nChecks for uses of `typing.NoReturn` and `typing.Never` in union types.\n\n## Why is this bad?\n`typing.NoReturn` and `typing.Never` are special types, used to indicate\nthat a function never returns, or that a type has no values.\n\nIncluding `typing.NoReturn` or `typing.Never` in a union type is redundant,\nas, e.g., `typing.Never | T` is equivalent to `T`.\n\n## Example\n\n```python\nfrom typing import Never\n\n\ndef func() -> Never | int: ...\n```\n\nUse instead:\n\n```python\ndef func() -> int: ...\n```\n\n## Fix safety\nThis rule's fix is marked as safe, unless the union type contains comments.\n\n## References\n- [Python documentation: `typing.Never`](https://docs.python.org/3/library/typing.html#typing.Never)\n- [Python documentation: `typing.NoReturn`](https://docs.python.org/3/library/typing.html#typing.NoReturn)\n",
|
|
894
|
+
"ruff/RUF021": "## What it does\nChecks for chained operators where adding parentheses could improve the\nclarity of the code.\n\n## Why is this bad?\n`and` always binds more tightly than `or` when chaining the two together,\nbut this can be hard to remember (and sometimes surprising).\nAdding parentheses in these situations can greatly improve code readability,\nwith no change to semantics or performance.\n\nFor example:\n```python\na, b, c = 1, 0, 2\nx = a or b and c\n\nd, e, f = 0, 1, 2\ny = d and e or f\n```\n\nUse instead:\n```python\na, b, c = 1, 0, 2\nx = a or (b and c)\n\nd, e, f = 0, 1, 2\ny = (d and e) or f\n```\n",
|
|
895
|
+
"ruff/RUF022": "## What it does\nChecks for `__all__` definitions that are not ordered\naccording to an \"isort-style\" sort.\n\nAn isort-style sort orders items first according to their casing:\nSCREAMING_SNAKE_CASE names (conventionally used for global constants)\ncome first, followed by CamelCase names (conventionally used for\nclasses), followed by anything else. Within each category,\na [natural sort](https://en.wikipedia.org/wiki/Natural_sort_order)\nis used to order the elements.\n\nNote that \"isort-style\" sorting here refers to how `isort` categorizes\nand orders imported symbols by casing (similar to `isort`'s\n[`order-by-type`](https://isort.readthedocs.io/en/latest/configuration/options.html#order-by-type)\nsetting), rather than `isort`'s\n[`sort-reexports`](https://isort.readthedocs.io/en/latest/configuration/options.html#sort-re-exports)\noption, which sorts `__all__` strictly lexicographically.\n\n## Why is this bad?\nConsistency is good. Use a common convention for `__all__` to make your\ncode more readable and idiomatic.\n\n## Example\n```python\nimport sys\n\n__all__ = [\n \"b\",\n \"c\",\n \"a\",\n]\n\nif sys.platform == \"win32\":\n __all__ += [\"z\", \"y\"]\n```\n\nUse instead:\n```python\nimport sys\n\n__all__ = [\n \"a\",\n \"b\",\n \"c\",\n]\n\nif sys.platform == \"win32\":\n __all__ += [\"y\", \"z\"]\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe if there are any comments that take up\na whole line by themselves inside the `__all__` definition, for example:\n```py\n__all__ = [\n # eggy things\n \"duck_eggs\",\n \"chicken_eggs\",\n # hammy things\n \"country_ham\",\n \"parma_ham\",\n]\n```\n\nThis is a common pattern used to delimit categories within a module's API,\nbut it would be out of the scope of this rule to attempt to maintain these\ncategories when alphabetically sorting the items of `__all__`.\n\nThe fix is also marked as unsafe if there are more than two `__all__` items\non a single line and that line also has a trailing comment, since here it\nis impossible to accurately gauge which item the comment should be moved\nwith when sorting `__all__`:\n```py\n__all__ = [\n \"a\", \"c\", \"e\", # a comment\n \"b\", \"d\", \"f\", # a second comment\n]\n```\n\nOther than this, the rule's fix is marked as always being safe, in that\nit should very rarely alter the semantics of any Python code.\nHowever, note that (although it's rare) the value of `__all__`\ncould be read by code elsewhere that depends on the exact\niteration order of the items in `__all__`, in which case this\nrule's fix could theoretically cause breakage.\n",
|
|
896
|
+
"ruff/RUF023": "## What it does\nChecks for `__slots__` definitions that are not ordered according to a\n[natural sort](https://en.wikipedia.org/wiki/Natural_sort_order).\n\n## Why is this bad?\nConsistency is good. Use a common convention for this special variable\nto make your code more readable and idiomatic.\n\n## Example\n```python\nclass Dog:\n __slots__ = \"name\", \"breed\"\n```\n\nUse instead:\n```python\nclass Dog:\n __slots__ = \"breed\", \"name\"\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe in three situations.\n\nFirstly, the fix is unsafe if there are any comments that take up\na whole line by themselves inside the `__slots__` definition, for example:\n```py\nclass Foo:\n __slots__ = [\n # eggy things\n \"duck_eggs\",\n \"chicken_eggs\",\n # hammy things\n \"country_ham\",\n \"parma_ham\",\n ]\n```\n\nThis is a common pattern used to delimit categories within a class's slots,\nbut it would be out of the scope of this rule to attempt to maintain these\ncategories when applying a natural sort to the items of `__slots__`.\n\nSecondly, the fix is also marked as unsafe if there are more than two\n`__slots__` items on a single line and that line also has a trailing\ncomment, since here it is impossible to accurately gauge which item the\ncomment should be moved with when sorting `__slots__`:\n```py\nclass Bar:\n __slots__ = [\n \"a\", \"c\", \"e\", # a comment\n \"b\", \"d\", \"f\", # a second comment\n ]\n```\n\nLastly, this rule's fix is marked as unsafe whenever Ruff can detect that\ncode elsewhere in the same file reads the `__slots__` variable in some way\nand the `__slots__` variable is not assigned to a set. This is because the\norder of the items in `__slots__` may have semantic significance if the\n`__slots__` of a class is being iterated over, or being assigned to another\nvalue.\n\nIn the vast majority of other cases, this rule's fix is unlikely to\ncause breakage; as such, Ruff will otherwise mark this rule's fix as\nsafe. However, note that (although it's rare) the value of `__slots__`\ncould still be read by code outside of the module in which the\n`__slots__` definition occurs, in which case this rule's fix could\ntheoretically cause breakage.\n",
|
|
897
|
+
"ruff/RUF024": "## What it does\nChecks for mutable objects passed as a value argument to `dict.fromkeys`.\n\n## Why is this bad?\nAll values in the dictionary created by the `dict.fromkeys` method\nrefer to the same instance of the provided object. If that object is\nmodified, all values are modified, which can lead to unexpected behavior.\nFor example, if the empty list (`[]`) is provided as the default value,\nall values in the dictionary will use the same list; as such, appending to\nany one entry will append to all entries.\n\nInstead, use a comprehension to generate a dictionary with distinct\ninstances of the default value.\n\n## Example\n```python\ncities = dict.fromkeys([\"UK\", \"Poland\"], [])\ncities[\"UK\"].append(\"London\")\ncities[\"Poland\"].append(\"Poznan\")\nprint(cities) # {'UK': ['London', 'Poznan'], 'Poland': ['London', 'Poznan']}\n```\n\nUse instead:\n```python\ncities = {country: [] for country in [\"UK\", \"Poland\"]}\ncities[\"UK\"].append(\"London\")\ncities[\"Poland\"].append(\"Poznan\")\nprint(cities) # {'UK': ['London'], 'Poland': ['Poznan']}\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as the edit will change the behavior of\nthe program by using a distinct object for every value in the dictionary,\nrather than a shared mutable instance. In some cases, programs may rely on\nthe previous behavior.\n\n## References\n- [Python documentation: `dict.fromkeys`](https://docs.python.org/3/library/stdtypes.html#dict.fromkeys)\n",
|
|
898
|
+
"ruff/RUF026": "## What it does\nChecks for incorrect usages of `default_factory` as a keyword argument when\ninitializing a `defaultdict`.\n\n## Why is this bad?\nThe `defaultdict` constructor accepts a callable as its first argument.\nFor example, it's common to initialize a `defaultdict` with `int` or `list`\nvia `defaultdict(int)` or `defaultdict(list)`, to create a dictionary that\nreturns `0` or `[]` respectively when a key is missing.\n\nThe default factory _must_ be provided as a positional argument, as all\nkeyword arguments to `defaultdict` are interpreted as initial entries in\nthe dictionary. For example, `defaultdict(foo=1, bar=2)` will create a\ndictionary with `{\"foo\": 1, \"bar\": 2}` as its initial entries.\n\nAs such, `defaultdict(default_factory=list)` will create a dictionary with\n`{\"default_factory\": list}` as its initial entry, instead of a dictionary\nthat returns `[]` when a key is missing. Specifying a `default_factory`\nkeyword argument is almost always a mistake, and one that type checkers\ncan't reliably detect.\n\n## Fix safety\nThis rule's fix is marked as unsafe, as converting `default_factory` from a\nkeyword to a positional argument will change the behavior of the code, even\nif the keyword argument was used erroneously.\n\n## Example\n```python\ndefaultdict(default_factory=int)\ndefaultdict(default_factory=list)\n```\n\nUse instead:\n```python\ndefaultdict(int)\ndefaultdict(list)\n```\n",
|
|
899
|
+
"ruff/RUF027": "## What it does\nSearches for strings that look like they were meant to be f-strings, but are missing an `f` prefix.\n\n## Why is this bad?\nExpressions inside curly braces are only evaluated if the string has an `f` prefix.\n\n## Details\n\nThere are many possible string literals which are not meant to be f-strings\ndespite containing f-string-like syntax. As such, this lint ignores all strings\nwhere one of the following conditions applies:\n\n1. The string is a standalone expression. For example, the rule ignores all docstrings.\n2. The string is part of a function call with argument names that match at least one variable\n (for example: `format(\"Message: {value}\", value=\"Hello World\")`)\n3. The string (or a parent expression of the string) has a direct method call on it\n (for example: `\"{value}\".format(...)`)\n4. The string has no `{...}` expression sections, or uses invalid f-string syntax.\n5. The string references variables that are not in scope, or it doesn't capture variables at all.\n6. Any format specifiers in the potential f-string are invalid.\n7. The string is part of a function call that is known to expect a template string rather than an\n evaluated f-string: for example, a [`logging`][logging] call, a [`gettext`][gettext] call,\n or a [FastAPI path].\n\n## Example\n\n```python\nname = \"Sarah\"\nday_of_week = \"Tuesday\"\nprint(\"Hello {name}! It is {day_of_week} today!\")\n```\n\nUse instead:\n```python\nname = \"Sarah\"\nday_of_week = \"Tuesday\"\nprint(f\"Hello {name}! It is {day_of_week} today!\")\n```\n\n## Fix safety\n\nThis fix will always change the behavior of the program and, despite the precautions detailed\nabove, this may be undesired. As such the fix is always marked as unsafe.\n\n## Options\n\n- `lint.logger-objects`\n\n[logging]: https://docs.python.org/3/howto/logging-cookbook.html#using-particular-formatting-styles-throughout-your-application\n[gettext]: https://docs.python.org/3/library/gettext.html\n[FastAPI path]: https://fastapi.tiangolo.com/tutorial/path-params/\n",
|
|
900
|
+
"ruff/RUF028": "## What it does\nChecks for formatter suppression comments that are ineffective or incompatible\nwith Ruff's formatter.\n\n## Why is this bad?\nSuppression comments that do not actually prevent formatting could cause unintended changes\nwhen the formatter is run.\n\n## Example\nIn the following example, all suppression comments would cause\na rule violation.\n\n```python\ndef decorator():\n pass\n\n\n@decorator\n# fmt: off\ndef example():\n if True:\n # fmt: skip\n expression = [\n # fmt: off\n 1,\n 2,\n ]\n # yapf: disable\n # fmt: on\n # yapf: enable\n```\n\n## Fix safety\n\nThis fix is always marked as unsafe because it deletes the invalid suppression comment,\nrather than trying to move it to a valid position, which the user more likely intended.\n",
|
|
901
|
+
"ruff/RUF029": "## What it does\nChecks for functions declared `async` that do not await or otherwise use features requiring the\nfunction to be declared `async`.\n\n## Why is this bad?\nDeclaring a function `async` when it's not is usually a mistake, and will artificially limit the\ncontexts where that function may be called. In some cases, labeling a function `async` is\nsemantically meaningful. For example, an async test or callback may need to run in an async\nexecution context, even if it only uses a `ContextVar`.\n\nIf the async context is intentional, add an actual await expression, such as\n`await asyncio.sleep(0)`, or disable this rule for the function.\n\n## Example\n```python\nasync def foo():\n bar()\n```\n\nUse instead:\n```python\ndef foo():\n bar()\n```\n",
|
|
902
|
+
"ruff/RUF030": "## What it does\nChecks for uses of `assert expression, print(message)`.\n\n## Why is this bad?\nIf an `assert x, y` assertion fails, the Python interpreter raises an\n`AssertionError`, and the evaluated value of `y` is used as the contents of\nthat assertion error. The `print` function always returns `None`, however,\nso the evaluated value of a call to `print` will always be `None`.\n\nUsing a `print` call in this context will therefore output the message to\n`stdout`, before raising an empty `AssertionError(None)`. Instead, remove\nthe `print` and pass the message directly as the second expression,\nallowing `stderr` to capture the message in a well-formatted context.\n\n## Example\n```python\nassert False, print(\"This is a message\")\n```\n\nUse instead:\n```python\nassert False, \"This is a message\"\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as changing the second expression\nwill result in a different `AssertionError` message being raised, as well as\na change in `stdout` output.\n\n## References\n- [Python documentation: `assert`](https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement)\n",
|
|
903
|
+
"ruff/RUF031": "## What it does\nChecks for consistent style regarding whether nonempty tuples in subscripts\nare parenthesized.\n\nThe exact nature of this violation depends on the setting\n[`lint.ruff.parenthesize-tuple-in-subscript`]. By default, the use of\nparentheses is considered a violation.\n\nThis rule is not applied inside \"typing contexts\" (type annotations,\ntype aliases and subscripted class bases), as these have their own specific\nconventions around them.\n\n## Why is this bad?\nIt is good to be consistent and, depending on the codebase, one or the other\nconvention may be preferred.\n\n## Example\n\n```python\ndirections = {(0, 1): \"North\", (1, 0): \"East\", (0, -1): \"South\", (-1, 0): \"West\"}\ndirections[(0, 1)]\n```\n\nUse instead (with default setting):\n\n```python\ndirections = {(0, 1): \"North\", (1, 0): \"East\", (0, -1): \"South\", (-1, 0): \"West\"}\ndirections[0, 1]\n```\n\n## Options\n- `lint.ruff.parenthesize-tuple-in-subscript`\n",
|
|
904
|
+
"ruff/RUF032": "## What it does\nChecks for `Decimal` calls passing a float literal.\n\n## Why is this bad?\nFloat literals have limited precision that can lead to unexpected results.\nThe `Decimal` class is designed to handle numbers with fixed-point precision,\nso a string literal should be used instead.\n\n## Example\n\n```python\nnum = Decimal(1.2345)\n```\n\nUse instead:\n```python\nnum = Decimal(\"1.2345\")\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe because it changes the underlying value\nof the `Decimal` instance that is constructed. This can lead to unexpected\nbehavior if your program relies on the previous value (whether deliberately or not).\n",
|
|
905
|
+
"ruff/RUF033": "## What it does\nChecks for `__post_init__` dataclass methods with parameter defaults.\n\n## Why is this bad?\nAdding a default value to a parameter in a `__post_init__` method has no\nimpact on whether the parameter will have a default value in the dataclass's\ngenerated `__init__` method. To create an init-only dataclass parameter with\na default value, you should use an `InitVar` field in the dataclass's class\nbody and give that `InitVar` field a default value.\n\nAs the [documentation] states:\n\n> Init-only fields are added as parameters to the generated `__init__()`\n> method, and are passed to the optional `__post_init__()` method. They are\n> not otherwise used by dataclasses.\n\n## Example\n```python\nfrom dataclasses import InitVar, dataclass\n\n\n@dataclass\nclass Foo:\n bar: InitVar[int] = 0\n\n def __post_init__(self, bar: int = 1, baz: int = 2) -> None:\n print(bar, baz)\n\n\nfoo = Foo() # Prints '0 2'.\n```\n\nUse instead:\n```python\nfrom dataclasses import InitVar, dataclass\n\n\n@dataclass\nclass Foo:\n bar: InitVar[int] = 1\n baz: InitVar[int] = 2\n\n def __post_init__(self, bar: int, baz: int) -> None:\n print(bar, baz)\n\n\nfoo = Foo() # Prints '1 2'.\n```\n\n## Fix safety\n\nThis fix is always marked as unsafe because, although switching to `InitVar` is usually correct,\nit is incorrect when the parameter is not intended to be part of the public API or when the value\nis meant to be shared across all instances.\n\n## References\n- [Python documentation: Post-init processing](https://docs.python.org/3/library/dataclasses.html#post-init-processing)\n- [Python documentation: Init-only variables](https://docs.python.org/3/library/dataclasses.html#init-only-variables)\n\n[documentation]: https://docs.python.org/3/library/dataclasses.html#init-only-variables\n",
|
|
906
|
+
"ruff/RUF034": "## What it does\nChecks for useless `if`-`else` conditions with identical arms.\n\n## Why is this bad?\nUseless `if`-`else` conditions add unnecessary complexity to the code without\nproviding any logical benefit. Assigning the value directly is clearer.\n\n## Example\n```python\nfoo = x if y else x\n```\n\nUse instead:\n```python\nfoo = x\n```\n",
|
|
907
|
+
"ruff/RUF035": "## Removed\nThis rule was implemented in `bandit` and has been remapped to\n[S704](unsafe-markup-use.md)\n\n## What it does\nChecks for non-literal strings being passed to [`markupsafe.Markup`][markupsafe-markup].\n\n## Why is this bad?\n[`markupsafe.Markup`][markupsafe-markup] does not perform any escaping,\nso passing dynamic content, like f-strings, variables or interpolated strings\nwill potentially lead to XSS vulnerabilities.\n\nInstead you should interpolate the `Markup` object.\n\nUsing [`lint.flake8-bandit.extend-markup-names`] additional objects can be\ntreated like `Markup`.\n\nThis rule was originally inspired by [flake8-markupsafe] but doesn't carve\nout any exceptions for i18n related calls by default.\n\nYou can use [`lint.flake8-bandit.allowed-markup-calls`] to specify exceptions.\n\n## Example\nGiven:\n```python\nfrom markupsafe import Markup\n\ncontent = \"<script>alert('Hello, world!')</script>\"\nhtml = Markup(f\"<b>{content}</b>\") # XSS\n```\n\nUse instead:\n```python\nfrom markupsafe import Markup\n\ncontent = \"<script>alert('Hello, world!')</script>\"\nhtml = Markup(\"<b>{}</b>\").format(content) # Safe\n```\n\nGiven:\n```python\nfrom markupsafe import Markup\n\nlines = [\n Markup(\"<b>heading</b>\"),\n \"<script>alert('XSS attempt')</script>\",\n]\nhtml = Markup(\"<br>\".join(lines)) # XSS\n```\n\nUse instead:\n```python\nfrom markupsafe import Markup\n\nlines = [\n Markup(\"<b>heading</b>\"),\n \"<script>alert('XSS attempt')</script>\",\n]\nhtml = Markup(\"<br>\").join(lines) # Safe\n```\n## Options\n- `lint.flake8-bandit.extend-markup-names`\n- `lint.flake8-bandit.allowed-markup-calls`\n\n## References\n- [MarkupSafe on PyPI](https://pypi.org/project/MarkupSafe/)\n- [`markupsafe.Markup` API documentation](https://markupsafe.palletsprojects.com/en/stable/escaping/#markupsafe.Markup)\n\n[markupsafe-markup]: https://markupsafe.palletsprojects.com/en/stable/escaping/#markupsafe.Markup\n[flake8-markupsafe]: https://github.com/vmagamedov/flake8-markupsafe\n",
|
|
908
|
+
"ruff/RUF036": "## What it does\nChecks for type annotations where `None` is not at the end of a union.\n\n## Why is this bad?\nType annotation unions are commutative, meaning that the order of the elements\ndoes not matter. The `None` literal represents the absence of a value. For\nreadability, it's preferred to write the more informative type expressions first.\n\n## Example\n```python\ndef func(arg: None | int): ...\n```\n\nUse instead:\n```python\ndef func(arg: int | None): ...\n```\n\n## References\n- [Python documentation: Union type](https://docs.python.org/3/library/stdtypes.html#types-union)\n- [Python documentation: `typing.Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)\n- [Python documentation: `None`](https://docs.python.org/3/library/constants.html#None)\n",
|
|
909
|
+
"ruff/RUF037": "## What it does\nChecks for use of `collections.deque` with an empty iterable as the first argument.\n\n## Why is this bad?\nIt's unnecessary to use an empty literal as a deque's iterable, since this is already the default behavior.\n\n## Example\n\n```python\nfrom collections import deque\n\nqueue = deque(set())\nqueue = deque([], 10)\n```\n\nUse instead:\n\n```python\nfrom collections import deque\n\nqueue = deque()\nqueue = deque(maxlen=10)\n```\n\n## Fix safety\n\nThe fix is marked as unsafe whenever it would delete comments present in the `deque` call or if\nthere are unrecognized arguments other than `iterable` and `maxlen`.\n\n## Fix availability\n\nThis rule's fix is unavailable if any starred arguments are present after the initial iterable.\n\n## References\n- [Python documentation: `collections.deque`](https://docs.python.org/3/library/collections.html#collections.deque)\n",
|
|
910
|
+
"ruff/RUF038": "## What it does\nChecks for `Literal[True, False]` type annotations.\n\n## Why is this bad?\n`Literal[True, False]` can be replaced with `bool` in type annotations,\nwhich has the same semantic meaning but is more concise and readable.\n\n`bool` type has exactly two constant instances: `True` and `False`. Static\ntype checkers such as [mypy] treat `Literal[True, False]` as equivalent to\n`bool` in a type annotation.\n\n## Example\n```python\nfrom typing import Literal\n\nx: Literal[True, False]\ny: Literal[True, False, \"hello\", \"world\"]\n```\n\nUse instead:\n```python\nfrom typing import Literal\n\nx: bool\ny: Literal[\"hello\", \"world\"] | bool\n```\n\n## Fix safety\nThe fix for this rule is marked as unsafe, as it may change the semantics of the code.\nSpecifically:\n\n- Type checkers may not treat `bool` as equivalent when overloading boolean arguments\n with `Literal[True]` and `Literal[False]` (see, e.g., [#14764] and [#5421]).\n- `bool` is not strictly equivalent to `Literal[True, False]`, as `bool` is\n a subclass of `int`, and this rule may not apply if the type annotations are used\n in a numeric context.\n\nFurther, the `Literal` slice may contain trailing-line comments which the fix would remove.\n\n## References\n- [Typing documentation: Legal parameters for `Literal` at type check time](https://typing.python.org/en/latest/spec/literal.html#legal-parameters-for-literal-at-type-check-time)\n- [Python documentation: Boolean type - `bool`](https://docs.python.org/3/library/stdtypes.html#boolean-type-bool)\n\n[mypy]: https://github.com/python/mypy/blob/master/mypy/typeops.py#L985\n[#14764]: https://github.com/python/mypy/issues/14764\n[#5421]: https://github.com/microsoft/pyright/issues/5421\n",
|
|
911
|
+
"ruff/RUF039": "## What it does\nReports the following `re` and `regex` calls when\ntheir first arguments are not raw strings:\n\n- For `regex` and `re`: `compile`, `findall`, `finditer`,\n `fullmatch`, `match`, `prefixmatch`, `search`, `split`, `sub`, `subn`.\n- `regex`-specific: `splititer`, `subf`, `subfn`, `template`.\n\n## Why is this bad?\nRegular expressions should be written\nusing raw strings to avoid double escaping.\n\n## Fix safety\nThe fix is unsafe if the string/bytes literal contains an escape sequence because the fix alters\nthe runtime value of the literal while retaining the regex semantics.\n\nFor example\n```python\n# Literal is `1\\n2`.\nre.compile(\"1\\n2\")\n\n# Literal is `1\\\\n2`, but the regex library will interpret `\\\\n` and will still match a newline\n# character as before.\nre.compile(r\"1\\n2\")\n```\n\n## Fix availability\n A fix is not available if either\n * the argument is a string with a (no-op) `u` prefix (e.g., `u\"foo\"`) as the prefix is\n incompatible with the raw prefix `r`\n * the argument is a string or bytes literal with an escape sequence that has a different\n meaning in the context of a regular expression such as `\\b`, which is word boundary or\n backspace in a regex, depending on the context, but always a backspace in string and bytes\n literals.\n\n## Example\n\n```python\nre.compile(\"foo\\\\bar\")\n```\n\nUse instead:\n\n```python\nre.compile(r\"foo\\bar\")\n```\n",
|
|
912
|
+
"ruff/RUF040": "## What it does\nChecks for invalid use of literals in assert message arguments.\n\n## Why is this bad?\nAn assert message which is a non-string literal was likely intended\nto be used in a comparison assertion, rather than as a message.\n\n## Example\n```python\nfruits = [\"apples\", \"plums\", \"pears\"]\nfruits.filter(lambda fruit: fruit.startswith(\"p\"))\nassert len(fruits), 2 # True unless the list is empty\n```\n\nUse instead:\n```python\nfruits = [\"apples\", \"plums\", \"pears\"]\nfruits.filter(lambda fruit: fruit.startswith(\"p\"))\nassert len(fruits) == 2\n```\n",
|
|
913
|
+
"ruff/RUF041": "## What it does\nChecks for unnecessary nested `Literal`.\n\n## Why is this bad?\nPrefer using a single `Literal`, which is equivalent and more concise.\n\nParameterization of literals by other literals is supported as an ergonomic\nfeature as proposed in [PEP 586], to enable patterns such as:\n```python\nReadOnlyMode = Literal[\"r\", \"r+\"]\nWriteAndTruncateMode = Literal[\"w\", \"w+\", \"wt\", \"w+t\"]\nWriteNoTruncateMode = Literal[\"r+\", \"r+t\"]\nAppendMode = Literal[\"a\", \"a+\", \"at\", \"a+t\"]\n\nAllModes = Literal[ReadOnlyMode, WriteAndTruncateMode,\n WriteNoTruncateMode, AppendMode]\n```\n\nAs a consequence, type checkers also support nesting of literals\nwhich is less readable than a flat `Literal`:\n```python\nAllModes = Literal[Literal[\"r\", \"r+\"], Literal[\"w\", \"w+\", \"wt\", \"w+t\"],\n Literal[\"r+\", \"r+t\"], Literal[\"a\", \"a+\", \"at\", \"a+t\"]]\n```\n\n## Example\n```python\nAllModes = Literal[\n Literal[\"r\", \"r+\"],\n Literal[\"w\", \"w+\", \"wt\", \"w+t\"],\n Literal[\"r+\", \"r+t\"],\n Literal[\"a\", \"a+\", \"at\", \"a+t\"],\n]\n```\n\nUse instead:\n```python\nAllModes = Literal[\n \"r\", \"r+\", \"w\", \"w+\", \"wt\", \"w+t\", \"r+\", \"r+t\", \"a\", \"a+\", \"at\", \"a+t\"\n]\n```\n\nor assign the literal to a variable as in the first example.\n\n## Fix safety\nThe fix for this rule is marked as unsafe when the `Literal` slice is split\nacross multiple lines and some of the lines have trailing comments.\n\n## References\n- [Typing documentation: Legal parameters for `Literal` at type check time](https://typing.python.org/en/latest/spec/literal.html#legal-parameters-for-literal-at-type-check-time)\n\n[PEP 586]: https://peps.python.org/pep-0586/\n",
|
|
914
|
+
"ruff/RUF043": "## What it does\nChecks for non-raw literal string arguments passed to the `match` parameter\nof `pytest.raises()` where the string contains at least one unescaped\nregex metacharacter.\n\n## Why is this bad?\nThe `match` argument is implicitly converted to a regex under the hood.\nIt should be made explicit whether the string is meant to be a regex or a \"plain\" pattern\nby prefixing the string with the `r` suffix, escaping the metacharacter(s)\nin the string using backslashes, or wrapping the entire string in a call to\n`re.escape()`.\n\n## Example\n\n```python\nimport pytest\n\n\nwith pytest.raises(Exception, match=\"A full sentence.\"):\n do_thing_that_raises()\n```\n\nIf the pattern is intended to be a regular expression, use a raw string to signal this\nintention:\n\n```python\nimport pytest\n\n\nwith pytest.raises(Exception, match=r\"A full sentence.\"):\n do_thing_that_raises()\n```\n\nAlternatively, escape any regex metacharacters with `re.escape`:\n\n```python\nimport pytest\nimport re\n\n\nwith pytest.raises(Exception, match=re.escape(\"A full sentence.\")):\n do_thing_that_raises()\n```\n\nor directly with backslashes:\n\n```python\nimport pytest\nimport re\n\n\nwith pytest.raises(Exception, \"A full sentence\\\\.\"):\n do_thing_that_raises()\n```\n\n## References\n- [Python documentation: `re.escape`](https://docs.python.org/3/library/re.html#re.escape)\n- [`pytest` documentation: `pytest.raises`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-raises)\n",
|
|
915
|
+
"ruff/RUF045": "## What it does\nChecks for implicit class variables in dataclasses.\n\nVariables matching the [`lint.dummy-variable-rgx`] are excluded\nfrom this rule.\n\n## Why is this bad?\nClass variables are shared between all instances of that class.\nIn dataclasses, fields with no annotations at all\nare implicitly considered class variables, and a `TypeError` is\nraised if a user attempts to initialize an instance of the class\nwith this field.\n\n\n```python\n@dataclass\nclass C:\n a = 1\n b: str = \"\"\n\nC(a = 42) # TypeError: C.__init__() got an unexpected keyword argument 'a'\n```\n\n## Example\n\n```python\n@dataclass\nclass C:\n a = 1\n```\n\nUse instead:\n\n```python\nfrom typing import ClassVar\n\n\n@dataclass\nclass C:\n a: ClassVar[int] = 1\n```\n\n## Options\n- [`lint.dummy-variable-rgx`]\n",
|
|
916
|
+
"ruff/RUF046": "## What it does\nChecks for `int` conversions of values that are already integers.\n\n## Why is this bad?\nSuch a conversion is unnecessary.\n\n## Known problems\nThis rule may produce false positives for `round`, `math.ceil`, `math.floor`,\nand `math.trunc` calls when values override the `__round__`, `__ceil__`, `__floor__`,\nor `__trunc__` operators such that they don't return an integer.\n\n## Example\n\n```python\nint(len([]))\nint(round(foo, None))\n```\n\nUse instead:\n\n```python\nlen([])\nround(foo)\n```\n\n## Fix safety\nThe fix for `round`, `math.ceil`, `math.floor`, and `math.truncate` is unsafe\nbecause removing the `int` conversion can change the semantics for values\noverriding the `__round__`, `__ceil__`, `__floor__`, or `__trunc__` dunder methods\nsuch that they don't return an integer.\n",
|
|
917
|
+
"ruff/RUF047": "## What it does\nChecks for `else` clauses that only contains `pass` and `...` statements.\n\n## Why is this bad?\nSuch an else clause does nothing and can be removed.\n\n## Example\n```python\nif foo:\n bar()\nelse:\n pass\n```\n\nUse instead:\n```python\nif foo:\n bar()\n```\n",
|
|
918
|
+
"ruff/RUF048": "## What it does\nChecks for calls of the form `map(int, __version__.split(\".\"))`.\n\n## Why is this bad?\n`__version__` does not always contain integral-like elements.\n\n```python\nimport matplotlib # `__version__ == \"3.9.1.post-1\"` in our environment\n\n# ValueError: invalid literal for int() with base 10: 'post1'\ntuple(map(int, matplotlib.__version__.split(\".\")))\n```\n\nSee also [*Version specifiers* | Packaging spec][version-specifier].\n\n## Example\n```python\ntuple(map(int, matplotlib.__version__.split(\".\")))\n```\n\nUse instead:\n```python\nimport packaging.version as version\n\nversion.parse(matplotlib.__version__)\n```\n\n[version-specifier]: https://packaging.python.org/en/latest/specifications/version-specifiers/#version-specifiers\n",
|
|
919
|
+
"ruff/RUF049": "## What it does\nChecks for enum classes which are also decorated with `@dataclass`.\n\n## Why is this bad?\nDecorating an enum with `@dataclass()` does not cause any errors at runtime,\nbut may cause erroneous results:\n\n```python\n@dataclass\nclass E(Enum):\n A = 1\n B = 2\n\nprint(E.A == E.B) # True\n```\n\n## Example\n\n```python\nfrom dataclasses import dataclass\nfrom enum import Enum\n\n\n@dataclass\nclass E(Enum): ...\n```\n\nUse instead:\n\n```python\nfrom enum import Enum\n\n\nclass E(Enum): ...\n```\n\n## References\n- [Python documentation: Enum HOWTO § Dataclass support](https://docs.python.org/3/howto/enum.html#dataclass-support)\n",
|
|
920
|
+
"ruff/RUF050": "## What it does\nChecks for `if` statements (without `elif` or `else` branches) where the\nbody contains only `pass` or `...`\n\n## Why is this bad?\nAn `if` statement with an empty body either does nothing (when the\ncondition is side-effect-free) or could be replaced with just the\ncondition expression (when it has side effects). This pattern commonly\narises when auto-fixers remove unused imports from conditional blocks\n(e.g., version-dependent imports), leaving behind an empty skeleton.\n\n## Example\n```python\nimport sys\n\nif sys.version_info >= (3, 11):\n pass\n```\n\nUse instead:\n```python\nimport sys\n```\n\n## Fix safety\nWhen the condition is side-effect-free, the fix removes the entire `if`\nstatement.\n\nWhen the condition has side effects (e.g., a function call), the fix\nreplaces the `if` statement with just the condition as an expression\nstatement, preserving the side effects.\n\nNote: conditions consisting solely of a name expression (like\n`if x: pass`) are treated as side-effect-free, even though `if x`\nimplicitly calls `x.__bool__()` (or `x.__len__()`), which could have\nside effects if overridden. In practice this is very rare, but if you\nrely on this behavior, suppress the diagnostic with `# noqa: RUF050`.\n\n## Related rules\n- [`needless-else (RUF047)`]: Detects empty `else` clauses. For `if`/`else`\n statements where all branches are empty, `RUF047` first removes the empty\n `else`, and then this rule catches the remaining empty `if`.\n- [`empty-type-checking-block (TC005)`]: Detects empty `if TYPE_CHECKING`\n blocks specifically.\n",
|
|
921
|
+
"ruff/RUF051": "## What it does\nChecks for `if key in dictionary: del dictionary[key]`.\n\n## Why is this bad?\nTo remove a key-value pair from a dictionary, it's more concise to use `.pop(..., None)`.\n\n## Example\n\n```python\ndictionary = {}\nif key in dictionary:\n del dictionary[key]\n```\n\nUse instead:\n\n```python\ndictionary = {}\ndictionary.pop(key, None)\n```\n\n## Fix safety\nThis rule's fix is marked as safe, unless the if statement contains comments.\n",
|
|
922
|
+
"ruff/RUF052": "## What it does\nChecks for \"dummy variables\" (variables that are named as if to indicate they are unused)\nthat are in fact used.\n\nBy default, \"dummy variables\" are any variables with names that start with leading\nunderscores. However, this is customisable using the [`lint.dummy-variable-rgx`] setting).\n\n## Why is this bad?\nMarking a variable with a leading underscore conveys that it is intentionally unused within the function or method.\nWhen these variables are later referenced in the code, it causes confusion and potential misunderstandings about\nthe code's intention. If a variable marked as \"unused\" is subsequently used, it suggests that either the variable\ncould be given a clearer name, or that the code is accidentally making use of the wrong variable.\n\nSometimes leading underscores are used to avoid variables shadowing other variables, Python builtins, or Python\nkeywords. However, [PEP 8] recommends to use trailing underscores for this rather than leading underscores.\n\nDunder variables are ignored by this rule, as are variables named `_`.\nOnly local variables in function scopes are flagged by the rule.\n\n## Example\n```python\ndef function():\n _variable = 3\n # important: avoid shadowing the builtin `id()` function!\n _id = 4\n return _variable + _id\n```\n\nUse instead:\n```python\ndef function():\n variable = 3\n # important: avoid shadowing the builtin `id()` function!\n id_ = 4\n return variable + id_\n```\n\n## Fix availability\nThe rule's fix is only available for variables that start with leading underscores.\nIt will also only be available if the \"obvious\" new name for the variable\nwould not shadow any other known variables already accessible from the scope\nin which the variable is defined.\n\n## Fix safety\nThis rule's fix is marked as unsafe.\n\nFor this rule's fix, Ruff renames the variable and fixes up all known references to\nit so they point to the renamed variable. However, some renamings also require other\nchanges such as different arguments to constructor calls or alterations to comments.\nRuff is aware of some of these cases: `_T = TypeVar(\"_T\")` will be fixed to\n`T = TypeVar(\"T\")` if the `_T` binding is flagged by this rule. However, in general,\ncases like these are hard to detect and hard to automatically fix.\n\n## Options\n- [`lint.dummy-variable-rgx`]\n\n[PEP 8]: https://peps.python.org/pep-0008/\n",
|
|
923
|
+
"ruff/RUF053": "## What it does\nChecks for classes that have [PEP 695] [type parameter lists]\nwhile also inheriting from `typing.Generic` or `typing_extensions.Generic`.\n\n## Why is this bad?\nSuch classes cause errors at runtime:\n\n```python\nfrom typing import Generic, TypeVar\n\nU = TypeVar(\"U\")\n\n# TypeError: Cannot inherit from Generic[...] multiple times.\nclass C[T](Generic[U]): ...\n```\n\n## Example\n\n```python\nfrom typing import Generic, ParamSpec, TypeVar, TypeVarTuple\n\nU = TypeVar(\"U\")\nP = ParamSpec(\"P\")\nTs = TypeVarTuple(\"Ts\")\n\n\nclass C[T](Generic[U, P, *Ts]): ...\n```\n\nUse instead:\n\n```python\nclass C[T, U, **P, *Ts]: ...\n```\n\n## Fix safety\nAs the fix changes runtime behaviour, it is always marked as unsafe.\nAdditionally, comments within the fix range will not be preserved.\n\n## References\n- [Python documentation: User-defined generic types](https://docs.python.org/3/library/typing.html#user-defined-generic-types)\n- [Python documentation: type parameter lists](https://docs.python.org/3/reference/compound_stmts.html#type-params)\n- [PEP 695 - Type Parameter Syntax](https://peps.python.org/pep-0695/)\n\n[PEP 695]: https://peps.python.org/pep-0695/\n[type parameter lists]: https://docs.python.org/3/reference/compound_stmts.html#type-params\n",
|
|
924
|
+
"ruff/RUF054": "## What it does\nChecks for form feed characters preceded by either a space or a tab.\n\n## Why is this bad?\n[The language reference][lexical-analysis-indentation] states:\n\n> A formfeed character may be present at the start of the line;\n> it will be ignored for the indentation calculations above.\n> Formfeed characters occurring elsewhere in the leading whitespace\n> have an undefined effect (for instance, they may reset the space count to zero).\n\n## Example\n\n```python\nif foo():\\n \\fbar()\n```\n\nUse instead:\n\n```python\nif foo():\\n bar()\n```\n\n[lexical-analysis-indentation]: https://docs.python.org/3/reference/lexical_analysis.html#indentation\n",
|
|
925
|
+
"ruff/RUF055": "## What it does\n\nChecks for uses of the `re` module that can be replaced with builtin `str` methods.\n\n## Why is this bad?\n\nPerforming checks on strings directly can make the code simpler, may require\nless escaping, and will often be faster.\n\n## Example\n\n```python\nre.sub(\"abc\", \"\", s)\n```\n\nUse instead:\n\n```python\ns.replace(\"abc\", \"\")\n```\n\n## Details\n\nThe rule reports the following calls when the first argument to the call is\na plain string literal, and no additional flags are passed:\n\n- `re.sub`\n- `re.match`\n- `re.prefixmatch`\n- `re.search`\n- `re.fullmatch`\n- `re.split`\n\nFor `re.sub`, the `repl` (replacement) argument must also be a string literal,\nnot a function. For `re.match`, `re.prefixmatch`, `re.search`, and `re.fullmatch`,\nthe return value must also be used only for its truth value.\n\n## Fix safety\n\nThis rule's fix is marked as unsafe if the affected expression contains comments. Otherwise,\nthe fix can be applied safely.\n\n## References\n- [Python Regular Expression HOWTO: Common Problems - Use String Methods](https://docs.python.org/3/howto/regex.html#use-string-methods)\n",
|
|
926
|
+
"ruff/RUF056": "## What it does\nChecks for `dict.get(key, falsy_value)` calls in boolean test positions.\n\n## Why is this bad?\nThe default fallback `None` is already falsy.\n\n## Example\n\n```python\nif dict.get(key, False):\n ...\n```\n\nUse instead:\n\n```python\nif dict.get(key):\n ...\n```\n\n## Fix safety\n\nThis rule's fix is marked as safe, unless the `dict.get()` call contains comments between\narguments that will be deleted.\n\n## Fix availability\n\nThis rule's fix is unavailable in cases where invalid arguments are provided to `dict.get`. As\nshown in the [documentation], `dict.get` takes two positional-only arguments, so invalid cases\nare identified by the presence of more than two arguments or any keyword arguments.\n\n[documentation]: https://docs.python.org/3/library/stdtypes.html#dict.get\n",
|
|
927
|
+
"ruff/RUF057": "## What it does\nChecks for `round()` calls that have no effect on the input.\n\n## Why is this bad?\nRounding a value that's already an integer is unnecessary.\nIt's clearer to use the value directly.\n\n## Example\n\n```python\na = round(1, 0)\n```\n\nUse instead:\n\n```python\na = 1\n```\n\n## Fix safety\n\nThe fix is marked unsafe if it is not possible to guarantee that the first argument of\n`round()` is of type `int`, or if the fix deletes comments.\n",
|
|
928
|
+
"ruff/RUF058": "## What it does\nChecks for `itertools.starmap` calls where the second argument is a `zip` call.\n\n## Why is this bad?\n`zip`-ping iterables only to unpack them later from within `starmap` is unnecessary.\nFor such cases, `map()` should be used instead.\n\n## Example\n\n```python\nfrom itertools import starmap\n\n\nstarmap(func, zip(a, b))\nstarmap(func, zip(a, b, strict=True))\n```\n\nUse instead:\n\n```python\nmap(func, a, b)\nmap(func, a, b, strict=True) # 3.14+\n```\n\n## Fix safety\n\nThis rule's fix is marked as unsafe if the `starmap` or `zip` expressions contain comments that\nwould be deleted by applying the fix. Otherwise, the fix can be applied safely.\n\n## Fix availability\n\nThis rule will emit a diagnostic but not suggest a fix if `map` has been shadowed from its\nbuiltin binding.\n",
|
|
929
|
+
"ruff/RUF059": "## What it does\nChecks for the presence of unused variables in unpacked assignments.\n\n## Why is this bad?\nA variable that is defined but never used can confuse readers.\n\nIf a variable is intentionally defined-but-not-used, it should be\nprefixed with an underscore, or some other value that adheres to the\n[`lint.dummy-variable-rgx`] pattern.\n\n## Example\n\n```python\ndef get_pair():\n return 1, 2\n\n\ndef foo():\n x, y = get_pair()\n return x\n```\n\nUse instead:\n\n```python\ndef foo():\n x, _ = get_pair()\n return x\n```\n\n## See also\n\nThis rule applies only to unpacked assignments. For regular assignments, see\n[`unused-variable`][F841].\n\n## Options\n- `lint.dummy-variable-rgx`\n\n[F841]: https://docs.astral.sh/ruff/rules/unused-variable/\n",
|
|
930
|
+
"ruff/RUF060": "## What it does\nChecks for membership tests on empty collections (such as `list`, `tuple`, `set`, or `dict`).\n\n## Why is this bad?\nIf the collection is always empty, the check is unnecessary and can be removed.\n\n## Example\n\n```python\nif 1 not in set():\n print(\"got it!\")\n```\n\nUse instead:\n\n```python\nprint(\"got it!\")\n```\n",
|
|
931
|
+
"ruff/RUF061": "## What it does\nChecks for non-context-manager use of `pytest.raises`, `pytest.warns`, and `pytest.deprecated_call`.\n\n## Why is this bad?\nThe context-manager form is more readable, easier to extend, and supports additional keyword\narguments.\n\n## Example\n```python\nimport pytest\n\n\nexcinfo = pytest.raises(ValueError, int, \"hello\")\npytest.warns(UserWarning, my_function, arg)\npytest.deprecated_call(my_deprecated_function, arg1, arg2)\n```\n\nUse instead:\n```python\nimport pytest\n\n\nwith pytest.raises(ValueError) as excinfo:\n int(\"hello\")\nwith pytest.warns(UserWarning):\n my_function(arg)\nwith pytest.deprecated_call():\n my_deprecated_function(arg1, arg2)\n```\n\n## References\n- [`pytest` documentation: `pytest.raises`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-raises)\n- [`pytest` documentation: `pytest.warns`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-warns)\n- [`pytest` documentation: `pytest.deprecated_call`](https://docs.pytest.org/en/latest/reference/reference.html#pytest-deprecated-call)\n",
|
|
932
|
+
"ruff/RUF063": "## What it does\nChecks for uses of `foo.__dict__.get(\"__annotations__\")` or\n`foo.__dict__[\"__annotations__\"]` on Python 3.10+ and Python < 3.10 when\n[`lint.typing-extensions`] is enabled.\n\n## Why is this bad?\nStarting with Python 3.14, directly accessing `__annotations__` via\n`foo.__dict__.get(\"__annotations__\")` or `foo.__dict__[\"__annotations__\"]`\nwill only return annotations if the class is defined under\n`from __future__ import annotations`.\n\nTherefore, it is better to use dedicated library functions like\n`annotationlib.get_annotations` (Python 3.14+), `inspect.get_annotations`\n(Python 3.10+), or `typing_extensions.get_annotations` (for Python < 3.10 if\n[typing-extensions](https://pypi.org/project/typing-extensions/) is\navailable).\n\nThe benefits of using these functions include:\n1. **Avoiding Undocumented Internals:** They provide a stable, public API,\n unlike direct `__dict__` access which relies on implementation details.\n2. **Forward-Compatibility:** They are designed to handle changes in\n Python's annotation system across versions, ensuring your code remains\n robust (e.g., correctly handling the Python 3.14 behavior mentioned\n above).\n\nSee [Python Annotations Best Practices](https://docs.python.org/3.14/howto/annotations.html)\nfor alternatives.\n\n## Example\n\n```python\nfoo.__dict__.get(\"__annotations__\", {})\n# or\nfoo.__dict__[\"__annotations__\"]\n```\n\nOn Python 3.14+, use instead:\n```python\nimport annotationlib\n\nannotationlib.get_annotations(foo)\n```\n\nOn Python 3.10+, use instead:\n```python\nimport inspect\n\ninspect.get_annotations(foo)\n```\n\nOn Python < 3.10 with [typing-extensions](https://pypi.org/project/typing-extensions/)\ninstalled, use instead:\n```python\nimport typing_extensions\n\ntyping_extensions.get_annotations(foo)\n```\n\n## Fix safety\n\nNo autofix is currently provided for this rule.\n\n## Fix availability\n\nNo autofix is currently provided for this rule.\n\n## References\n- [Python Annotations Best Practices](https://docs.python.org/3.14/howto/annotations.html)\n",
|
|
933
|
+
"ruff/RUF064": "## What it does\nChecks for standard library functions which take a numeric `mode` argument\nwhere a non-octal integer literal is passed.\n\n## Why is this bad?\n\nNumeric modes are made up of one to four octal digits. Converting a non-octal\ninteger to octal may not be the mode the author intended.\n\n## Example\n\n```python\nos.chmod(\"foo\", 644)\n```\n\nUse instead:\n\n```python\nos.chmod(\"foo\", 0o644)\n```\n\n## Fix safety\n\nThere are two categories of unsafe fixes, the first of which is where it looks like\nthe author intended to use an octal literal but the `0o` prefix is missing:\n\n```python\nos.chmod(\"foo\", 400)\nos.chmod(\"foo\", 644)\n```\n\nThis class of fix changes runtime behaviour. In the first case, `400`\ncorresponds to `0o620` (`u=rw,g=w,o=`). As this mode is not deemed likely,\nit is changed to `0o400` (`u=r,go=`). Similarly, `644` corresponds to\n`0o1204` (`u=ws,g=,o=r`) and is changed to `0o644` (`u=rw,go=r`).\n\nThe second category is decimal literals which are recognised as likely valid\nbut in decimal form:\n\n```python\nos.chmod(\"foo\", 256)\nos.chmod(\"foo\", 493)\n```\n\n`256` corresponds to `0o400` (`u=r,go=`) and `493` corresponds to `0o755`\n(`u=rwx,go=rx`). Both of these fixes keep runtime behavior unchanged. If the\noriginal code really intended to use `0o256` (`u=w,g=rx,o=rw`) instead of\n`256`, this fix should not be accepted.\n\nAs a special case, zero is allowed to omit the `0o` prefix unless it has\nmultiple digits:\n\n```python\nos.chmod(\"foo\", 0) # Ok\nos.chmod(\"foo\", 0o000) # Ok\nos.chmod(\"foo\", 000) # Lint emitted and fix suggested\n```\n\nRuff will suggest a safe fix for multi-digit zeros to add the `0o` prefix.\n\n## Fix availability\n\nA fix is only available if the integer literal matches a set of common modes.\n",
|
|
934
|
+
"ruff/RUF065": "## What it does\nChecks for eager string conversion of arguments to `logging` calls.\n\n## Why is this bad?\nArguments to `logging` calls will be formatted as strings automatically, so it\nis unnecessary and less efficient to eagerly format the arguments before passing\nthem in.\n\n## Known problems\n\nThis rule detects uses of the `logging` module via a heuristic.\nSpecifically, it matches against:\n\n- Uses of the `logging` module itself (e.g., `import logging; logging.info(...)`).\n- Uses of `flask.current_app.logger` (e.g., `from flask import current_app; current_app.logger.info(...)`).\n- Objects whose name starts with `log` or ends with `logger` or `logging`,\n when used in the same file in which they are defined (e.g., `logger = logging.getLogger(); logger.info(...)`).\n- Imported objects marked as loggers via the [`lint.logger-objects`] setting, which can be\n used to enforce these rules against shared logger objects (e.g., `from module import logger; logger.info(...)`,\n when [`lint.logger-objects`] is set to `[\"module.logger\"]`).\n\n## Example\n```python\nimport logging\n\nlogging.basicConfig(format=\"%(message)s\", level=logging.INFO)\n\nuser = \"Maria\"\n\nlogging.info(\"%s - Something happened\", str(user))\n```\n\nUse instead:\n```python\nimport logging\n\nlogging.basicConfig(format=\"%(message)s\", level=logging.INFO)\n\nuser = \"Maria\"\n\nlogging.info(\"%s - Something happened\", user)\n```\n\n## Options\n- `lint.logger-objects`\n\n## References\n- [Python documentation: `logging`](https://docs.python.org/3/library/logging.html)\n- [Python documentation: Optimization](https://docs.python.org/3/howto/logging.html#optimization)\n",
|
|
935
|
+
"ruff/RUF066": "## What it does\nDetects class `@property` methods that does not have a `return` statement.\n\n## Why is this bad?\nProperty methods are expected to return a computed value, a missing return in a property usually indicates an implementation mistake.\n\n## Example\n```python\nclass User:\n @property\n def full_name(self):\n f\"{self.first_name} {self.last_name}\"\n```\n\nUse instead:\n```python\nclass User:\n @property\n def full_name(self):\n return f\"{self.first_name} {self.last_name}\"\n```\n\n## Options\n\n- `lint.pydocstyle.property-decorators`\n\n## References\n- [Python documentation: The property class](https://docs.python.org/3/library/functions.html#property)\n",
|
|
936
|
+
"ruff/RUF067": "## What it does\n\nDetects the presence of code in `__init__.py` files.\n\n## Why is this bad?\n\n`__init__.py` files are often empty or only contain simple code to modify a module's API. As\nsuch, it's easy to overlook them and their possible side effects when debugging.\n\n## Example\n\nInstead of defining `MyClass` directly in `__init__.py`:\n\n```python\n\"\"\"My module docstring.\"\"\"\n\n\nclass MyClass:\n def my_method(self): ...\n```\n\nmove the definition to another file, import it, and include it in `__all__`:\n\n```python\n\"\"\"My module docstring.\"\"\"\n\nfrom submodule import MyClass\n\n__all__ = [\"MyClass\"]\n```\n\nCode in `__init__.py` files is also run at import time and can cause surprising slowdowns. To\ndisallow any code in `__init__.py` files, you can enable the\n[`lint.ruff.strictly-empty-init-modules`] setting. In this case:\n\n```python\n\"\"\"My module docstring.\"\"\"\n\nfrom submodule import MyClass\n\n__all__ = [\"MyClass\"]\n```\n\nthe only fix is removing everything but the docstring:\n\n```python\n\"\"\"My module docstring.\"\"\"\n```\n\n## Details\n\nIn both modes, this rule allows module-level and attribute docstrings in `__init__.py` files.\n\nIn non-strict mode, this rule additionally allows several common patterns:\n\n- Imports\n- Assignments to dunder names (identifiers starting and ending with `__`, such as `__all__` or\n `__submodules__`)\n- `if TYPE_CHECKING` blocks\n- [PEP-562] module-level `__getattr__` and `__dir__` functions\n\n## Options\n\n- [`lint.ruff.strictly-empty-init-modules`]\n\n## References\n\n- [`flake8-empty-init-modules`](https://github.com/samueljsb/flake8-empty-init-modules/)\n\n[PEP-562]: https://peps.python.org/pep-0562/\n",
|
|
937
|
+
"ruff/RUF068": "## What it does\nDetects duplicate elements in `__all__` definitions.\n\n## Why is this bad?\nDuplicate elements in `__all__` serve no purpose and can indicate copy-paste errors or\nincomplete refactoring.\n\n## Example\n```python\n__all__ = [\n \"DatabaseConnection\",\n \"Product\",\n \"User\",\n \"DatabaseConnection\", # Duplicate\n]\n```\n\nUse instead:\n```python\n__all__ = [\n \"DatabaseConnection\",\n \"Product\",\n \"User\",\n]\n```\n\n## Fix Safety\nThis rule's fix is marked as unsafe if the replacement would remove comments attached to the\noriginal expression, potentially losing important context or documentation.\n\nFor example:\n```python\n__all__ = [\n \"PublicAPI\",\n # TODO: Remove this in v2.0\n \"PublicAPI\", # Deprecated alias\n]\n```\n",
|
|
938
|
+
"ruff/RUF069": "## What it does\nChecks for comparisons between floating-point values using `==` or `!=`.\n\n## Why is this bad?\nDirectly comparing floating-point numbers for exact equality or inequality\ncan lead to incorrect and non-deterministic outcomes. This is because\nfloating-point values are finite binary approximations of real numbers.\nMany decimal values, such as `0.1`, cannot be represented exactly in binary,\nleading to small rounding errors. Furthermore, the results of arithmetic\noperations are subject to rounding at each step, and the order of operations\ncan influence the final result. Consequently, two mathematically equivalent\ncomputations may yield binary floating-point values that differ by a tiny\nmargin. Relying on exact comparison treats these semantically equal values\nas different, breaking logical correctness.\n\n## How to fix\nFor general Python code, use tolerance-based comparison functions from the\nstandard library:\n\n- Use `math.isclose()` for scalar comparisons\n- Use `cmath.isclose()` for complex numbers comparisons\n- Use `unittest.assertAlmostEqual()` in tests with `unittest`\n\nNote that `math.isclose()` and `cmath.isclose()` have a default absolute tolerance of zero, so\nwhen comparing values near zero, you must explicitly specify an `abs_tol`\nparameter.\n\nMany frameworks and libraries provide their own specialized functions for\nfloating-point comparison, often with different default tolerances optimized\nfor their specific use cases:\n\n- For `NumPy` arrays: use `numpy.isclose()` or `numpy.allclose()`\n- For `PyTorch` tensors: use `torch.isclose()`\n- Check your framework's / library's documentation for equivalent functions\n\nFor scenarios requiring exact decimal arithmetic, consider using the\n`Decimal` class from the `decimal` module instead of floating-point numbers.\n\n## Example\n\n```python\nassert 0.1 + 0.2 == 0.3 # AssertionError\n\nassert complex(0.3, 0.1) == complex(0.1 + 0.2, 0.1) # AssertionError\n```\n\nUse instead:\n\n```python\nimport cmath\nimport math\n\n# Scalar comparison\nassert math.isclose(0.1 + 0.2, 0.3, abs_tol=1e-9)\n# Complex numbers comparison\nassert cmath.isclose(complex(0.3, 0.1), complex(0.1 + 0.2, 0.1), abs_tol=1e-9)\n```\n\n## Ecosystem-specific alternatives\n\n```python\nimport numpy as np\n\narr1 = np.sum(np.array([0.1, 0.2]))\n\nassert np.all(arr1 == 0.3) # AssertionError\n```\n\nUse instead:\n\n```python\nimport numpy as np\n\narr1 = np.sum(np.array([0.1, 0.2]))\n\nassert np.all(np.isclose(arr1, 0.3, rtol=1e-9, atol=1e-9))\n# or\nassert np.allclose(arr1, 0.3, rtol=1e-9, atol=1e-9)\n```\n\n## References\n- [Python documentation: Floating Point Arithmetic: Issues and Limitations](https://docs.python.org/3/tutorial/floatingpoint.html#floating-point-arithmetic-issues-and-limitations)\n- [Decimal fixed point and floating point arithmetic](https://docs.python.org/3/library/decimal.html#module-decimal)\n- [Python documentation: `math.isclose`](https://docs.python.org/3/library/math.html#math.isclose)\n- [Python documentation: `cmath.isclose`](https://docs.python.org/3/library/cmath.html#cmath.isclose)\n- [Python documentation: `unittest.assertAlmostEqual`](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertAlmostEqual)\n- [NumPy documentation: `numpy.isclose`](https://numpy.org/doc/stable/reference/generated/numpy.isclose.html#numpy-isclose)\n- [NumPy documentation: `numpy.allclose`](https://numpy.org/doc/stable/reference/generated/numpy.allclose.html#numpy-allclose)\n- [PyTorch documentation: `torch.isclose`](https://docs.pytorch.org/docs/stable/generated/torch.isclose.html#torch-isclose)\n",
|
|
939
|
+
"ruff/RUF070": "## What it does\nChecks for variable assignments that immediately precede a `yield` (or\n`yield from`) of the assigned variable, where the variable is not\nreferenced anywhere else.\n\n## Why is this bad?\nThe variable assignment is not necessary, as the value can be yielded\ndirectly.\n\n## Example\n```python\ndef gen():\n x = 1\n yield x\n```\n\nUse instead:\n```python\ndef gen():\n yield 1\n```\n\n## Fix safety\nThis fix is always marked as unsafe because removing the intermediate\nvariable assignment changes the local variable bindings visible to\n`locals()` and debuggers when the generator is suspended at the `yield`.\n",
|
|
940
|
+
"ruff/RUF071": "## What it does\nChecks for uses of `os.path.commonprefix`.\n\n## Why is this bad?\n`os.path.commonprefix` performs a character-by-character string\ncomparison rather than comparing path components. This leads to\nincorrect results when paths share a common string prefix that\nis not a valid path component.\n\n`os.path.commonpath` correctly compares path components.\n\n`os.path.commonprefix` is deprecated as of Python 3.15.\n\n## Example\n```python\nimport os\n\n# Returns \"/usr/l\" \u2014 not a valid directory!\nos.path.commonprefix([\"/usr/lib\", \"/usr/local/lib\"])\n```\n\nUse instead:\n```python\nimport os\n\n# Returns \"/usr\" \u2014 correct common path\nos.path.commonpath([\"/usr/lib\", \"/usr/local/lib\"])\n```\n\n## Fix safety\n\nThis fix is marked as unsafe because `os.path.commonprefix` and\n`os.path.commonpath` have different semantics:\n\n- `commonprefix` performs a character-by-character string comparison\n and returns the longest common string prefix.\n- `commonpath` compares path components and returns the longest common\n path prefix.\n\nIf you are intentionally using `commonprefix` for non-path string\ncomparisons (e.g., finding a common prefix among arbitrary strings\nlike version numbers or identifiers), see the\n[error suppression](https://docs.astral.sh/ruff/linter/#error-suppression)\ndocumentation for ways to disable this rule.\n\nFor example:\n\n```python\nimport os\n\n# commonprefix works on non-path strings\nos.path.commonprefix([\"12345\", \"12378\"]) # \"123\"\nos.path.commonpath([\"12345\", \"12378\"]) # \"\"\n```\n\n## References\n- [Python documentation: `os.path.commonprefix`](https://docs.python.org/3/library/os.path.html#os.path.commonprefix)\n- [Python documentation: `os.path.commonpath`](https://docs.python.org/3/library/os.path.html#os.path.commonpath)\n- [Why `os.path.commonprefix` is deprecated](https://sethmlarson.dev/deprecate-confusing-apis-like-os-path-commonprefix)\n- [CPython deprecation issue](https://github.com/python/cpython/issues/144347)\n",
|
|
941
|
+
"ruff/RUF072": "## What it does\nChecks for `finally` clauses that only contain `pass` or `...` statements\n\n## Why is this bad?\nAn empty `finally` clause is a no-op and adds unnecessary noise.\nIf the `try` statement has `except` or `else` clauses, the `finally`\nclause can simply be removed. If it's a bare `try/finally`, the entire\n`try` statement can be replaced with its body\n\n## Example\n```python\ntry:\n foo()\nexcept Exception:\n bar()\nfinally:\n pass\n```\n\nUse instead:\n```python\ntry:\n foo()\nexcept Exception:\n bar()\n```\n\n## Example\n```python\ntry:\n foo()\nfinally:\n pass\n```\n\nUse instead:\n```python\nfoo()\n```\n\n## See also\n- [`needless-else`][RUF047]: Removes empty `else` clauses on `try` (and\n other statements). Both rules can fire on the same `try` statement\n- [`suppressible-exception`][SIM105]: Rewrites `try/except: pass` to\n `contextlib.suppress()`. Won't apply while a `finally` clause is present,\n so RUF072 must remove it first\n- [`useless-try-except`][TRY203]: Flags `try/except` that only re-raises\n",
|
|
942
|
+
"ruff/RUF073": "## What it does\nChecks for uses of the `%` operator on f-strings.\n\n## Why is this bad?\nF-strings already support interpolation via `{...}` expressions.\nUsing the `%` operator on an f-string is almost certainly a mistake,\nsince the f-string's interpolation and `%`-formatting serve the same\npurpose. This typically indicates that the developer intended to use\neither an f-string or `%`-formatting, but not both.\n\n## Example\n```python\nf\"{name}\" % name\nf\"hello %s %s\" % (first, second)\n```\n\nUse instead:\n```python\nf\"{name}\"\nf\"hello {first} {second}\"\n```\n",
|
|
943
|
+
"ruff/RUF074": "## What it does\nChecks for incorrect ordering of decorators on functions and methods.\n\n## Why is this bad?\nDecorators are applied bottom-up. Certain decorator combinations cause\nruntime errors or silent wrong behavior when placed in the wrong order.\nFor example, `@abstractmethod` must be the innermost (bottom) decorator\nwhen combined with `@property`, `@classmethod`, or `@staticmethod`.\n\n## Example\n```python\nfrom abc import abstractmethod\n\n\nclass Foo:\n @abstractmethod\n @property\n def bar(self): ...\n```\n\nUse instead:\n```python\nfrom abc import abstractmethod\n\n\nclass Foo:\n @property\n @abstractmethod\n def bar(self): ...\n```\n\n## References\n- [Python documentation: `abc.abstractmethod`](https://docs.python.org/3/library/abc.html#abc.abstractmethod)\n- [Python documentation: `contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager)\n",
|
|
944
|
+
"ruff/RUF075": "## What it does\nChecks for `@contextlib.contextmanager` decorated functions that contain\n`yield` expressions not protected against exceptions.\n\n## Why is this bad?\nWhen a context manager is used, code after `yield` is intended to run\nduring cleanup when the context exits. However, if an exception is raised\ninside the `with` block, code after an unprotected `yield` will never\nexecute.\n\nWrapping `yield` in a `try`/`finally` or `try`/`except` block ensures\nthat exceptions are handled appropriately.\n\n## Example\n```python\nfrom contextlib import contextmanager\n\n\n@contextmanager\ndef my_context():\n print(\"setup\")\n yield\n print(\"cleanup\") # This won't run if an exception is raised!\n```\n\nUse instead:\n```python\nfrom contextlib import contextmanager\n\n\n@contextmanager\ndef my_context():\n print(\"setup\")\n try:\n yield\n finally:\n print(\"cleanup\") # This always runs\n```\n\n## References\n- [Python documentation: `contextlib.contextmanager`](https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager)\n",
|
|
945
|
+
"ruff/RUF077": "## What it does\nChecks for default values on receiver parameters (e.g., `self`, `cls`) in method definitions.\n\n## Why is this bad?\nReceiver parameters (`self`, `cls`, or any name used as the receiver) should not have default\nvalues. In practice, these parameters are usually bound by the method binding protocol, so a\ndefault value on a receiver parameter is almost\ncertainly a mistake and can lead to confusing behavior or runtime errors.\n\n## Example\n\n```python\nclass A:\n def method(self=None): ...\n\n @classmethod\n def build(cls=None): ...\n```\n\nUse instead:\n\n```python\nclass A:\n def method(self): ...\n\n @classmethod\n def build(cls): ...\n```\n\n## Fix safety\nThis fix is always marked as unsafe. Removing the default changes behavior for a caller that\ninvokes the method directly through the class rather than through an instance (e.g.\n`A.method()` instead of `A().method()`), relying on the receiver parameter's default value.\n\n## Known limitations\nTo avoid false positives, this rule only flags an undecorated method, an undecorated\n`__new__`, or a method whose sole decorator is the one that makes it a `@classmethod`. A\nmethod with any other decorator (including common ones like `@property`, `@x.setter`, or\n`@typing.override`) is not flagged, even though such decorators typically leave the receiver\nbinding unchanged, because an arbitrary decorator could alter it.\n\n## Options\n- `lint.pep8-naming.classmethod-decorators`\n",
|
|
946
|
+
"ruff/RUF100": "## What it does\nChecks for `noqa` directives that are no longer applicable.\n\n## Why is this bad?\nA `noqa` directive that no longer matches any diagnostic violations is\nlikely included by mistake, and should be removed to avoid confusion.\n\n## Example\n```python\nimport foo # noqa: F401\n\n\ndef bar():\n foo.bar()\n```\n\nUse instead:\n```python\nimport foo\n\n\ndef bar():\n foo.bar()\n```\n\n## Conflict with other linters\nWhen using `RUF100` with the `--fix` option, Ruff may remove trailing comments\nthat follow a `# noqa` directive on the same line, as it interprets the\nremainder of the line as a description for the suppression.\n\nTo prevent Ruff from removing suppressions for other tools (like `pylint`\nor `mypy`), separate them with a second `#` character:\n\n```python\n# Bad: Ruff --fix will remove the pylint comment\ndef visit_ImportFrom(self, node): # noqa: N802, pylint: disable=invalid-name\n pass\n\n\n# Good: Ruff will preserve the pylint comment\ndef visit_ImportFrom(self, node): # noqa: N802 # pylint: disable=invalid-name\n pass\n```\n\n## Fix safety\n\nThe rule's fix is marked as unsafe when a full suppression comment would be removed and there\nare other nested comments on the same line. Removing such a comment can change the behavior of\nother suppression comments before or after the removed comment.\n\n## See also\n\nThis rule ignores any codes that are unknown to Ruff, as it can't determine\nif the codes are valid or used by other tools. Enable [`invalid-rule-code`][RUF102]\nto flag any unknown rule codes.\n\n## References\n- [Ruff error suppression](https://docs.astral.sh/ruff/linter/#error-suppression)\n\n[RUF102]: https://docs.astral.sh/ruff/rules/invalid-rule-code/\n",
|
|
947
|
+
"ruff/RUF101": "## What it does\nChecks for `noqa` directives that use redirected rule codes.\n\n## Why is this bad?\nWhen one of Ruff's rule codes has been redirected, the implication is that the rule has\nbeen deprecated in favor of another rule or code. To keep your codebase\nconsistent and up-to-date, prefer the canonical rule code over the deprecated\ncode.\n\n## Example\n```python\nx = eval(command) # noqa: PGH001\n```\n\nUse instead:\n```python\nx = eval(command) # noqa: S307\n```\n",
|
|
948
|
+
"ruff/RUF102": "## What it does\nChecks for `noqa` codes that are invalid.\n\n## Why is this bad?\nInvalid rule codes serve no purpose and may indicate outdated code suppressions.\n\n## Example\n```python\nimport os # noqa: XYZ999\n```\n\nUse instead:\n```python\nimport os\n```\n\nOr if there are still valid codes needed:\n```python\nimport os # noqa: E402\n```\n\n## Fix safety\n\nThe rule's fix is marked as unsafe when a full suppression comment would be removed and there\nare other nested comments on the same line. Removing such a comment can change the behavior of\nother suppression comments before or after the removed comment.\n\n## Options\n\nThis rule will flag rule codes that are unknown to Ruff, even if they are\nvalid for other tools. You can tell Ruff to ignore such codes by configuring\nthe list of known \"external\" rule codes with the following option:\n\n- `lint.external`\n",
|
|
949
|
+
"ruff/RUF103": "## What it does\nChecks for invalid suppression comments\n\n## Why is this bad?\nInvalid suppression comments are ignored by Ruff, and should either\nbe fixed or removed to avoid confusion.\n\n## Example\n```python\n# ruff: disable # missing codes\n```\n\nUse instead:\n```python\n# ruff: disable[E501]\n```\n\nOr delete the invalid suppression comment.\n\n## References\n- [Ruff error suppression](https://docs.astral.sh/ruff/linter/#error-suppression)\n",
|
|
950
|
+
"ruff/RUF104": "## What it does\nChecks for unmatched range suppression comments\n\n## Why is this bad?\nUnmatched range suppression comments can inadvertently suppress violations\nover larger sections of code than intended, particularly at module scope.\n\n## Example\n```python\ndef foo():\n # ruff: disable[E501] # unmatched\n REALLY_LONG_VALUES = [...]\n\n print(REALLY_LONG_VALUES)\n```\n\nUse instead:\n```python\ndef foo():\n # ruff: disable[E501]\n REALLY_LONG_VALUES = [...]\n # ruff: enable[E501]\n\n print(REALLY_LONG_VALUES)\n```\n\n## References\n- [Ruff error suppression](https://docs.astral.sh/ruff/linter/#error-suppression)\n",
|
|
951
|
+
"ruff/RUF105": "## What it does\n\nChecks for the use of `noqa` comments instead of Ruff-specific `ruff: ignore` comments.\n\n## Why is this bad?\n\n`ruff: ignore` comments allow the use of rule names instead of codes and can be used in more\nplaces than `noqa` comments.\n\nNote that this is an opinionated, stylistic rule. `noqa` comments may be needed for backwards\ncompatibility with other tools. You should also feel free to disable this rule if you simply\nprefer `noqa` comments.\n\n## Example\n\n```python\nimport os # noqa: F401\n```\n\nUse instead:\n```python\nimport os # ruff: ignore[F401]\n```\n\nOr if you prefer the own-line form:\n\n```python\n# ruff: ignore[unused-import]\nimport os\n```\n\n## Options\n\nThis rule will flag `noqa` comments containing rule codes that are unknown to Ruff, even if they\nare valid for other tools. You can tell Ruff to ignore such codes by configuring the list of\nknown \"external\" rule codes with the following option:\n\n- `lint.external`\n\nRuff will still emit a diagnostic without a fix if `external` and known codes are present in the\nsame `noqa` comment, assuming that only the `external` codes need to remain in the `noqa`\ncomment.\n\n## See also\n\nThis rule avoids offering a fix if any of the rule codes in a `noqa` comment are unused. See\n`unused-noqa` for a rule that will remove these and allow the remaining codes to be moved into a\n`ruff: ignore` comment.\n",
|
|
952
|
+
"ruff/RUF106": "## What it does\n\nChecks for rule codes in Ruff-specific suppression comments.\n\n## Why is this bad?\n\nHuman-readable rule names are easier to understand than rule codes. Using names also avoids\nrequiring readers to look up the meaning of each code.\n\nThis rule applies to `ruff: ignore`, `ruff: file-ignore`, `ruff: disable`, and `ruff: enable`\ncomments.\n\n## Example\n\n```python\nimport os # ruff: ignore[F401]\n```\n\nUse instead:\n```python\nimport os # ruff: ignore[unused-import]\n```\n",
|
|
953
|
+
"ruff/RUF200": "## What it does\nChecks for any pyproject.toml that does not conform to the schema from the relevant PEPs.\n\n## Why is this bad?\nYour project may contain invalid metadata or configuration without you noticing.\n\n## Example\n```toml\n[project]\nname = \"crab\"\nversion = \"1.0.0\"\nauthors = [\"Ferris the Crab <ferris@example.org>\"]\n```\n\nUse instead:\n```toml\n[project]\nname = \"crab\"\nversion = \"1.0.0\"\nauthors = [\n { name = \"Ferris the Crab\", email = \"ferris@example.org\" }\n]\n```\n\n## References\n- [Specification of `[project]` in pyproject.toml](https://packaging.python.org/en/latest/specifications/declaring-project-metadata/)\n- [Specification of `[build-system]` in pyproject.toml](https://peps.python.org/pep-0518/)\n- [Draft but implemented license declaration extensions](https://peps.python.org/pep-0639)\n",
|
|
954
|
+
"ruff/RUF201": "## What it does\n\nChecks for any configuration files that use rule codes as selectors.\n\n## Why is this bad?\n\nHuman-readable rule names are easier to understand than rule codes. Using names also avoids\nrequiring readers to look up the meaning of each code.\n\n## Example\n\n```toml\n[tool.ruff.lint]\nselect = [\"F401\"]\n```\n\nUse instead:\n\n```toml\n[tool.ruff.lint]\nselect = [\"unused-import\"]\n```\n",
|
|
955
|
+
"ruff/TRY002": "## What it does\nChecks for code that raises `Exception` or `BaseException` directly.\n\n## Why is this bad?\nHandling such exceptions requires the use of `except Exception` or\n`except BaseException`. These will capture almost _any_ raised exception,\nincluding failed assertions, division by zero, and more.\n\nPrefer to raise your own exception, or a more specific built-in\nexception, so that you can avoid over-capturing exceptions that you\ndon't intend to handle.\n\n## Example\n```python\ndef main_function():\n if not cond:\n raise Exception()\n\n\ndef consumer_func():\n try:\n do_step()\n prepare()\n main_function()\n except Exception:\n logger.error(\"Oops\")\n```\n\nUse instead:\n```python\ndef main_function():\n if not cond:\n raise CustomException()\n\n\ndef consumer_func():\n try:\n do_step()\n prepare()\n main_function()\n except CustomException:\n logger.error(\"Main function failed\")\n except Exception:\n logger.error(\"Oops\")\n```\n",
|
|
956
|
+
"ruff/TRY004": "## What it does\nChecks for type checks that do not raise `TypeError`.\n\n## Why is this bad?\nThe Python documentation states that `TypeError` should be raised upon\nencountering an inappropriate type.\n\n## Example\n```python\ndef foo(n: int):\n if isinstance(n, int):\n pass\n else:\n raise ValueError(\"n must be an integer\")\n```\n\nUse instead:\n```python\ndef foo(n: int):\n if isinstance(n, int):\n pass\n else:\n raise TypeError(\"n must be an integer\")\n```\n\n## References\n- [Python documentation: `TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError)\n",
|
|
957
|
+
"ruff/TRY200": "## Removed\nThis rule is identical to [B904] which should be used instead.\n\n## What it does\nChecks for exceptions that are re-raised without specifying the cause via\nthe `from` keyword.\n\n## Why is this bad?\nThe `from` keyword sets the `__cause__` attribute of the exception, which\nstores the \"cause\" of the exception. The availability of an exception\n\"cause\" is useful for debugging.\n\n## Example\n```python\ndef reciprocal(n):\n try:\n return 1 / n\n except ZeroDivisionError:\n raise ValueError()\n```\n\nUse instead:\n```python\ndef reciprocal(n):\n try:\n return 1 / n\n except ZeroDivisionError as exc:\n raise ValueError() from exc\n```\n\n## References\n- [Python documentation: Exception context](https://docs.python.org/3/library/exceptions.html#exception-context)\n\n[B904]: https://docs.astral.sh/ruff/rules/raise-without-from-inside-except/\n",
|
|
958
|
+
"ruff/TRY201": "## What it does\nChecks for needless exception names in `raise` statements.\n\n## Why is this bad?\nIt's redundant to specify the exception name in a `raise` statement if the\nexception is being re-raised.\n\n## Example\n```python\ndef foo():\n try:\n ...\n except ValueError as exc:\n raise exc\n```\n\nUse instead:\n```python\ndef foo():\n try:\n ...\n except ValueError:\n raise\n```\n\n## Fix safety\nThis rule's fix is marked as unsafe, as it doesn't properly handle bound\nexceptions that are shadowed between the `except` and `raise` statements.\n",
|
|
959
|
+
"ruff/TRY203": "## What it does\nChecks for immediate uses of `raise` within exception handlers.\n\n## Why is this bad?\nCapturing an exception, only to immediately reraise it, has no effect.\nInstead, remove the error-handling code and let the exception propagate\nupwards without the unnecessary `try`-`except` block.\n\n## Example\n```python\ndef foo():\n try:\n bar()\n except NotImplementedError:\n raise\n```\n\nUse instead:\n```python\ndef foo():\n bar()\n```\n",
|
|
960
|
+
"ruff/TRY300": "## What it does\nChecks for `return` statements in `try` blocks.\n\n## Why is this bad?\nThe `try`-`except` statement has an `else` clause for code that should\nrun _only_ if no exceptions were raised. Returns in `try` blocks may\nexhibit confusing or unwanted behavior, such as being overridden by\ncontrol flow in `except` and `finally` blocks, or unintentionally\nsuppressing an exception.\n\n## Example\n```python\nimport logging\n\n\ndef reciprocal(n):\n try:\n rec = 1 / n\n print(f\"reciprocal of {n} is {rec}\")\n return rec\n except ZeroDivisionError:\n logging.exception(\"Exception occurred\")\n raise\n```\n\nUse instead:\n```python\nimport logging\n\n\ndef reciprocal(n):\n try:\n rec = 1 / n\n except ZeroDivisionError:\n logging.exception(\"Exception occurred\")\n raise\n else:\n print(f\"reciprocal of {n} is {rec}\")\n return rec\n```\n\n## References\n- [Python documentation: Errors and Exceptions](https://docs.python.org/3/tutorial/errors.html)\n",
|
|
961
|
+
"ruff/TRY301": "## What it does\nChecks for `raise` statements within `try` blocks. The only `raise`s\ncaught are those that throw exceptions caught by the `try` statement itself.\n\n## Why is this bad?\nRaising and catching exceptions within the same `try` block is redundant,\nas the code can be refactored to avoid the `try` block entirely.\n\nAlternatively, the `raise` can be moved within an inner function, making\nthe exception reusable across multiple call sites.\n\n## Example\n```python\ndef bar():\n pass\n\n\ndef foo():\n try:\n a = bar()\n if not a:\n raise ValueError\n except ValueError:\n raise\n```\n\nUse instead:\n```python\ndef bar():\n raise ValueError\n\n\ndef foo():\n try:\n a = bar() # refactored `bar` to raise `ValueError`\n except ValueError:\n raise\n```\n",
|
|
962
|
+
"ruff/TRY400": "## What it does\nChecks for uses of `logging.error` instead of `logging.exception` when\nlogging an exception.\n\n## Why is this bad?\n`logging.exception` logs the exception and the traceback, while\n`logging.error` only logs the exception. The former is more appropriate\nwhen logging an exception, as the traceback is often useful for debugging.\n\n## Example\n```python\nimport logging\n\n\ndef func():\n try:\n raise NotImplementedError\n except NotImplementedError:\n logging.error(\"Exception occurred\")\n```\n\nUse instead:\n```python\nimport logging\n\n\ndef func():\n try:\n raise NotImplementedError\n except NotImplementedError:\n logging.exception(\"Exception occurred\")\n```\n\n## Fix safety\nThis rule's fix is marked as safe when run against `logging.error` calls,\nbut unsafe when marked against other logger-like calls (e.g.,\n`logger.error`), since the rule is prone to false positives when detecting\nlogger-like calls outside of the `logging` module.\n\n## Options\n\n- `lint.logger-objects`\n\n## References\n- [Python documentation: `logging.exception`](https://docs.python.org/3/library/logging.html#logging.exception)\n",
|
|
963
|
+
"ruff/TRY401": "## What it does\nChecks for excessive logging of exception objects.\n\n## Why is this bad?\nWhen logging exceptions via `logging.exception`, the exception object\nis logged automatically. Including the exception object in the log\nmessage is redundant and can lead to excessive logging.\n\n## Example\n```python\ntry:\n ...\nexcept ValueError as e:\n logger.exception(f\"Found an error: {e}\")\n```\n\nUse instead:\n```python\ntry:\n ...\nexcept ValueError:\n logger.exception(\"Found an error\")\n```\n\n## Options\n\n- `lint.logger-objects`\n",
|
|
964
|
+
"bandit/B604:any_other_function_with_shell_equals_true": "Python possesses many mechanisms to invoke an external executable. However,\ndoing so may present a security issue if appropriate care is not taken to\nsanitize any user provided or variable input.\n\nThis plugin test is part of a family of tests built to check for process\nspawning and warn appropriately. Specifically, this plugin test\ninterrogates method calls for the presence of a keyword parameter `shell`\nequalling true. It is related to detection of shell injection issues and is\nintended to catch custom wrappers to vulnerable methods that may have been\ncreated.\n\nSee also:\n\n- :doc:`../plugins/linux_commands_wildcard_injection`\n- :doc:`../plugins/subprocess_popen_with_shell_equals_true`\n- :doc:`../plugins/subprocess_without_shell_equals_true`\n- :doc:`../plugins/start_process_with_no_shell`\n- :doc:`../plugins/start_process_with_a_shell`\n- :doc:`../plugins/start_process_with_partial_path`\n\n**Config Options:**\n\nThis plugin test shares a configuration with others in the same family,\nnamely `shell_injection`. This configuration is divided up into three\nsections, `subprocess`, `shell` and `no_shell`. They each list Python calls\nthat spawn subprocesses, invoke commands within a shell, or invoke commands\nwithout a shell (by replacing the calling process) respectively.\n\nSpecifically, this plugin excludes those functions listed under the\nsubprocess section, these methods are tested in a separate specific test\nplugin and this exclusion prevents duplicate issue reporting.\n\n```\n\nshell_injection:\n # Start a process using the subprocess module, or one of its\n wrappers.\n subprocess: [subprocess.Popen, subprocess.call,\n subprocess.check_call, subprocess.check_output\n execute_with_timeout]\n\n\n```\n**Example:**\n\n```\n\n>> Issue: Function call with shell=True parameter identified, possible\nsecurity issue.\n Severity: Medium Confidence: High\n CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html)\n Location: ./examples/subprocess_shell.py:9\n8 pop('/bin/gcc --version', shell=True)\n9 Popen('/bin/gcc --version', shell=True)\n10\n\n```\n\n - https://security.openstack.org/guidelines/dg_avoid-shell-true.html\n - https://security.openstack.org/guidelines/dg_use-subprocess-securely.html\n - https://cwe.mitre.org/data/definitions/78.html\n\n\n CWE information added",
|
|
965
|
+
"bandit/B610:django_extra_used": "**Example:**\n\n```\n\n>> Issue: [B610:django_extra_used] Use of extra potential SQL attack vector.\n Severity: Medium Confidence: Medium\n CWE: CWE-89 (https://cwe.mitre.org/data/definitions/89.html)\n Location: examples/django_sql_injection_extra.py:29:0\n More Info: https://bandit.readthedocs.io/en/latest/plugins/b610_django_extra_used.html\n28 tables_str = 'django_content_type\" WHERE \"auth_user\".\"username\"=\"admin'\n29 User.objects.all().extra(tables=[tables_str]).distinct()\n\n```\n\n - https://docs.djangoproject.com/en/dev/topics/security/#sql-injection-protection\n - https://cwe.mitre.org/data/definitions/89.html\n\n\n CWE information added",
|
|
966
|
+
"bandit/B703:django_mark_safe": "**Example:**\n\n```\n\n>> Issue: [B703:django_mark_safe] Potential XSS on mark_safe function.\n Severity: Medium Confidence: High\n CWE: CWE-80 (https://cwe.mitre.org/data/definitions/80.html)\n Location: examples/mark_safe_insecure.py:159:4\n More Info: https://bandit.readthedocs.io/en/latest/plugins/b703_django_mark_safe.html\n158 str_arg = 'could be insecure'\n159 safestring.mark_safe(str_arg)\n\n```\n\n - https://docs.djangoproject.com/en/dev/topics/security/#cross-site-scripting-xss-protection\n - https://docs.djangoproject.com/en/dev/ref/utils/#module-django.utils.safestring\n - https://docs.djangoproject.com/en/dev/ref/utils/#django.utils.html.format_html\n - https://cwe.mitre.org/data/definitions/80.html\n\n\n CWE information added",
|
|
967
|
+
"bandit/B611:django_rawsql_used": "**Example:**\n\n```\n\n>> Issue: [B611:django_rawsql_used] Use of RawSQL potential SQL attack vector.\n Severity: Medium Confidence: Medium\n CWE: CWE-89 (https://cwe.mitre.org/data/definitions/89.html)\n Location: examples/django_sql_injection_raw.py:11:26\n More Info: https://bandit.readthedocs.io/en/latest/plugins/b611_django_rawsql_used.html\n10 ' WHERE \"username\"=\"admin\" OR 1=%s --'\n11 User.objects.annotate(val=RawSQL(raw, [0]))\n\n```\n\n - https://docs.djangoproject.com/en/dev/topics/security/#sql-injection-protection\n - https://cwe.mitre.org/data/definitions/89.html\n\n\n CWE information added",
|
|
968
|
+
"bandit/B107:hardcoded_password_default": "The use of hard-coded passwords increases the possibility of password\nguessing tremendously. This plugin test looks for all function definitions\nthat specify a default string literal for some argument. It checks that\nthe argument does not look like a password.\n\nVariables are considered to look like a password if they have match any one\nof:\n\n- \"password\"\n- \"pass\"\n- \"passwd\"\n- \"pwd\"\n- \"secret\"\n- \"token\"\n- \"secrete\"\n\nNote: this can be noisy and may generate false positives. We do not\nreport on None values which can be legitimately used as a default value,\nwhen initializing a function or class.\n\n**Config Options:**\n\nNone\n\n**Example:**\n\n```\n\n>> Issue: [B107:hardcoded_password_default] Possible hardcoded\npassword: 'Admin'\n Severity: Low Confidence: Medium\n CWE: CWE-259 (https://cwe.mitre.org/data/definitions/259.html)\n Location: ./examples/hardcoded-passwords.py:1\n\n1 def someFunction(user, password=\"Admin\"):\n2 print(\"Hi \" + user)\n\n```\n\n - https://www.owasp.org/index.php/Use_of_hard-coded_password\n - https://cwe.mitre.org/data/definitions/259.html\n\n\n CWE information added",
|
|
969
|
+
"bandit/B106:hardcoded_password_funcarg": "The use of hard-coded passwords increases the possibility of password\nguessing tremendously. This plugin test looks for all function calls being\npassed a keyword argument that is a string literal. It checks that the\nassigned local variable does not look like a password.\n\nVariables are considered to look like a password if they have match any one\nof:\n\n- \"password\"\n- \"pass\"\n- \"passwd\"\n- \"pwd\"\n- \"secret\"\n- \"token\"\n- \"secrete\"\n\nNote: this can be noisy and may generate false positives.\n\n**Config Options:**\n\nNone\n\n**Example:**\n\n```\n\n>> Issue: [B106:hardcoded_password_funcarg] Possible hardcoded\npassword: 'blerg'\n Severity: Low Confidence: Medium\n CWE: CWE-259 (https://cwe.mitre.org/data/definitions/259.html)\n Location: ./examples/hardcoded-passwords.py:16\n15\n16 doLogin(password=\"blerg\")\n\n```\n\n - https://www.owasp.org/index.php/Use_of_hard-coded_password\n - https://cwe.mitre.org/data/definitions/259.html\n\n\n CWE information added",
|
|
970
|
+
"bandit/B105:hardcoded_password_string": "The use of hard-coded passwords increases the possibility of password\nguessing tremendously. This plugin test looks for all string literals and\nchecks the following conditions:\n\n- assigned to a variable that looks like a password\n- assigned to a dict key that looks like a password\n- assigned to a class attribute that looks like a password\n- used in a comparison with a variable that looks like a password\n\nVariables are considered to look like a password if they have match any one\nof:\n\n- \"password\"\n- \"pass\"\n- \"passwd\"\n- \"pwd\"\n- \"secret\"\n- \"token\"\n- \"secrete\"\n\nNote: this can be noisy and may generate false positives.\n\n**Config Options:**\n\nNone\n\n**Example:**\n\n```\n\n>> Issue: Possible hardcoded password '(root)'\n Severity: Low Confidence: Low\n CWE: CWE-259 (https://cwe.mitre.org/data/definitions/259.html)\n Location: ./examples/hardcoded-passwords.py:5\n4 def someFunction2(password):\n5 if password == \"root\":\n6 print(\"OK, logged in\")\n\n```\n\n - https://www.owasp.org/index.php/Use_of_hard-coded_password\n - https://cwe.mitre.org/data/definitions/259.html\n\n\n CWE information added",
|
|
971
|
+
"bandit/B615:huggingface_unsafe_download": "This plugin checks for unsafe artifact download from Hugging Face Hub\nwithout immutable/reproducible revision pinning.",
|
|
972
|
+
"bandit/B614:pytorch_load": "This plugin checks for unsafe use of `torch.load` and\n`torch.serialization.load`. Using `torch.load` or\n`torch.serialization.load` with untrusted data can lead to\narbitrary code execution. The safe alternative is to use\n`weights_only=True` or the safetensors library.",
|
|
973
|
+
"bandit/B508:snmp_insecure_version": "This test is for checking for the usage of insecure SNMP version like\n v1, v2c\n\nPlease update your code to use more secure versions of SNMP.\n\n**Example:**\n\n```\n\n>> Issue: [B508:snmp_insecure_version_check] The use of SNMPv1 and\n SNMPv2 is insecure. You should use SNMPv3 if able.\n Severity: Medium Confidence: High\n CWE: CWE-319 (https://cwe.mitre.org/data/definitions/319.html)\n Location: examples/snmp.py:4:4\n More Info: https://bandit.readthedocs.io/en/latest/plugins/b508_snmp_insecure_version_check.html\n3 # SHOULD FAIL\n4 a = CommunityData('public', mpModel=0)\n5 # SHOULD FAIL\n\n```\n\n - http://snmplabs.com/pysnmp/examples/hlapi/asyncore/sync/manager/cmdgen/snmp-versions.html\n - https://cwe.mitre.org/data/definitions/319.html\n\n\n CWE information added",
|
|
974
|
+
"bandit/B509:snmp_weak_cryptography": "This test is for checking for the usage of insecure SNMP cryptography:\n v3 using noAuthNoPriv.\n\nPlease update your code to use more secure versions of SNMP. For example:\n\nInstead of:\n `CommunityData('public', mpModel=0)`\n\nUse (Defaults to usmHMACMD5AuthProtocol and usmDESPrivProtocol\n `UsmUserData(\"securityName\", \"authName\", \"privName\")`\n\n**Example:**\n\n```\n\n>> Issue: [B509:snmp_crypto_check] You should not use SNMPv3 without encryption. noAuthNoPriv & authNoPriv is insecure\n Severity: Medium CWE: CWE-319 (https://cwe.mitre.org/data/definitions/319.html) Confidence: High\n Location: examples/snmp.py:6:11\n More Info: https://bandit.readthedocs.io/en/latest/plugins/b509_snmp_crypto_check.html\n5 # SHOULD FAIL\n6 insecure = UsmUserData(\"securityName\")\n7 # SHOULD FAIL\n\n```\n\n - http://snmplabs.com/pysnmp/examples/hlapi/asyncore/sync/manager/cmdgen/snmp-versions.html\n - https://cwe.mitre.org/data/definitions/319.html\n\n\n CWE information added",
|
|
975
|
+
"bandit/B503:ssl_with_bad_defaults": "This plugin is part of a family of tests that detect the use of known bad\nversions of SSL/TLS, please see :doc:`../plugins/ssl_with_bad_version` for\na complete discussion. Specifically, this plugin test scans for Python\nmethods with default parameter values that specify the use of broken\nSSL/TLS protocol versions. Currently, detection supports methods using\nPython's native SSL/TLS support and the pyOpenSSL module. A MEDIUM severity\nwarning will be reported whenever known broken protocol versions are\ndetected.\n\n**Config Options:**\n\nThis test shares the configuration provided for the standard\n:doc:`../plugins/ssl_with_bad_version` test, please refer to its\ndocumentation.\n\n**Example:**\n\n```\n\n>> Issue: Function definition identified with insecure SSL/TLS protocol\nversion by default, possible security issue.\n Severity: Medium Confidence: Medium\n CWE: CWE-327 (https://cwe.mitre.org/data/definitions/327.html)\n Location: ./examples/ssl-insecure-version.py:28\n27\n28 def open_ssl_socket(version=SSL.SSLv2_METHOD):\n29 pass\n\n```\n\n - :func:`ssl_with_bad_version`\n - :func:`ssl_with_no_version`\n - https://heartbleed.com/\n - https://en.wikipedia.org/wiki/POODLE\n - https://security.openstack.org/guidelines/dg_move-data-securely.html\n\n\n CWE information added\n\n Added TLS 1.1",
|
|
976
|
+
"bandit/B502:ssl_with_bad_version": "Several highly publicized exploitable flaws have been discovered\nin all versions of SSL and early versions of TLS. It is strongly\nrecommended that use of the following known broken protocol versions be\navoided:\n\n- SSL v2\n- SSL v3\n- TLS v1\n- TLS v1.1\n\nThis plugin test scans for calls to Python methods with parameters that\nindicate the used broken SSL/TLS protocol versions. Currently, detection\nsupports methods using Python's native SSL/TLS support and the pyOpenSSL\nmodule. A HIGH severity warning will be reported whenever known broken\nprotocol versions are detected.\n\nIt is worth noting that native support for TLS 1.2 is only available in\nmore recent Python versions, specifically 2.7.9 and up, and 3.x\n\nA note on 'SSLv23':\n\nAmongst the available SSL/TLS versions provided by Python/pyOpenSSL there\nexists the option to use SSLv23. This very poorly named option actually\nmeans \"use the highest version of SSL/TLS supported by both the server and\nclient\". This may (and should be) a version well in advance of SSL v2 or\nv3. Bandit can scan for the use of SSLv23 if desired, but its detection\ndoes not necessarily indicate a problem.\n\nWhen using SSLv23 it is important to also provide flags to explicitly\nexclude bad versions of SSL/TLS from the protocol versions considered. Both\nthe Python native and pyOpenSSL modules provide the ``OP_NO_SSLv2`` and\n``OP_NO_SSLv3`` flags for this purpose.\n\n**Config Options:**\n\n```\n\nssl_with_bad_version:\n bad_protocol_versions:\n - PROTOCOL_SSLv2\n - SSLv2_METHOD\n - SSLv23_METHOD\n - PROTOCOL_SSLv3 # strict option\n - PROTOCOL_TLSv1 # strict option\n - SSLv3_METHOD # strict option\n - TLSv1_METHOD # strict option\n\n```\n**Example:**\n\n```\n\n>> Issue: ssl.wrap_socket call with insecure SSL/TLS protocol version\nidentified, security issue.\n Severity: High Confidence: High\n CWE: CWE-327 (https://cwe.mitre.org/data/definitions/327.html)\n Location: ./examples/ssl-insecure-version.py:13\n12 # strict tests\n13 ssl.wrap_socket(ssl_version=ssl.PROTOCOL_SSLv3)\n14 ssl.wrap_socket(ssl_version=ssl.PROTOCOL_TLSv1)\n\n```\n\n - :func:`ssl_with_bad_defaults`\n - :func:`ssl_with_no_version`\n - https://heartbleed.com/\n - https://en.wikipedia.org/wiki/POODLE\n - https://security.openstack.org/guidelines/dg_move-data-securely.html\n - https://cwe.mitre.org/data/definitions/327.html\n\n\n CWE information added\n\n Added TLS 1.1",
|
|
977
|
+
"bandit/B504:ssl_with_no_version": "This plugin is part of a family of tests that detect the use of known bad\nversions of SSL/TLS, please see :doc:`../plugins/ssl_with_bad_version` for\na complete discussion. Specifically, This plugin test scans for specific\nmethods in Python's native SSL/TLS support and the pyOpenSSL module that\nconfigure the version of SSL/TLS protocol to use. These methods are known\nto provide default value that maximize compatibility, but permit use of the\naforementioned broken protocol versions. A LOW severity warning will be\nreported whenever this is detected.\n\n**Config Options:**\n\nThis test shares the configuration provided for the standard\n:doc:`../plugins/ssl_with_bad_version` test, please refer to its\ndocumentation.\n\n**Example:**\n\n```\n\n>> Issue: ssl.wrap_socket call with no SSL/TLS protocol version\nspecified, the default SSLv23 could be insecure, possible security\nissue.\n Severity: Low Confidence: Medium\n CWE: CWE-327 (https://cwe.mitre.org/data/definitions/327.html)\n Location: ./examples/ssl-insecure-version.py:23\n22\n23 ssl.wrap_socket()\n24\n\n```\n\n - :func:`ssl_with_bad_version`\n - :func:`ssl_with_bad_defaults`\n - https://heartbleed.com/\n - https://en.wikipedia.org/wiki/POODLE\n - https://security.openstack.org/guidelines/dg_move-data-securely.html\n\n\n CWE information added",
|
|
978
|
+
"bandit/B605:start_process_with_a_shell": "Python possesses many mechanisms to invoke an external executable. However,\ndoing so may present a security issue if appropriate care is not taken to\nsanitize any user provided or variable input.\n\nThis plugin test is part of a family of tests built to check for process\nspawning and warn appropriately. Specifically, this test looks for the\nspawning of a subprocess using a command shell. This type of subprocess\ninvocation is dangerous as it is vulnerable to various shell injection\nattacks. Great care should be taken to sanitize all input in order to\nmitigate this risk. Calls of this type are identified by the use of certain\ncommands which are known to use shells. Bandit will report a LOW\nseverity warning.\n\nSee also:\n\n- :doc:`../plugins/linux_commands_wildcard_injection`\n- :doc:`../plugins/subprocess_without_shell_equals_true`\n- :doc:`../plugins/start_process_with_no_shell`\n- :doc:`../plugins/start_process_with_partial_path`\n- :doc:`../plugins/subprocess_popen_with_shell_equals_true`\n\n**Config Options:**\n\nThis plugin test shares a configuration with others in the same family,\nnamely `shell_injection`. This configuration is divided up into three\nsections, `subprocess`, `shell` and `no_shell`. They each list Python calls\nthat spawn subprocesses, invoke commands within a shell, or invoke commands\nwithout a shell (by replacing the calling process) respectively.\n\nThis plugin specifically scans for methods listed in `shell` section.\n\n```\n\nshell_injection:\n shell:\n - os.system\n - os.popen\n - os.popen2\n - os.popen3\n - os.popen4\n - popen2.popen2\n - popen2.popen3\n - popen2.popen4\n - popen2.Popen3\n - popen2.Popen4\n - commands.getoutput\n - commands.getstatusoutput\n - subprocess.getoutput\n - subprocess.getstatusoutput\n\n```\n**Example:**\n\n```\n\n>> Issue: Starting a process with a shell: check for injection.\n Severity: Low Confidence: Medium\n CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html)\n Location: examples/os_system.py:3\n2\n3 os.system('/bin/echo hi')\n\n```\n\n - https://security.openstack.org\n - https://docs.python.org/3/library/os.html#os.system\n - https://docs.python.org/3/library/subprocess.html#frequently-used-arguments\n - https://security.openstack.org/guidelines/dg_use-subprocess-securely.html\n - https://cwe.mitre.org/data/definitions/78.html\n\n\n CWE information added",
|
|
979
|
+
"bandit/B606:start_process_with_no_shell": "Python possesses many mechanisms to invoke an external executable. However,\ndoing so may present a security issue if appropriate care is not taken to\nsanitize any user provided or variable input.\n\nThis plugin test is part of a family of tests built to check for process\nspawning and warn appropriately. Specifically, this test looks for the\nspawning of a subprocess in a way that doesn't use a shell. Although this\nis generally safe, it maybe useful for penetration testing workflows to\ntrack where external system calls are used. As such a LOW severity message\nis generated.\n\nSee also:\n\n- :doc:`../plugins/linux_commands_wildcard_injection`\n- :doc:`../plugins/subprocess_without_shell_equals_true`\n- :doc:`../plugins/start_process_with_a_shell`\n- :doc:`../plugins/start_process_with_partial_path`\n- :doc:`../plugins/subprocess_popen_with_shell_equals_true`\n\n**Config Options:**\n\nThis plugin test shares a configuration with others in the same family,\nnamely `shell_injection`. This configuration is divided up into three\nsections, `subprocess`, `shell` and `no_shell`. They each list Python calls\nthat spawn subprocesses, invoke commands within a shell, or invoke commands\nwithout a shell (by replacing the calling process) respectively.\n\nThis plugin specifically scans for methods listed in `no_shell` section.\n\n```\n\nshell_injection:\n no_shell:\n - os.execl\n - os.execle\n - os.execlp\n - os.execlpe\n - os.execv\n - os.execve\n - os.execvp\n - os.execvpe\n - os.spawnl\n - os.spawnle\n - os.spawnlp\n - os.spawnlpe\n - os.spawnv\n - os.spawnve\n - os.spawnvp\n - os.spawnvpe\n - os.startfile\n\n```\n**Example:**\n\n```\n\n>> Issue: [start_process_with_no_shell] Starting a process without a\n shell.\n Severity: Low Confidence: Medium\n CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html)\n Location: examples/os-spawn.py:8\n7 os.spawnv(mode, path, args)\n8 os.spawnve(mode, path, args, env)\n9 os.spawnvp(mode, file, args)\n\n```\n\n - https://security.openstack.org\n - https://docs.python.org/3/library/os.html#os.system\n - https://docs.python.org/3/library/subprocess.html#frequently-used-arguments\n - https://security.openstack.org/guidelines/dg_use-subprocess-securely.html\n - https://cwe.mitre.org/data/definitions/78.html\n\n\n CWE information added",
|
|
980
|
+
"bandit/B607:start_process_with_partial_path": "Python possesses many mechanisms to invoke an external executable. If the\ndesired executable path is not fully qualified relative to the filesystem\nroot then this may present a potential security risk.\n\nIn POSIX environments, the `PATH` environment variable is used to specify a\nset of standard locations that will be searched for the first matching\nnamed executable. While convenient, this behavior may allow a malicious\nactor to exert control over a system. If they are able to adjust the\ncontents of the `PATH` variable, or manipulate the file system, then a\nbogus executable may be discovered in place of the desired one. This\nexecutable will be invoked with the user privileges of the Python process\nthat spawned it, potentially a highly privileged user.\n\nThis test will scan the parameters of all configured Python methods,\nlooking for paths that do not start at the filesystem root, that is, do not\nhave a leading '/' character.\n\n**Config Options:**\n\nThis plugin test shares a configuration with others in the same family,\nnamely `shell_injection`. This configuration is divided up into three\nsections, `subprocess`, `shell` and `no_shell`. They each list Python calls\nthat spawn subprocesses, invoke commands within a shell, or invoke commands\nwithout a shell (by replacing the calling process) respectively.\n\nThis test will scan parameters of all methods in all sections. Note that\nmethods are fully qualified and de-aliased prior to checking.\n\n```\n\nshell_injection:\n # Start a process using the subprocess module, or one of its\n wrappers.\n subprocess:\n - subprocess.Popen\n - subprocess.call\n\n # Start a process with a function vulnerable to shell injection.\n shell:\n - os.system\n - os.popen\n - popen2.Popen3\n - popen2.Popen4\n - commands.getoutput\n - commands.getstatusoutput\n # Start a process with a function that is not vulnerable to shell\n injection.\n no_shell:\n - os.execl\n - os.execle\n\n\n```\n**Example:**\n\n```\n\n>> Issue: Starting a process with a partial executable path\nSeverity: Low Confidence: High\nCWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html)\nLocation: ./examples/partial_path_process.py:3\n2 from subprocess import Popen as pop\n3 pop('gcc --version', shell=False)\n\n```\n\n - https://security.openstack.org\n - https://docs.python.org/3/library/os.html#process-management\n - https://cwe.mitre.org/data/definitions/78.html\n\n\n CWE information added",
|
|
981
|
+
"bandit/B602:subprocess_popen_with_shell_equals_true": "Python possesses many mechanisms to invoke an external executable. However,\ndoing so may present a security issue if appropriate care is not taken to\nsanitize any user provided or variable input.\n\nThis plugin test is part of a family of tests built to check for process\nspawning and warn appropriately. Specifically, this test looks for the\nspawning of a subprocess using a command shell. This type of subprocess\ninvocation is dangerous as it is vulnerable to various shell injection\nattacks. Great care should be taken to sanitize all input in order to\nmitigate this risk. Calls of this type are identified by a parameter of\n'shell=True' being given.\n\nAdditionally, this plugin scans the command string given and adjusts its\nreported severity based on how it is presented. If the command string is a\nsimple static string containing no special shell characters, then the\nresulting issue has low severity. If the string is static, but contains\nshell formatting characters or wildcards, then the reported issue is\nmedium. Finally, if the string is computed using Python's string\nmanipulation or formatting operations, then the reported issue has high\nseverity. These severity levels reflect the likelihood that the code is\nvulnerable to injection.\n\nSee also:\n\n- :doc:`../plugins/linux_commands_wildcard_injection`\n- :doc:`../plugins/subprocess_without_shell_equals_true`\n- :doc:`../plugins/start_process_with_no_shell`\n- :doc:`../plugins/start_process_with_a_shell`\n- :doc:`../plugins/start_process_with_partial_path`\n\n**Config Options:**\n\nThis plugin test shares a configuration with others in the same family,\nnamely `shell_injection`. This configuration is divided up into three\nsections, `subprocess`, `shell` and `no_shell`. They each list Python calls\nthat spawn subprocesses, invoke commands within a shell, or invoke commands\nwithout a shell (by replacing the calling process) respectively.\n\nThis plugin specifically scans for methods listed in `subprocess` section\nthat have shell=True specified.\n\n```\n\nshell_injection:\n\n # Start a process using the subprocess module, or one of its\n wrappers.\n subprocess:\n - subprocess.Popen\n - subprocess.call\n\n\n```\n**Example:**\n\n```\n\n>> Issue: subprocess call with shell=True seems safe, but may be\nchanged in the future, consider rewriting without shell\n Severity: Low Confidence: High\n CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html)\n Location: ./examples/subprocess_shell.py:21\n20 subprocess.check_call(['/bin/ls', '-l'], shell=False)\n21 subprocess.check_call('/bin/ls -l', shell=True)\n22\n\n>> Issue: call with shell=True contains special shell characters,\nconsider moving extra logic into Python code\n Severity: Medium Confidence: High\n CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html)\n Location: ./examples/subprocess_shell.py:26\n25\n26 subprocess.Popen('/bin/ls *', shell=True)\n27 subprocess.Popen('/bin/ls %s' % ('something',), shell=True)\n\n>> Issue: subprocess call with shell=True identified, security issue.\n Severity: High Confidence: High\n CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html)\n Location: ./examples/subprocess_shell.py:27\n26 subprocess.Popen('/bin/ls *', shell=True)\n27 subprocess.Popen('/bin/ls %s' % ('something',), shell=True)\n28 subprocess.Popen('/bin/ls {}'.format('something'), shell=True)\n\n```\n\n - https://security.openstack.org\n - https://docs.python.org/3/library/subprocess.html#frequently-used-arguments\n - https://security.openstack.org/guidelines/dg_use-subprocess-securely.html\n - https://security.openstack.org/guidelines/dg_avoid-shell-true.html\n - https://cwe.mitre.org/data/definitions/78.html\n\n\n CWE information added",
|
|
982
|
+
"bandit/B603:subprocess_without_shell_equals_true": "Python possesses many mechanisms to invoke an external executable. However,\ndoing so may present a security issue if appropriate care is not taken to\nsanitize any user provided or variable input.\n\nThis plugin test is part of a family of tests built to check for process\nspawning and warn appropriately. Specifically, this test looks for the\nspawning of a subprocess without the use of a command shell. This type of\nsubprocess invocation is not vulnerable to shell injection attacks, but\ncare should still be taken to ensure validity of input.\n\nBecause this is a lesser issue than that described in\n`subprocess_popen_with_shell_equals_true` a LOW severity warning is\nreported.\n\nSee also:\n\n- :doc:`../plugins/linux_commands_wildcard_injection`\n- :doc:`../plugins/subprocess_popen_with_shell_equals_true`\n- :doc:`../plugins/start_process_with_no_shell`\n- :doc:`../plugins/start_process_with_a_shell`\n- :doc:`../plugins/start_process_with_partial_path`\n\n**Config Options:**\n\nThis plugin test shares a configuration with others in the same family,\nnamely `shell_injection`. This configuration is divided up into three\nsections, `subprocess`, `shell` and `no_shell`. They each list Python calls\nthat spawn subprocesses, invoke commands within a shell, or invoke commands\nwithout a shell (by replacing the calling process) respectively.\n\nThis plugin specifically scans for methods listed in `subprocess` section\nthat have shell=False specified.\n\n```\n\nshell_injection:\n # Start a process using the subprocess module, or one of its\n wrappers.\n subprocess:\n - subprocess.Popen\n - subprocess.call\n\n```\n**Example:**\n\n```\n\n>> Issue: subprocess call - check for execution of untrusted input.\n Severity: Low Confidence: High\n CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html)\n Location: ./examples/subprocess_shell.py:23\n22\n23 subprocess.check_output(['/bin/ls', '-l'])\n24\n\n```\n\n - https://security.openstack.org\n - https://docs.python.org/3/library/subprocess.html#frequently-used-arguments\n - https://security.openstack.org/guidelines/dg_avoid-shell-true.html\n - https://security.openstack.org/guidelines/dg_use-subprocess-securely.html\n - https://cwe.mitre.org/data/definitions/78.html\n\n\n CWE information added",
|
|
983
|
+
"bandit/B301:blacklist": "Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.\n\nFlagged calls and imports: `pickle.loads`, `pickle.load`, `pickle.Unpickler`, `dill.loads`, `dill.load`, `dill.Unpickler`, `shelve.open`, `shelve.DbfilenameShelf`, `jsonpickle.decode`, `jsonpickle.unpickler.decode`, `jsonpickle.unpickler.Unpickler`, `pandas.read_pickle`",
|
|
984
|
+
"bandit/B302:blacklist": "Deserialization with the marshal module is possibly dangerous.\n\nFlagged calls and imports: `marshal.load`, `marshal.loads`",
|
|
985
|
+
"bandit/B303:blacklist": "Use of insecure MD2, MD4, MD5, or SHA1 hash function.\n\nFlagged calls and imports: `Crypto.Hash.MD2.new`, `Crypto.Hash.MD4.new`, `Crypto.Hash.MD5.new`, `Crypto.Hash.SHA.new`, `Cryptodome.Hash.MD2.new`, `Cryptodome.Hash.MD4.new`, `Cryptodome.Hash.MD5.new`, `Cryptodome.Hash.SHA.new`, `cryptography.hazmat.primitives.hashes.MD5`, `cryptography.hazmat.primitives.hashes.SHA1`",
|
|
986
|
+
"bandit/B304:blacklist": "Use of insecure cipher {name}. Replace with a known secure cipher such as AES.\n\nFlagged calls and imports: `Crypto.Cipher.ARC2.new`, `Crypto.Cipher.ARC4.new`, `Crypto.Cipher.Blowfish.new`, `Crypto.Cipher.DES.new`, `Crypto.Cipher.XOR.new`, `Cryptodome.Cipher.ARC2.new`, `Cryptodome.Cipher.ARC4.new`, `Cryptodome.Cipher.Blowfish.new`, `Cryptodome.Cipher.DES.new`, `Cryptodome.Cipher.XOR.new`, `cryptography.hazmat.primitives.ciphers.algorithms.ARC4`, `cryptography.hazmat.primitives.ciphers.algorithms.Blowfish`, `cryptography.hazmat.primitives.ciphers.algorithms.CAST5`, `cryptography.hazmat.primitives.ciphers.algorithms.IDEA`, `cryptography.hazmat.primitives.ciphers.algorithms.SEED`, `cryptography.hazmat.primitives.ciphers.algorithms.TripleDES`",
|
|
987
|
+
"bandit/B305:blacklist": "Use of insecure cipher mode {name}.\n\nFlagged calls and imports: `cryptography.hazmat.primitives.ciphers.modes.ECB`",
|
|
988
|
+
"bandit/B306:blacklist": "Use of insecure and deprecated function (mktemp).\n\nFlagged calls and imports: `tempfile.mktemp`",
|
|
989
|
+
"bandit/B307:blacklist": "Use of possibly insecure function - consider using safer ast.literal_eval.\n\nFlagged calls and imports: `eval`",
|
|
990
|
+
"bandit/B308:blacklist": "Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.\n\nFlagged calls and imports: `django.utils.safestring.mark_safe`",
|
|
991
|
+
"bandit/B310:blacklist": "Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.\n\nFlagged calls and imports: `urllib.request.urlopen`, `urllib.request.urlretrieve`, `urllib.request.URLopener`, `urllib.request.FancyURLopener`, `six.moves.urllib.request.urlopen`, `six.moves.urllib.request.urlretrieve`, `six.moves.urllib.request.URLopener`, `six.moves.urllib.request.FancyURLopener`",
|
|
992
|
+
"bandit/B311:blacklist": "Standard pseudo-random generators are not suitable for security/cryptographic purposes.\n\nFlagged calls and imports: `random.Random`, `random.random`, `random.randrange`, `random.randint`, `random.choice`, `random.choices`, `random.uniform`, `random.triangular`, `random.randbytes`, `random.sample`, `random.randrange`, `random.getrandbits`",
|
|
993
|
+
"bandit/B312:blacklist": "Telnet-related functions are being called. Telnet is considered insecure. Use SSH or some other encrypted protocol.\n\nFlagged calls and imports: `telnetlib.Telnet`",
|
|
994
|
+
"bandit/B313:blacklist": "Using {name} to parse untrusted XML data is known to be vulnerable to XML attacks. Replace {name} with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called\n\nFlagged calls and imports: `xml.etree.cElementTree.parse`, `xml.etree.cElementTree.iterparse`, `xml.etree.cElementTree.fromstring`, `xml.etree.cElementTree.XMLParser`",
|
|
995
|
+
"bandit/B314:blacklist": "Using {name} to parse untrusted XML data is known to be vulnerable to XML attacks. Replace {name} with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called\n\nFlagged calls and imports: `xml.etree.ElementTree.parse`, `xml.etree.ElementTree.iterparse`, `xml.etree.ElementTree.fromstring`, `xml.etree.ElementTree.XMLParser`",
|
|
996
|
+
"bandit/B315:blacklist": "Using {name} to parse untrusted XML data is known to be vulnerable to XML attacks. Replace {name} with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called\n\nFlagged calls and imports: `xml.sax.expatreader.create_parser`",
|
|
997
|
+
"bandit/B316:blacklist": "Using {name} to parse untrusted XML data is known to be vulnerable to XML attacks. Replace {name} with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called\n\nFlagged calls and imports: `xml.dom.expatbuilder.parse`, `xml.dom.expatbuilder.parseString`",
|
|
998
|
+
"bandit/B317:blacklist": "Using {name} to parse untrusted XML data is known to be vulnerable to XML attacks. Replace {name} with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called\n\nFlagged calls and imports: `xml.sax.parse`, `xml.sax.parseString`, `xml.sax.make_parser`",
|
|
999
|
+
"bandit/B318:blacklist": "Using {name} to parse untrusted XML data is known to be vulnerable to XML attacks. Replace {name} with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called\n\nFlagged calls and imports: `xml.dom.minidom.parse`, `xml.dom.minidom.parseString`",
|
|
1000
|
+
"bandit/B319:blacklist": "Using {name} to parse untrusted XML data is known to be vulnerable to XML attacks. Replace {name} with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called\n\nFlagged calls and imports: `xml.dom.pulldom.parse`, `xml.dom.pulldom.parseString`",
|
|
1001
|
+
"bandit/B321:blacklist": "FTP-related functions are being called. FTP is considered insecure. Use SSH/SFTP/SCP or some other encrypted protocol.\n\nFlagged calls and imports: `ftplib.FTP`",
|
|
1002
|
+
"bandit/B323:blacklist": "By default, Python will create a secure, verified ssl context for use in such classes as HTTPSConnection. However, it still allows using an insecure context via the _create_unverified_context that reverts to the previous behavior that does not validate certificates or perform hostname checks.\n\nFlagged calls and imports: `ssl._create_unverified_context`",
|
|
1003
|
+
"bandit/B401:blacklist": "A telnet-related module is being imported. Telnet is considered insecure. Use SSH or some other encrypted protocol.\n\nFlagged calls and imports: `telnetlib`",
|
|
1004
|
+
"bandit/B402:blacklist": "A FTP-related module is being imported. FTP is considered insecure. Use SSH/SFTP/SCP or some other encrypted protocol.\n\nFlagged calls and imports: `ftplib`",
|
|
1005
|
+
"bandit/B403:blacklist": "Consider possible security implications associated with {name} module.\n\nFlagged calls and imports: `pickle`, `cPickle`, `dill`, `shelve`",
|
|
1006
|
+
"bandit/B404:blacklist": "Consider possible security implications associated with the subprocess module.\n\nFlagged calls and imports: `subprocess`",
|
|
1007
|
+
"bandit/B405:blacklist": "Using {name} to parse untrusted XML data is known to be vulnerable to XML attacks. Replace {name} with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.\n\nFlagged calls and imports: `xml.etree.cElementTree`, `xml.etree.ElementTree`",
|
|
1008
|
+
"bandit/B406:blacklist": "Using {name} to parse untrusted XML data is known to be vulnerable to XML attacks. Replace {name} with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.\n\nFlagged calls and imports: `xml.sax`",
|
|
1009
|
+
"bandit/B407:blacklist": "Using {name} to parse untrusted XML data is known to be vulnerable to XML attacks. Replace {name} with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.\n\nFlagged calls and imports: `xml.dom.expatbuilder`",
|
|
1010
|
+
"bandit/B408:blacklist": "Using {name} to parse untrusted XML data is known to be vulnerable to XML attacks. Replace {name} with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.\n\nFlagged calls and imports: `xml.dom.minidom`",
|
|
1011
|
+
"bandit/B409:blacklist": "Using {name} to parse untrusted XML data is known to be vulnerable to XML attacks. Replace {name} with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.\n\nFlagged calls and imports: `xml.dom.pulldom`",
|
|
1012
|
+
"bandit/B411:blacklist": "Using {name} to parse untrusted XML data is known to be vulnerable to XML attacks. Use defusedxml.xmlrpc.monkey_patch() function to monkey-patch xmlrpclib and mitigate XML vulnerabilities.\n\nFlagged calls and imports: `xmlrpc`",
|
|
1013
|
+
"bandit/B412:blacklist": "Consider possible security implications associated with {name} module.\n\nFlagged calls and imports: `wsgiref.handlers.CGIHandler`, `twisted.web.twcgi.CGIScript`, `twisted.web.twcgi.CGIDirectory`",
|
|
1014
|
+
"bandit/B413:blacklist": "The pyCrypto library and its module {name} are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.\n\nFlagged calls and imports: `Crypto.Cipher`, `Crypto.Hash`, `Crypto.IO`, `Crypto.Protocol`, `Crypto.PublicKey`, `Crypto.Random`, `Crypto.Signature`, `Crypto.Util`",
|
|
1015
|
+
"bandit/B415:blacklist": "An IPMI-related module is being imported. IPMI is considered insecure. Use an encrypted protocol.\n\nFlagged calls and imports: `pyghmi`",
|
|
1016
|
+
"eslint/constructor-super": "Constructors of derived classes must call `super()`.\nConstructors of non derived classes must not call `super()`.\nIf this is not observed, the JavaScript engine will raise a runtime error.\n\nThis rule checks whether or not there is a valid `super()` call.\n\n## Rule Details\n\nThis rule is aimed to flag invalid/missing `super()` calls.\n\nThis is a syntax error because there is no `extends` clause in the class:\n\n```js\nclass A {\n constructor() {\n super();\n }\n}\n```\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint constructor-super: \"error\"*/\n\nclass A extends B {\n constructor() { } // Would throw a ReferenceError.\n}\n\n// Classes which inherits from a non constructor are always problems.\nclass C extends null {\n constructor() {\n super(); // Would throw a TypeError.\n }\n}\n\nclass D extends null {\n constructor() { } // Would throw a ReferenceError.\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint constructor-super: \"error\"*/\n\nclass A {\n constructor() { }\n}\n\nclass B extends C {\n constructor() {\n super();\n }\n}\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nIf you don't want to be notified about invalid/missing `super()` callings in constructors, you can safely disable this rule.",
|
|
1017
|
+
"eslint/for-direction": "A `for` loop with a stop condition that can never be reached, such as one with a counter that moves in the wrong direction, will run infinitely. While there are occasions when an infinite loop is intended, the convention is to construct such loops as `while` loops. More typically, an infinite `for` loop is a bug.\n\n## Rule Details\n\nThis rule forbids `for` loops where the counter variable changes in such a way that the stop condition will never be met. For example, if the counter variable is increasing (i.e. `i++`) and the stop condition tests that the counter is greater than zero (`i >= 0`) then the loop will never exit.\n\n> **Note:** This rule only checks the **direction** of the counter relative to the stop condition. It does not check the actual values to determine whether the loop will execute at least once. For example, a loop like `for (let i = 0; i < 0; i++) {}` is considered valid by this rule because the counter direction (`i++`) matches the condition (`i <`), even though the condition is false from the start (dead code).\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint for-direction: \"error\"*/\nfor (let i = 0; i < 10; i--) {\n}\n\nfor (let i = 10; i >= 0; i++) {\n}\n\nfor (let i = 0; i > 10; i++) {\n // counter i is on the left with >, so i++ (increasing) is the wrong direction\n}\n\nfor (let i = 0; i > 0; i++) {\n // counter i is on the left with >, so i++ (increasing) is the wrong direction\n}\n\nfor (let i = 0; 0 < i; i++) {\n // counter i is on the right with <, so i++ (increasing) is the wrong direction\n}\n\nfor (let i = 0; 10 > i; i--) {\n}\n\nconst n = -2;\nfor (let i = 0; i < 10; i += n) {\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint for-direction: \"error\"*/\nfor (let i = 0; i < 10; i++) {\n}\n\nfor (let i = 0; 10 > i; i++) { // with counter \"i\" on the right\n}\n\nfor (let i = 10; i >= 0; i += this.step) { // direction unknown\n}\n\nfor (let i = MIN; i <= MAX; i -= 0) { // not increasing or decreasing\n}\n\nfor (let i = 0; i < 0; i++) {\n // counter i is on the left with <, so i++ (increasing) is the correct direction\n // (loop never executes, but direction is consistent)\n}\n\nfor (let i = 0; 0 > i; i++) {\n // counter i is on the right with >, so i++ (increasing) is the correct direction\n // (loop never executes, but direction is consistent)\n}\n```\n\n\n## Options\n\nThis rule has no options.",
|
|
1018
|
+
"eslint/getter-return": "The get syntax binds an object property to a function that will be called when that property is looked up. It was first introduced in ECMAScript 5:\n\n```js\nconst p = {\n get name(){\n return \"nicholas\";\n }\n};\n\nObject.defineProperty(p, \"age\", {\n get: function (){\n return 17;\n }\n});\n```\n\nNote that every `getter` is expected to return a value.\n\n## Rule Details\n\nThis rule enforces that a return statement is present in property getters.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint getter-return: \"error\"*/\n\nconst p = {\n get name(){\n // no returns.\n }\n};\n\nObject.defineProperty(p, \"age\", {\n get: function (){\n // no returns.\n }\n});\n\nclass P{\n get name(){\n // no returns.\n }\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint getter-return: \"error\"*/\n\nconst p = {\n get name(){\n return \"nicholas\";\n }\n};\n\nObject.defineProperty(p, \"age\", {\n get: function (){\n return 18;\n }\n});\n\nclass P{\n get name(){\n return \"nicholas\";\n }\n}\n```\n\n\n## Options\n\nThis rule has an object option:\n\n* `\"allowImplicit\": false` (default) disallows implicitly returning `undefined` with a `return` statement.\n\nExamples of **correct** code for the `{ \"allowImplicit\": true }` option:\n\n**Correct code:**\n\n```js\n/*eslint getter-return: [\"error\", { allowImplicit: true }]*/\nconst p = {\n get name(){\n return; // return undefined implicitly.\n }\n};\n```\n\n\n## When Not To Use It\n\nIf your project will not be using ES5 property getters you do not need this rule.",
|
|
1019
|
+
"eslint/no-async-promise-executor": "The `new Promise` constructor accepts an *executor* function as an argument, which has `resolve` and `reject` parameters that can be used to control the state of the created Promise. For example:\n\n```js\nconst result = new Promise(function executor(resolve, reject) {\n readFile('foo.txt', function(err, result) {\n if (err) {\n reject(err);\n } else {\n resolve(result);\n }\n });\n});\n```\n\nThe executor function can also be an `async function`. However, this is usually a mistake, for a few reasons:\n\n* If an async executor function throws an error, the error will be lost and won't cause the newly-constructed `Promise` to reject. This could make it difficult to debug and handle some errors.\n* If a Promise executor function is using `await`, this is usually a sign that it is not actually necessary to use the `new Promise` constructor, or the scope of the `new Promise` constructor can be reduced.\n\n## Rule Details\n\nThis rule aims to disallow async Promise executor functions.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-async-promise-executor: \"error\"*/\n\nconst foo = new Promise(async (resolve, reject) => {\n readFile('foo.txt', function(err, result) {\n if (err) {\n reject(err);\n } else {\n resolve(result);\n }\n });\n});\n\nconst result = new Promise(async (resolve, reject) => {\n resolve(await foo);\n});\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-async-promise-executor: \"error\"*/\n\nconst foo = new Promise((resolve, reject) => {\n readFile('foo.txt', function(err, result) {\n if (err) {\n reject(err);\n } else {\n resolve(result);\n }\n });\n});\n\nconst result = Promise.resolve(foo);\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nIf your codebase doesn't support `async function` syntax, there's no need to enable this rule.",
|
|
1020
|
+
"eslint/no-case-declarations": "This rule disallows lexical declarations (`let`, `const`, `function` and `class`)\nin `case`/`default` clauses. The reason is that the lexical declaration is visible\nin the entire `switch` block but it only gets initialized when it is assigned, which\nwill only happen if the `case` where it is defined is reached.\n\nTo ensure that the lexical declaration only applies to the current `case` clause\nwrap your clauses in blocks.\n\n## Rule Details\n\nThis rule aims to prevent access to uninitialized lexical bindings as well as accessing hoisted functions across `case` clauses.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-case-declarations: \"error\"*/\n\nswitch (foo) {\n case 1:\n let x = 1;\n break;\n case 2:\n const y = 2;\n break;\n case 3:\n function f() {}\n break;\n default:\n class C {}\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-case-declarations: \"error\"*/\n\n// Declarations outside switch-statements are valid\nconst a = 0;\n\nswitch (foo) {\n // The following case clauses are wrapped into blocks using brackets\n case 1: {\n let x = 1;\n break;\n }\n case 2: {\n const y = 2;\n break;\n }\n case 3: {\n function f() {}\n break;\n }\n case 4:\n // Declarations using var without brackets are valid due to function-scope hoisting\n var z = 4;\n break;\n default: {\n class C {}\n }\n}\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nIf you depend on fall through behavior and want access to bindings introduced in the `case` block.",
|
|
1021
|
+
"eslint/no-class-assign": "`ClassDeclaration` creates a variable, and we can modify the variable.\n\n```js\nclass A { }\nA = 0;\n```\n\nBut the modification is a mistake in most cases.\n\n## Rule Details\n\nThis rule is aimed to flag modifying variables of class declarations.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-class-assign: \"error\"*/\n\nclass A { }\nA = 0;\n```\n\n\n**Incorrect code:**\n\n```js\n/*eslint no-class-assign: \"error\"*/\n\nA = 0;\nclass A { }\n```\n\n\n**Incorrect code:**\n\n```js\n/*eslint no-class-assign: \"error\"*/\n\nclass A {\n b() {\n A = 0;\n }\n}\n```\n\n\n**Incorrect code:**\n\n```js\n/*eslint no-class-assign: \"error\"*/\n\nlet A = class A {\n b() {\n A = 0;\n // `let A` is shadowed by the class name.\n }\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-class-assign: \"error\"*/\n\nlet A = class A { }\nA = 0; // A is a variable.\n```\n\n\n**Correct code:**\n\n```js\n/*eslint no-class-assign: \"error\"*/\n\nlet A = class {\n b() {\n A = 0; // A is a variable.\n }\n}\n```\n\n\n**Correct code:**\n\n```js\n/*eslint no-class-assign: 2*/\n\nclass A {\n b(A) {\n A = 0; // A is a parameter.\n }\n}\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nIf you don't want to be notified about modifying variables of class declarations, you can safely disable this rule.",
|
|
1022
|
+
"eslint/no-compare-neg-zero": "## Rule Details\n\nThe rule should warn against code that tries to compare against `-0`, since that will not work as intended. That is, code like `x === -0` will pass for both `+0` and `-0`. The author probably intended `Object.is(x, -0)`.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/* eslint no-compare-neg-zero: \"error\" */\n\nif (x === -0) {\n // doSomething()...\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/* eslint no-compare-neg-zero: \"error\" */\n\nif (x === 0) {\n // doSomething()...\n}\n```\n\n\n**Correct code:**\n\n```js\n/* eslint no-compare-neg-zero: \"error\" */\n\nif (Object.is(x, -0)) {\n // doSomething()...\n}\n```\n\n\n## Options\n\nThis rule has no options.",
|
|
1023
|
+
"eslint/no-cond-assign": "In conditional statements, it is very easy to mistype a comparison operator (such as `==`) as an assignment operator (such as `=`). For example:\n\n```js\n// Check the user's job title\nif (user.jobTitle = \"manager\") {\n // user.jobTitle is now incorrect\n}\n```\n\nThere are valid reasons to use assignment operators in conditional statements. However, it can be difficult to tell whether a specific assignment was intentional.\n\n## Rule Details\n\nThis rule disallows ambiguous assignment operators in test conditions of `if`, `for`, `while`, and `do...while` statements.\n\n## Options\n\nThis rule has a string option:\n\n* `\"except-parens\"` (default) allows assignments in test conditions *only if* they are enclosed in parentheses (for example, to allow reassigning a variable in the test of a `while` or `do...while` loop).\n* `\"always\"` disallows all assignments in test conditions.\n\n### except-parens\n\nExamples of **incorrect** code for this rule with the default `\"except-parens\"` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-cond-assign: \"error\"*/\n\n// Unintentional assignment\nlet x;\nif (x = 0) {\n const b = 1;\n}\n\n// Practical example that is similar to an error\nconst setHeight = function (someNode) {\n do {\n someNode.height = \"100px\";\n } while (someNode = someNode.parentNode);\n}\n```\n\n\nExamples of **correct** code for this rule with the default `\"except-parens\"` option:\n\n**Correct code:**\n\n```js\n/*eslint no-cond-assign: \"error\"*/\n\n// Assignment replaced by comparison\nlet x;\nif (x === 0) {\n const b = 1;\n}\n\n// Practical example that wraps the assignment in parentheses\nconst setHeight = function (someNode) {\n do {\n someNode.height = \"100px\";\n } while ((someNode = someNode.parentNode));\n}\n\n// Practical example that wraps the assignment and tests for 'null'\nconst set_height = function (someNode) {\n do {\n someNode.height = \"100px\";\n } while ((someNode = someNode.parentNode) !== null);\n}\n```\n\n\n### always\n\nExamples of **incorrect** code for this rule with the `\"always\"` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-cond-assign: [\"error\", \"always\"]*/\n\n// Unintentional assignment\nlet x;\nif (x = 0) {\n const b = 1;\n}\n\n// Practical example that is similar to an error\nconst setHeight = function (someNode) {\n do {\n someNode.height = \"100px\";\n } while (someNode = someNode.parentNode);\n}\n\n// Practical example that wraps the assignment in parentheses\nconst set_height = function (someNode) {\n do {\n someNode.height = \"100px\";\n } while ((someNode = someNode.parentNode));\n}\n\n// Practical example that wraps the assignment and tests for 'null'\nconst heightSetter = function (someNode) {\n do {\n someNode.height = \"100px\";\n } while ((someNode = someNode.parentNode) !== null);\n}\n```\n\n\nExamples of **correct** code for this rule with the `\"always\"` option:\n\n**Correct code:**\n\n```js\n/*eslint no-cond-assign: [\"error\", \"always\"]*/\n\n// Assignment replaced by comparison\nlet x;\nif (x === 0) {\n const b = 1;\n}\n```",
|
|
1024
|
+
"eslint/no-const-assign": "Constant bindings cannot be modified. An attempt to modify a constant binding will raise a runtime error.\n\n## Rule Details\n\nThis rule is aimed to flag modifying variables that are declared using `const`, `using`, or `await using` keywords.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-const-assign: \"error\"*/\n\nconst a = 0;\na = 1;\n```\n\n\n**Incorrect code:**\n\n```js\n/*eslint no-const-assign: \"error\"*/\n\nconst a = 0;\na += 1;\n```\n\n\n**Incorrect code:**\n\n```js\n/*eslint no-const-assign: \"error\"*/\n\nconst a = 0;\n++a;\n```\n\n\n**Incorrect code:**\n\n```js\n/*eslint no-const-assign: \"error\"*/\n\nif (foo) {\n\tusing a = getSomething();\n\ta = somethingElse;\n}\n\nif (bar) {\n\tawait using a = getSomething();\n\ta = somethingElse;\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-const-assign: \"error\"*/\n\nconst a = 0;\nconsole.log(a);\n```\n\n\n**Correct code:**\n\n```js\n/*eslint no-const-assign: \"error\"*/\n\nif (foo) {\n\tusing a = getSomething();\n\ta.execute();\n}\n\nif (bar) {\n\tawait using a = getSomething();\n\ta.execute();\n}\n```\n\n\n**Correct code:**\n\n```js\n/*eslint no-const-assign: \"error\"*/\n\nfor (const a in [1, 2, 3]) { // `a` is re-defined (not modified) on each loop step.\n console.log(a);\n}\n```\n\n\n**Correct code:**\n\n```js\n/*eslint no-const-assign: \"error\"*/\n\nfor (const a of [1, 2, 3]) { // `a` is re-defined (not modified) on each loop step.\n console.log(a);\n}\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nIf you don't want to be notified about modifying variables that are declared using `const`, `using`, and `await using` keywords, you can safely disable this rule.",
|
|
1025
|
+
"eslint/no-constant-binary-expression": "Comparisons which will always evaluate to true or false and logical expressions (`||`, `&&`, `??`) which either always short-circuit or never short-circuit are both likely indications of programmer error.\n\nThese errors are especially common in complex expressions where operator precedence is easy to misjudge. For example:\n\n```js\n// One might think this would evaluate as `a + (b ?? c)`:\nconst x = a + b ?? c;\n\n// But it actually evaluates as `(a + b) ?? c`. Since `a + b` can never be null,\n// the `?? c` has no effect.\n```\n\nAdditionally, this rule detects comparisons to newly constructed objects/arrays/functions/etc. In JavaScript, where objects are compared by reference, a newly constructed object can _never_ `===` any other value. This can be surprising for programmers coming from languages where objects are compared by value.\n\n```js\n// Programmers coming from a language where objects are compared by value might expect this to work:\nconst isEmpty = x === [];\n\n// However, this will always result in `isEmpty` being `false`.\n```\n\n## Rule Details\n\nThis rule identifies `==` and `===` comparisons which, based on the semantics of the JavaScript language, will always evaluate to `true` or `false`.\n\nIt also identifies `||`, `&&` and `??` logical expressions which will either always or never short-circuit. Additionally, when configured with the `checkRelationalComparisons` option, it can identify constant relational comparisons (such as `<` or `>=`).\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-constant-binary-expression: \"error\"*/\n\nconst value1 = +x == null;\n\nconst value2 = condition ? x : {} || DEFAULT;\n\nconst value3 = !foo == null;\n\nconst value4 = new Boolean(foo) === true;\n\nconst objIsEmpty = someObj === {};\n\nconst arrIsEmpty = someArr === [];\n\nconst shortCircuit1 = condition1 && false && condition2;\n\nconst shortCircuit2 = condition1 || true || condition2;\n\nconst shortCircuit3 = condition1 ?? \"non-nullish\" ?? condition2;\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-constant-binary-expression: \"error\"*/\n\nconst value1 = x == null;\n\nconst value2 = (condition ? x : {}) || DEFAULT;\n\nconst value3 = !(foo == null);\n\nconst value4 = Boolean(foo) === true;\n\nconst objIsEmpty = Object.keys(someObj).length === 0;\n\nconst arrIsEmpty = someArr.length === 0;\n```\n\n\n## Options\n\nThis rule has an object option:\n\n* `\"checkRelationalComparisons\": true` (default `false`) checks for relational comparisons (`<`, `<=`, `>`, `>=`) where both sides are literal values.\n\n### checkRelationalComparisons\n\nExamples of **incorrect** code for this rule with the `{ \"checkRelationalComparisons\": true }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-constant-binary-expression: [\"error\", { \"checkRelationalComparisons\": true } ]*/\n\nconst value1 = 1 < 2;\n\nconst value2 = \"a\" >= \"b\";\n\nconst value3 = true > false;\n\nconst hasStreak = profile.streak ?? 0 > 1;\n```\n\n\nExamples of **correct** code for this rule with the `{ \"checkRelationalComparisons\": true }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-constant-binary-expression: [\"error\", { \"checkRelationalComparisons\": true } ]*/\n\nconst value1 = 1 < x;\n\nconst value2 = a >= b;\n\nconst hasStreak = (profile.streak ?? 0) > 1;\n```",
|
|
1026
|
+
"eslint/no-constant-condition": "A constant expression (for example, a literal) as a test condition might be a typo or development trigger for a specific behavior. For example, the following code looks as if it is not ready for production.\n\n```js\nif (false) {\n doSomethingUnfinished();\n}\n```\n\n## Rule Details\n\nThis rule disallows constant expressions in the test condition of:\n\n* `if`, `for`, `while`, or `do...while` statement\n* `?:` ternary expression\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-constant-condition: \"error\"*/\n\nif (false) {\n doSomethingUnfinished();\n}\n\nif (void x) {\n doSomethingUnfinished();\n}\n\nif (x &&= false) {\n doSomethingNever();\n}\n\nif (class {}) {\n doSomethingAlways();\n}\n\nif (new Boolean(x)) {\n doSomethingAlways();\n}\n\nif (Boolean(1)) {\n doSomethingAlways();\n}\n\nif (undefined) {\n doSomethingUnfinished();\n}\n\nif (x ||= true) {\n doSomethingAlways();\n}\n\nfor (;-2;) {\n doSomethingForever();\n}\n\nwhile (typeof x) {\n doSomethingForever();\n}\n\ndo {\n doSomethingForever();\n} while (x = -1);\n\nconst result = 0 ? a : b;\n\nif(input === \"hello\" || \"bye\"){\n output(input);\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-constant-condition: \"error\"*/\n\nif (x === 0) {\n doSomething();\n}\n\nfor (;;) {\n doSomethingForever();\n}\n\nwhile (typeof x === \"undefined\") {\n doSomething();\n}\n\ndo {\n doSomething();\n} while (x);\n\nconst result = x !== 0 ? a : b;\n\nif(input === \"hello\" || input === \"bye\"){\n output(input);\n}\n```\n\n\n## Options\n\n### checkLoops\n\nThis is a string option having following values:\n\n* `\"all\"` - Disallow constant expressions in all loops.\n* `\"allExceptWhileTrue\"` (default) - Disallow constant expressions in all loops except `while` loops with expression `true`.\n* `\"none\"` - Allow constant expressions in loops.\n\nOr instead you can set the `checkLoops` value to booleans where `true` is same as `\"all\"` and `false` is same as `\"none\"`.\n\nExamples of **incorrect** code for when `checkLoops` is `\"all\"` or `true`:\n\n**Incorrect code:**\n\n```js\n/*eslint no-constant-condition: [\"error\", { \"checkLoops\": \"all\" }]*/\n\nwhile (true) {\n doSomething();\n};\n\nfor (;true;) {\n doSomething();\n};\n```\n\n\n**Incorrect code:**\n\n```js\n/*eslint no-constant-condition: [\"error\", { \"checkLoops\": true }]*/\n\nwhile (true) {\n doSomething();\n};\n\ndo {\n doSomething();\n} while (true)\n```\n\n\nExamples of **correct** code for when `checkLoops` is `\"all\"` or `true`:\n\n**Correct code:**\n\n```js\n/*eslint no-constant-condition: [\"error\", { \"checkLoops\": \"all\" }]*/\n\nwhile (a === b) {\n doSomething();\n};\n```\n\n\n**Correct code:**\n\n```js\n/*eslint no-constant-condition: [\"error\", { \"checkLoops\": true }]*/\n\nfor (let x = 0; x <= 10; x++) {\n doSomething();\n};\n```\n\n\nExample of **correct** code for when `checkLoops` is `\"allExceptWhileTrue\"`:\n\n**Correct code:**\n\n```js\n/*eslint no-constant-condition: \"error\"*/\n\nwhile (true) {\n doSomething();\n};\n```\n\n\nExamples of **correct** code for when `checkLoops` is `\"none\"` or `false`:\n\n**Correct code:**\n\n```js\n/*eslint no-constant-condition: [\"error\", { \"checkLoops\": \"none\" }]*/\n\nwhile (true) {\n doSomething();\n if (condition()) {\n break;\n }\n};\n\ndo {\n doSomething();\n if (condition()) {\n break;\n }\n} while (true)\n```\n\n\n**Correct code:**\n\n```js\n/*eslint no-constant-condition: [\"error\", { \"checkLoops\": false }]*/\n\nwhile (true) {\n doSomething();\n if (condition()) {\n break;\n }\n};\n\nfor (;true;) {\n doSomething();\n if (condition()) {\n break;\n }\n};\n```",
|
|
1027
|
+
"eslint/no-control-regex": "Control characters are special, invisible characters in the ASCII range 0-31. These characters are rarely used in JavaScript strings so a regular expression containing elements that explicitly match these characters is most likely a mistake.\n\n## Rule Details\n\nThis rule disallows control characters and some escape sequences that match control characters in regular expressions.\n\nThe following elements of regular expression patterns are considered possible errors in typing and are therefore disallowed by this rule:\n\n* Hexadecimal character escapes from `\\x00` to `\\x1F`.\n* Unicode character escapes from `\\u0000` to `\\u001F`.\n* Unicode code point escapes from `\\u{0}` to `\\u{1F}`.\n* Unescaped raw characters from U+0000 to U+001F.\n\nControl escapes such as `\\t` and `\\n` are allowed by this rule. Control letter escapes such as `\\cA`-`\\cZ` (and `\\ca`-`\\cz`) are also allowed, since writing a control character this way makes the intent to match a control character explicit, unlike the hexadecimal, Unicode, and raw forms above, which can obscure that intent.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-control-regex: \"error\"*/\n\nconst pattern1 = /\\x00/;\nconst pattern2 = /\\x0C/;\nconst pattern3 = /\\x1F/;\nconst pattern4 = /\\u000C/;\nconst pattern5 = /\\u{C}/u;\nconst pattern6 = new RegExp(\"\\x0C\"); // raw U+000C character in the pattern\nconst pattern7 = new RegExp(\"\\\\x0C\"); // \\x0C pattern\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-control-regex: \"error\"*/\n\nconst pattern1 = /\\x20/;\nconst pattern2 = /\\u0020/;\nconst pattern3 = /\\u{20}/u;\nconst pattern4 = /\\t/;\nconst pattern5 = /\\n/;\nconst pattern6 = new RegExp(\"\\x20\");\nconst pattern7 = new RegExp(\"\\\\t\");\nconst pattern8 = new RegExp(\"\\\\n\");\nconst pattern9 = /\\cJ/; // control letter escape for U+000A\n```\n\n\n## Options\n\nThis rule has no options.\n\n## Known Limitations\n\nWhen checking `RegExp` constructor calls, this rule examines evaluated regular expression patterns. Therefore, although this rule intends to allow syntax such as `\\t`, it doesn't allow `new RegExp(\"\\t\")` since the evaluated pattern (string value of `\"\\t\"`) contains a raw control character (the TAB character).\n\n```js\n/*eslint no-control-regex: \"error\"*/\n\nnew RegExp(\"\\t\"); // disallowed since the pattern is: <TAB>\n\nnew RegExp(\"\\\\t\"); // allowed since the pattern is: \\t\n```\n\nThere is no difference in behavior between `new RegExp(\"\\t\")` and `new RegExp(\"\\\\t\")`, and the intention to match the TAB character is clear in both cases. They are equally valid for the purpose of this rule, but it only allows `new RegExp(\"\\\\t\")`.\n\n## When Not To Use It\n\nIf you need to use control character pattern matching, then you should turn this rule off.",
|
|
1028
|
+
"eslint/no-debugger": "The `debugger` statement is used to tell the executing JavaScript environment to stop execution and start up a debugger at the current point in the code. This has fallen out of favor as a good practice with the advent of modern debugging and development tools. Production code should definitely not contain `debugger`, as it will cause the browser to stop executing code and open an appropriate debugger.\n\n## Rule Details\n\nThis rule disallows `debugger` statements.\n\nExample of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-debugger: \"error\"*/\n\nfunction isTruthy(x) {\n debugger;\n return Boolean(x);\n}\n```\n\n\nExample of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-debugger: \"error\"*/\n\nfunction isTruthy(x) {\n return Boolean(x); // set a breakpoint at this line\n}\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nIf your code is still very much in development and don't want to worry about stripping `debugger` statements, then turn this rule off. You'll generally want to turn it back on when testing code prior to deployment.",
|
|
1029
|
+
"eslint/no-delete-var": "The purpose of the `delete` operator is to remove a property from an object. Using the `delete` operator on a variable might lead to unexpected behavior.\n\n## Rule Details\n\nThis rule disallows the use of the `delete` operator on variables.\n\nIf ESLint parses code in strict mode, the parser (instead of this rule) reports the error.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-delete-var: \"error\"*/\n\nlet x;\ndelete x;\n```\n\n\n## Options\n\nThis rule has no options.",
|
|
1030
|
+
"eslint/no-dupe-args": "If more than one parameter has the same name in a function definition, the last occurrence \"shadows\" the preceding occurrences. A duplicated name might be a typing error.\n\n## Rule Details\n\nThis rule disallows duplicate parameter names in function declarations or expressions. It does not apply to arrow functions or class methods, because the parser reports the error.\n\nIf ESLint parses code in strict mode, the parser (instead of this rule) reports the error.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-dupe-args: \"error\"*/\n\nfunction foo(a, b, a) {\n console.log(\"value of the second a:\", a);\n}\n\nconst bar = function (a, b, a) {\n console.log(\"value of the second a:\", a);\n};\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-dupe-args: \"error\"*/\n\nfunction foo(a, b, c) {\n console.log(a, b, c);\n}\n\nconst bar = function (a, b, c) {\n console.log(a, b, c);\n};\n```\n\n\n## Options\n\nThis rule has no options.",
|
|
1031
|
+
"eslint/no-dupe-class-members": "If there are declarations of the same name in class members, the last declaration overwrites other declarations silently.\nIt can cause unexpected behaviors.\n\n```js\nclass Foo {\n bar() { console.log(\"hello\"); }\n bar() { console.log(\"goodbye\"); }\n}\n\nconst foo = new Foo();\nfoo.bar(); // goodbye\n```\n\n## Rule Details\n\nThis rule is aimed to flag the use of duplicate names in class members.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-dupe-class-members: \"error\"*/\n\nclass A {\n bar() { }\n bar() { }\n}\n\nclass B {\n bar() { }\n get bar() { }\n}\n\nclass C {\n bar;\n bar;\n}\n\nclass D {\n bar;\n bar() { }\n}\n\nclass E {\n static bar() { }\n static bar() { }\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-dupe-class-members: \"error\"*/\n\nclass A {\n bar() { }\n qux() { }\n}\n\nclass B {\n get bar() { }\n set bar(value) { }\n}\n\nclass C {\n bar;\n qux;\n}\n\nclass D {\n bar;\n qux() { }\n}\n\nclass E {\n static bar() { }\n bar() { }\n}\n```\n\n\nThis rule additionally supports TypeScript type syntax. It has support for TypeScript's method overload definitions.\n\nExamples of **correct** TypeScript code for this rule:\n\n**Correct code:**\n\n```ts\n/* eslint no-dupe-class-members: \"error\" */\n\nclass A {\n\tfoo(value: string): void;\n\tfoo(value: number): void;\n\tfoo(value: string | number) {} // \u2705 This is the actual implementation.\n}\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nThis rule should not be used in ES3/5 environments.\n\nIn ES2015 (ES6) or later, if you don't want to be notified about duplicate names in class members, you can safely disable this rule.",
|
|
1032
|
+
"eslint/no-dupe-else-if": "`if-else-if` chains are commonly used when there is a need to execute only one branch (or at most one branch) out of several possible branches, based on certain conditions.\n\n```js\nif (a) {\n foo();\n} else if (b) {\n bar();\n} else if (c) {\n baz();\n}\n```\n\nTwo identical test conditions in the same chain are almost always a mistake in the code. Unless there are side effects in the expressions, a duplicate will evaluate to the same `true` or `false` value as the identical expression earlier in the chain, meaning that its branch can never execute.\n\n```js\nif (a) {\n foo();\n} else if (b) {\n bar();\n} else if (b) {\n baz();\n}\n```\n\nIn the above example, `baz()` can never execute. Obviously, `baz()` could be executed only when `b` evaluates to `true`, but in that case `bar()` would be executed instead, since it's earlier in the chain.\n\n## Rule Details\n\nThis rule disallows duplicate conditions in the same `if-else-if` chain.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-dupe-else-if: \"error\"*/\n\nif (isSomething(x)) {\n foo();\n} else if (isSomething(x)) {\n bar();\n}\n\nif (a) {\n foo();\n} else if (b) {\n bar();\n} else if (c && d) {\n baz();\n} else if (c && d) {\n quux();\n} else {\n quuux();\n}\n\nif (n === 1) {\n foo();\n} else if (n === 2) {\n bar();\n} else if (n === 3) {\n baz();\n} else if (n === 2) {\n quux();\n} else if (n === 5) {\n quuux();\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-dupe-else-if: \"error\"*/\n\nif (isSomething(x)) {\n foo();\n} else if (isSomethingElse(x)) {\n bar();\n}\n\nif (a) {\n foo();\n} else if (b) {\n bar();\n} else if (c && d) {\n baz();\n} else if (c && e) {\n quux();\n} else {\n quuux();\n}\n\nif (n === 1) {\n foo();\n} else if (n === 2) {\n bar();\n} else if (n === 3) {\n baz();\n} else if (n === 4) {\n quux();\n} else if (n === 5) {\n quuux();\n}\n```\n\n\nThis rule can also detect some cases where the conditions are not identical, but the branch can never execute due to the logic of `||` and `&&` operators.\n\nExamples of additional **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-dupe-else-if: \"error\"*/\n\nif (a || b) {\n foo();\n} else if (a) {\n bar();\n}\n\nif (a) {\n foo();\n} else if (b) {\n bar();\n} else if (a || b) {\n baz();\n}\n\nif (a) {\n foo();\n} else if (a && b) {\n bar();\n}\n\nif (a && b) {\n foo();\n} else if (a && b && c) {\n bar();\n}\n\nif (a || b) {\n foo();\n} else if (b && c) {\n bar();\n}\n\nif (a) {\n foo();\n} else if (b && c) {\n bar();\n} else if (d && (c && e && b || a)) {\n baz();\n}\n```\n\n\nPlease note that this rule does not compare conditions from the chain with conditions inside statements, and will not warn in the cases such as follows:\n\n```js\nif (a) {\n if (a) {\n foo();\n }\n}\n\nif (a) {\n foo();\n} else {\n if (a) {\n bar();\n }\n}\n```\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nIn rare cases where you really need identical test conditions in the same chain, which necessarily means that the expressions in the chain are causing and relying on side effects, you will have to turn this rule off.",
|
|
1033
|
+
"eslint/no-dupe-keys": "Multiple properties with the same key in object literals can cause unexpected behavior in your application.\n\n```js\nconst foo = {\n bar: \"baz\",\n bar: \"qux\"\n};\n```\n\n## Rule Details\n\nThis rule disallows duplicate keys in object literals.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-dupe-keys: \"error\"*/\n\nconst foo = {\n bar: \"baz\",\n bar: \"qux\"\n};\n\nconst bar = {\n \"bar\": \"baz\",\n bar: \"qux\"\n};\n\nconst baz = {\n 0x1: \"baz\",\n 1: \"qux\"\n};\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-dupe-keys: \"error\"*/\n\nconst foo = {\n bar: \"baz\",\n quxx: \"qux\"\n};\n\nconst obj = {\n \"__proto__\": baz, // defines object's prototype\n [\"__proto__\"]: qux // defines a property named \"__proto__\"\n};\n```\n\n\n## Options\n\nThis rule has no options.",
|
|
1034
|
+
"eslint/no-duplicate-case": "If a `switch` statement has duplicate test expressions in `case` clauses, it is likely that a programmer copied a `case` clause but forgot to change the test expression.\n\n## Rule Details\n\nThis rule disallows duplicate test expressions in `case` clauses of `switch` statements.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-duplicate-case: \"error\"*/\n\nconst a = 1,\n one = 1;\n\nswitch (a) {\n case 1:\n break;\n case 2:\n break;\n case 1: // duplicate test expression\n break;\n default:\n break;\n}\n\nswitch (a) {\n case one:\n break;\n case 2:\n break;\n case one: // duplicate test expression\n break;\n default:\n break;\n}\n\nswitch (a) {\n case \"1\":\n break;\n case \"2\":\n break;\n case \"1\": // duplicate test expression\n break;\n default:\n break;\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-duplicate-case: \"error\"*/\n\nconst a = 1,\n one = 1;\n\nswitch (a) {\n case 1:\n break;\n case 2:\n break;\n case 3:\n break;\n default:\n break;\n}\n\nswitch (a) {\n case one:\n break;\n case 2:\n break;\n case 3:\n break;\n default:\n break;\n}\n\nswitch (a) {\n case \"1\":\n break;\n case \"2\":\n break;\n case \"3\":\n break;\n default:\n break;\n}\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nIn rare cases where identical test expressions in `case` clauses produce different values, which necessarily means that the expressions are causing and relying on side effects, you will have to disable this rule.\n\n```js\nswitch (a) {\n case i++:\n foo();\n break;\n case i++: // eslint-disable-line no-duplicate-case\n bar();\n break;\n}\n```",
|
|
1035
|
+
"eslint/no-empty": "Empty block statements, while not technically errors, usually occur due to refactoring that wasn't completed. They can cause confusion when reading code.\n\n## Rule Details\n\nThis rule disallows empty block statements. This rule ignores block statements which contain a comment (for example, in an empty `catch` or `finally` block of a `try` statement to indicate that execution should continue regardless of errors).\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-empty: \"error\"*/\n\nif (foo) {\n}\n\nwhile (foo) {\n}\n\nswitch(foo) {\n}\n\ntry {\n doSomething();\n} catch(ex) {\n\n} finally {\n\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-empty: \"error\"*/\n\nif (foo) {\n // empty\n}\n\nwhile (foo) {\n /* empty */\n}\n\nswitch(foo) {\n /* empty */\n}\n\ntry {\n doSomething();\n} catch (ex) {\n // continue regardless of error\n}\n\ntry {\n doSomething();\n} finally {\n /* continue regardless of error */\n}\n```\n\n\n## Options\n\nThis rule has an object option for exceptions:\n\n* `\"allowEmptyCatch\": true` allows empty `catch` clauses (that is, which do not contain a comment)\n\n### allowEmptyCatch\n\nExamples of additional **correct** code for this rule with the `{ \"allowEmptyCatch\": true }` option:\n\n**Correct code:**\n\n```js\n/* eslint no-empty: [\"error\", { \"allowEmptyCatch\": true }] */\ntry {\n doSomething();\n} catch (ex) {}\n\ntry {\n doSomething();\n}\ncatch (ex) {}\nfinally {\n /* continue regardless of error */\n}\n```\n\n\n## When Not To Use It\n\nIf you intentionally use empty block statements then you can disable this rule.",
|
|
1036
|
+
"eslint/no-empty-character-class": "Because empty character classes in regular expressions do not match anything, they might be typing mistakes.\n\n```js\nconst foo = /^abc[]/;\n```\n\n## Rule Details\n\nThis rule disallows empty character classes in regular expressions.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-empty-character-class: \"error\"*/\n\n/^abc[]/.test(\"abcdefg\"); // false\n\"abcdefg\".match(/^abc[]/); // null\n\n/^abc[[]]/v.test(\"abcdefg\"); // false\n\"abcdefg\".match(/^abc[[]]/v); // null\n\n/^abc[[]--[x]]/v.test(\"abcdefg\"); // false\n\"abcdefg\".match(/^abc[[]--[x]]/v); // null\n\n/^abc[[d]&&[]]/v.test(\"abcdefg\"); // false\n\"abcdefg\".match(/^abc[[d]&&[]]/v); // null\n\nconst regex = /^abc[d[]]/v;\nregex.test(\"abcdefg\"); // true, the nested `[]` has no effect\n\"abcdefg\".match(regex); // [\"abcd\"]\nregex.test(\"abcefg\"); // false, the nested `[]` has no effect\n\"abcefg\".match(regex); // null\nregex.test(\"abc\"); // false, the nested `[]` has no effect\n\"abc\".match(regex); // null\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-empty-character-class: \"error\"*/\n\n/^abc/.test(\"abcdefg\"); // true\n\"abcdefg\".match(/^abc/); // [\"abc\"]\n\n/^abc[a-z]/.test(\"abcdefg\"); // true\n\"abcdefg\".match(/^abc[a-z]/); // [\"abcd\"]\n\n/^abc[^]/.test(\"abcdefg\"); // true\n\"abcdefg\".match(/^abc[^]/); // [\"abcd\"]\n```\n\n\n## Options\n\nThis rule has no options.\n\n## Known Limitations\n\nThis rule does not report empty character classes in the string argument of calls to the `RegExp` constructor.\n\nExample of a *false negative* when this rule reports correct code:\n\n```js\n/*eslint no-empty-character-class: \"error\"*/\n\nconst abcNeverMatches = new RegExp(\"^abc[]\");\n```",
|
|
1037
|
+
"eslint/no-empty-pattern": "When using destructuring, it's possible to create a pattern that has no effect. This happens when empty curly braces are used to the right of an embedded object destructuring pattern, such as:\n\n```js\n// doesn't create any variables\nconst {a: {}} = foo;\n```\n\nIn this code, no new variables are created because `a` is just a location helper while the `{}` is expected to contain the variables to create, such as:\n\n```js\n// creates variable b\nconst {a: { b }} = foo;\n```\n\nIn many cases, the empty object pattern is a mistake where the author intended to use a default value instead, such as:\n\n```js\n// creates variable a\nconst {a = {}} = foo;\n```\n\nThe difference between these two patterns is subtle, especially because the problematic empty pattern looks just like an object literal.\n\n## Rule Details\n\nThis rule aims to flag any empty patterns in destructured objects and arrays, and as such, will report a problem whenever one is encountered.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-empty-pattern: \"error\"*/\n\nconst {} = foo;\nconst [] = foo;\nconst {a: {}} = foo;\nconst {a: []} = foo;\nfunction foo({}) {}\nfunction bar([]) {}\nfunction baz({a: {}}) {}\nfunction qux({a: []}) {}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-empty-pattern: \"error\"*/\n\nconst {a = {}} = foo;\nconst {b = []} = foo;\nfunction foo({a = {}}) {}\nfunction bar({a = []}) {}\n```\n\n\n## Options\n\nThis rule has an object option for exceptions:\n\n### allowObjectPatternsAsParameters\n\nSet to `false` by default. Setting this option to `true` allows empty object patterns as function parameters.\n\n**Note:** This rule doesn't allow empty array patterns as function parameters.\n\nExamples of **incorrect** code for this rule with the `{\"allowObjectPatternsAsParameters\": true}` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-empty-pattern: [\"error\", { \"allowObjectPatternsAsParameters\": true }]*/\n\nfunction foo({a: {}}) {}\nconst bar = function({a: {}}) {};\nconst qux = ({a: {}}) => {};\nconst quux = ({} = bar) => {};\nconst item = ({} = { bar: 1 }) => {};\n\nfunction baz([]) {}\n```\n\n\nExamples of **correct** code for this rule with the `{\"allowObjectPatternsAsParameters\": true}` option:\n\n**Correct code:**\n\n```js\n/*eslint no-empty-pattern: [\"error\", { \"allowObjectPatternsAsParameters\": true }]*/\n\nfunction foo({}) {}\nconst bar = function({}) {};\nconst qux = ({}) => {};\n\nfunction baz({} = {}) {}\n```",
|
|
1038
|
+
"eslint/no-empty-static-block": "Empty static blocks, while not technically errors, usually occur due to refactoring that wasn't completed. They can cause confusion when reading code.\n\n## Rule Details\n\nThis rule disallows empty static blocks. This rule ignores static blocks which contain a comment.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-empty-static-block: \"error\"*/\n\nclass Foo {\n static {}\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-empty-static-block: \"error\"*/\n\nclass Foo {\n static {\n bar();\n }\n}\n\nclass Bar {\n static {\n // comment\n }\n}\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nThis rule should not be used in environments prior to ES2022.",
|
|
1039
|
+
"eslint/no-ex-assign": "If a `catch` clause in a `try` statement accidentally (or purposely) assigns another value to the exception parameter, it is impossible to refer to the error from that point on.\nSince there is no `arguments` object to offer alternative access to this data, assignment of the parameter is absolutely destructive.\n\n## Rule Details\n\nThis rule disallows reassigning exceptions in `catch` clauses.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-ex-assign: \"error\"*/\n\ntry {\n // code\n} catch (e) {\n e = 10;\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-ex-assign: \"error\"*/\n\ntry {\n // code\n} catch (e) {\n const foo = 10;\n}\n```\n\n\n## Options\n\nThis rule has no options.",
|
|
1040
|
+
"eslint/no-extra-boolean-cast": "In contexts such as an `if` statement's test where the result of the expression will already be coerced to a Boolean, casting to a Boolean via double negation (`!!`) or a `Boolean` call is unnecessary. For example, these `if` statements are equivalent:\n\n```js\nif (!!foo) {\n // ...\n}\n\nif (Boolean(foo)) {\n // ...\n}\n\nif (foo) {\n // ...\n}\n```\n\n## Rule Details\n\nThis rule disallows unnecessary boolean casts.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-extra-boolean-cast: \"error\"*/\n\nconst foo = !!!bar;\n\nconst foo1 = !!bar ? baz : bat;\n\nconst foo2 = Boolean(!!bar);\n\nconst foo3 = new Boolean(!!bar);\n\nif (!!foo) {\n // ...\n}\n\nif (Boolean(foo)) {\n // ...\n}\n\nwhile (!!foo) {\n // ...\n}\n\ndo {\n // ...\n} while (Boolean(foo));\n\nfor (; !!foo; ) {\n // ...\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-extra-boolean-cast: \"error\"*/\n\nconst foo = !!bar;\nconst foo1 = Boolean(bar);\n\nfunction qux() {\n return !!bar;\n}\n\nfoo = bar ? !!baz : !!bat;\n```\n\n\n## Options\n\nThis rule has an object option:\n\n* `\"enforceForInnerExpressions\"` when set to `true`, in addition to checking default contexts, checks whether extra boolean casts are present in expressions whose result is used in a boolean context. See examples below. Default is `false`, meaning that this rule by default does not warn about extra booleans cast inside inner expressions.\n\n**Deprecated:** The object property `enforceForLogicalOperands` is deprecated ([eslint#18222](https://github.com/eslint/eslint/pull/18222)). Please use `enforceForInnerExpressions` instead.\n\n### enforceForInnerExpressions\n\nExamples of **incorrect** code for this rule with `\"enforceForInnerExpressions\"` option set to `true`:\n\n**Incorrect code:**\n\n```js\n/*eslint no-extra-boolean-cast: [\"error\", {\"enforceForInnerExpressions\": true}]*/\n\nif (!!foo || bar) {\n //...\n}\n\nwhile (!!foo && bar) {\n //...\n}\n\nif ((!!foo || bar) && !!baz) {\n //...\n}\n\nconst foo = new Boolean(!!bar || baz);\n\nfoo && Boolean(bar) ? baz : bat;\n\nconst ternaryBranches = Boolean(bar ? !!baz : bat);\n\nconst nullishCoalescingOperator = Boolean(bar ?? Boolean(baz));\n\nconst commaOperator = Boolean((bar, baz, !!bat));\n\n// another comma operator example\nfor (let i = 0; console.log(i), Boolean(i < 10); i++) {\n // ...\n}\n```\n\n\nExamples of **correct** code for this rule with `\"enforceForInnerExpressions\"` option set to `true`:\n\n**Correct code:**\n\n```js\n/*eslint no-extra-boolean-cast: [\"error\", {\"enforceForInnerExpressions\": true}]*/\n\n// Note that `||` and `&&` alone aren't a boolean context for either operand\n// since the resultant value need not be a boolean without casting.\nconst foo = !!bar || baz;\n\nif (foo || bar) {\n //...\n}\n\nwhile (foo && bar) {\n //...\n}\n\nif ((foo || bar) && baz) {\n //...\n}\n\nconst foo1 = new Boolean(bar || baz);\n\nfoo && bar ? baz : bat;\n\nconst ternaryBranches = Boolean(bar ? baz : bat);\n\nconst nullishCoalescingOperator = Boolean(bar ?? baz);\n\nconst commaOperator = Boolean((bar, baz, bat));\n\n// another comma operator example\nfor (let i = 0; console.log(i), i < 10; i++) {\n // ...\n}\n\n// comma operator in non-final position\nBoolean((Boolean(bar), baz, bat));\n```",
|
|
1041
|
+
"eslint/no-fallthrough": "The `switch` statement in JavaScript is one of the more error-prone constructs of the language thanks in part to the ability to \"fall through\" from one `case` to the next. For example:\n\n```js\nswitch(foo) {\n case 1:\n doSomething();\n\n case 2:\n doSomethingElse();\n}\n```\n\nIn this example, if `foo` is `1`, then execution will flow through both cases, as the first falls through to the second. You can prevent this by using `break`, as in this example:\n\n```js\nswitch(foo) {\n case 1:\n doSomething();\n break;\n\n case 2:\n doSomethingElse();\n}\n```\n\nThat works fine when you don't want a fallthrough, but what if the fallthrough is intentional, there is no way to indicate that in the language. It's considered a best practice to always indicate when a fallthrough is intentional using a comment which matches the `/falls?\\s?through/i` regular expression but isn't a directive:\n\n```js\nswitch(foo) {\n case 1:\n doSomething();\n // falls through\n\n case 2:\n doSomethingElse();\n}\n\nswitch(foo) {\n case 1:\n doSomething();\n // fall through\n\n case 2:\n doSomethingElse();\n}\n\nswitch(foo) {\n case 1:\n doSomething();\n // fallsthrough\n\n case 2:\n doSomethingElse();\n}\n\nswitch(foo) {\n case 1: {\n doSomething();\n // falls through\n }\n\n case 2: {\n doSomethingElse();\n }\n}\n```\n\nIn this example, there is no confusion as to the expected behavior. It is clear that the first case is meant to fall through to the second case.\n\n## Rule Details\n\nThis rule is aimed at eliminating unintentional fallthrough of one case to the other. As such, it flags any fallthrough scenarios that are not marked by a comment.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-fallthrough: \"error\"*/\n\nswitch(foo) {\n case 1:\n doSomething();\n\n case 2:\n doSomething();\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-fallthrough: \"error\"*/\n\nswitch(foo) {\n case 1:\n doSomething();\n break;\n\n case 2:\n doSomething();\n}\n\nfunction bar(foo) {\n switch(foo) {\n case 1:\n doSomething();\n return;\n\n case 2:\n doSomething();\n }\n}\n\nswitch(foo) {\n case 1:\n doSomething();\n throw new Error(\"Boo!\");\n\n case 2:\n doSomething();\n}\n\nswitch(foo) {\n case 1:\n case 2:\n doSomething();\n}\n\nswitch(foo) {\n case 1: case 2:\n doSomething();\n}\n\nswitch(foo) {\n case 1:\n doSomething();\n // falls through\n\n case 2:\n doSomething();\n}\n\nswitch(foo) {\n case 1: {\n doSomething();\n // falls through\n }\n\n case 2: {\n doSomethingElse();\n }\n}\n```\n\n\nNote that the last `case` statement in these examples does not cause a warning because there is nothing to fall through into.\n\n## Options\n\nThis rule has an object option:\n\n* Set the `commentPattern` option to a regular expression string to change the test for intentional fallthrough comment. If the fallthrough comment matches a directive, that takes precedence over `commentPattern`.\n\n* Set the `allowEmptyCase` option to `true` to allow empty cases regardless of the layout. By default, this rule does not require a fallthrough comment after an empty `case` only if the empty `case` and the next `case` are on the same line or on consecutive lines.\n\n* Set the `reportUnusedFallthroughComment` option to `true` to prohibit a fallthrough comment from being present if the case cannot fallthrough due to being unreachable. This is mostly intended to help avoid misleading comments occurring as a result of refactoring.\n\n### commentPattern\n\nExamples of **correct** code for the `{ \"commentPattern\": \"break[\\\\s\\\\w]*omitted\" }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-fallthrough: [\"error\", { \"commentPattern\": \"break[\\\\s\\\\w]*omitted\" }]*/\n\nswitch(foo) {\n case 1:\n doSomething();\n // break omitted\n\n case 2:\n doSomething();\n}\n\nswitch(foo) {\n case 1:\n doSomething();\n // caution: break is omitted intentionally\n\n default:\n doSomething();\n}\n```\n\n\n### allowEmptyCase\n\nExamples of **correct** code for the `{ \"allowEmptyCase\": true }` option:\n\n**Correct code:**\n\n```js\n/* eslint no-fallthrough: [\"error\", { \"allowEmptyCase\": true }] */\n\nswitch(foo){\n case 1:\n\n case 2: doSomething();\n}\n\nswitch(foo){\n case 1:\n /*\n Put a message here \n */\n case 2: doSomething();\n}\n\n```\n\n\n### reportUnusedFallthroughComment\n\nExamples of **incorrect** code for the `{ \"reportUnusedFallthroughComment\": true }` option:\n\n**Incorrect code:**\n\n```js\n/* eslint no-fallthrough: [\"error\", { \"reportUnusedFallthroughComment\": true }] */\n\nswitch(foo){\n case 1:\n doSomething();\n break;\n // falls through\n case 2: doSomething();\n}\n\nfunction f() {\n switch(foo){\n case 1:\n if (a) {\n throw new Error();\n } else if (b) {\n break;\n } else {\n return;\n }\n // falls through\n case 2:\n break;\n }\n}\n```\n\n\nExamples of **correct** code for the `{ \"reportUnusedFallthroughComment\": true }` option:\n\n**Correct code:**\n\n```js\n/* eslint no-fallthrough: [\"error\", { \"reportUnusedFallthroughComment\": true }] */\n\nswitch(foo){\n case 1:\n doSomething();\n break;\n // just a comment\n case 2: doSomething();\n}\n```\n\n\n## When Not To Use It\n\nIf you don't want to enforce that each `case` statement should end with a `throw`, `return`, `break`, or comment, then you can safely turn this rule off.",
|
|
1042
|
+
"eslint/no-func-assign": "JavaScript functions can be written as a FunctionDeclaration `function foo() { ... }` or as a FunctionExpression `const foo = function() { ... };`. While a JavaScript interpreter might tolerate it, overwriting/reassigning a function written as a FunctionDeclaration is often indicative of a mistake or issue.\n\n```js\nfunction foo() {}\nfoo = bar;\n```\n\n## Rule Details\n\nThis rule disallows reassigning `function` declarations.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-func-assign: \"error\"*/\n\nfunction foo() {}\nfoo = bar;\n\nfunction baz() {\n baz = bar;\n}\n\nlet a = function hello() {\n hello = 123;\n};\n```\n\n\nExamples of **incorrect** code for this rule, unlike the corresponding rule in JSHint:\n\n**Incorrect code:**\n\n```js\n/*eslint no-func-assign: \"error\"*/\n\nfoo = bar;\nfunction foo() {}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-func-assign: \"error\"*/\n\nlet foo = function () {}\nfoo = bar;\n\nfunction baz(baz) { // `baz` is shadowed.\n baz = bar;\n}\n\nfunction qux() {\n const qux = bar; // `qux` is shadowed.\n}\n```\n\n\n## Options\n\nThis rule has no options.",
|
|
1043
|
+
"eslint/no-global-assign": "JavaScript environments contain a number of built-in global variables, such as `window` in browsers and `process` in Node.js. In almost all cases, you don't want to assign a value to these global variables as doing so could result in losing access to important functionality. For example, you probably don't want to do this in browser code:\n\n```js\nwindow = {};\n```\n\nWhile examples such as `window` are obvious, there are often hundreds of built-in global objects provided by JavaScript environments. It can be hard to know if you're assigning to a global variable or not.\n\n## Rule Details\n\nThis rule disallows modifications to read-only global variables.\n\nESLint has the capability to configure global variables as read-only.\n\nSee also: [Specify Globals](../use/configure/language-options#specify-globals)\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-global-assign: \"error\"*/\n\nObject = null\nundefined = 1\n```\n\n\n**Incorrect code:**\n\n```js\n/*eslint no-global-assign: \"error\"*/\n/*global window:readonly*/\n\nwindow = {}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-global-assign: \"error\"*/\n\na = 1\nlet b = 1\nb = 2\n```\n\n\n**Correct code:**\n\n```js\n/*eslint no-global-assign: \"error\"*/\n/*global onload:writable*/\n\nonload = function() {}\n```\n\n\n## Options\n\nThis rule accepts an `exceptions` option, which can be used to specify a list of builtins for which reassignments will be allowed:\n\n```json\n{\n \"rules\": {\n \"no-global-assign\": [\"error\", {\"exceptions\": [\"Object\"]}]\n }\n}\n```\n\n## When Not To Use It\n\nIf you are trying to override one of the native objects.",
|
|
1044
|
+
"eslint/no-import-assign": "The updates of imported bindings by ES Modules cause runtime errors.\n\n## Rule Details\n\nThis rule warns the assignments, increments, and decrements of imported bindings.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-import-assign: \"error\"*/\n\nimport mod, { named } from \"./mod.mjs\"\nimport * as mod_ns from \"./mod.mjs\"\n\nmod = 1 // ERROR: 'mod' is readonly.\nnamed = 2 // ERROR: 'named' is readonly.\nmod_ns.named = 3 // ERROR: The members of 'mod_ns' are readonly.\nmod_ns = {} // ERROR: 'mod_ns' is readonly.\n// Can't extend 'mod_ns'\nObject.assign(mod_ns, { foo: \"foo\" }) // ERROR: The members of 'mod_ns' are readonly.\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-import-assign: \"error\"*/\n\nimport mod, { named } from \"./mod.mjs\"\nimport * as mod_ns from \"./mod.mjs\"\n\nmod.prop = 1\nnamed.prop = 2\nmod_ns.named.prop = 3\n\n// Known Limitation\nfunction test(obj) {\n obj.named = 4 // Not errored because 'obj' is not namespace objects.\n}\ntest(mod_ns) // Not errored because it doesn't know that 'test' updates the member of the argument.\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nIf you don't want to be notified about modifying imported bindings, you can disable this rule.",
|
|
1045
|
+
"eslint/no-invalid-regexp": "An invalid pattern in a regular expression literal is a `SyntaxError` when the code is parsed, but an invalid string in `RegExp` constructors throws a `SyntaxError` only when the code is executed.\n\n## Rule Details\n\nThis rule disallows invalid regular expression strings in `RegExp` constructors.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-invalid-regexp: \"error\"*/\n\nRegExp('[')\n\nRegExp('.', 'z')\n\nnew RegExp('\\\\')\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-invalid-regexp: \"error\"*/\n\nRegExp('.')\n\nnew RegExp\n\nthis.RegExp('[')\n```\n\n\nPlease note that this rule validates regular expressions per the latest ECMAScript specification, regardless of your parser settings.\n\nIf you want to allow additional constructor flags for any reason, you can specify them using the `allowConstructorFlags` option. These flags will then be ignored by the rule.\n\n## Options\n\nThis rule has an object option for exceptions:\n\n* `\"allowConstructorFlags\"` is a case-sensitive array of flags\n\n### allowConstructorFlags\n\nExamples of **correct** code for this rule with the `{ \"allowConstructorFlags\": [\"a\", \"z\"] }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-invalid-regexp: [\"error\", { \"allowConstructorFlags\": [\"a\", \"z\"] }]*/\n\nnew RegExp('.', 'a')\n\nnew RegExp('.', 'az')\n```",
|
|
1046
|
+
"eslint/no-irregular-whitespace": "Invalid or irregular whitespace causes issues with ECMAScript 5 parsers and also makes code harder to debug in a similar nature to mixed tabs and spaces.\n\nVarious whitespace characters can be inputted by programmers by mistake for example from copying or keyboard shortcuts. Pressing Alt + Space on macOS adds in a non breaking space character for example.\n\nA simple fix for this problem could be to rewrite the offending line from scratch. This might also be a problem introduced by the text editor: if rewriting the line does not fix it, try using a different editor.\n\nKnown issues these spaces cause:\n\n* Ogham Space Mark\n * Is a valid token separator, but is rendered as a visible glyph in most typefaces, which may be misleading in source code.\n* Mongolian Vowel Separator\n * Is no longer considered a space separator since Unicode 6.3. It will result in a syntax error in current parsers when used in place of a regular token separator.\n* Line Separator and Paragraph Separator\n * These have always been valid whitespace characters and line terminators, but were considered illegal in string literals prior to ECMAScript 2019.\n* Zero Width Space\n * Is NOT considered a separator for tokens and is often parsed as an `Unexpected token ILLEGAL`.\n * Is NOT shown in modern browsers making code repository software expected to resolve the visualization.\n\nIn JSON, none of the characters listed as irregular whitespace by this rule may appear outside of a string.\n\n## Rule Details\n\nThis rule is aimed at catching invalid whitespace that is not a normal tab and space. Some of these characters may cause issues in modern browsers and others will be a debugging issue to spot.\n\nThis rule disallows the following characters except where the options allow:\n\n```text\n\\u000B - Line Tabulation (\\v) - <VT>\n\\u000C - Form Feed (\\f) - <FF>\n\\u0085 - Next Line - <NEL>\n\\u00A0 - No-Break Space - <NBSP>\n\\u1680 - Ogham Space Mark - <OGSP>\n\\u180E - Mongolian Vowel Separator - <MVS>\n\\u2000 - En Quad - <NQSP>\n\\u2001 - Em Quad - <MQSP>\n\\u2002 - En Space - <ENSP>\n\\u2003 - Em Space - <EMSP>\n\\u2004 - Three-Per-Em - <THPMSP> - <3/MSP>\n\\u2005 - Four-Per-Em - <FPMSP> - <4/MSP>\n\\u2006 - Six-Per-Em - <SPMSP> - <6/MSP>\n\\u2007 - Figure Space - <FSP>\n\\u2008 - Punctuation Space - <PUNCSP>\n\\u2009 - Thin Space - <THSP>\n\\u200A - Hair Space - <HSP>\n\\u200B - Zero Width Space - <ZWSP>\n\\u2028 - Line Separator - <LS> - <LSEP>\n\\u2029 - Paragraph Separator - <PS> - <PSEP>\n\\u202F - Narrow No-Break Space - <NNBSP>\n\\u205F - Medium Mathematical Space - <MMSP>\n\\u3000 - Ideographic Space - <IDSP>\n\\uFEFF - Zero Width No-Break Space - <BOM>\n```\n\n## Options\n\nThis rule has an object option for exceptions:\n\n* `\"skipStrings\": true` (default) allows any whitespace characters in string literals\n* `\"skipComments\": true` allows any whitespace characters in comments\n* `\"skipRegExps\": true` allows any whitespace characters in regular expression literals\n* `\"skipTemplates\": true` allows any whitespace characters in template literals\n* `\"skipJSXText\": true` allows any whitespace characters in JSX text\n\n### skipStrings\n\nExamples of **incorrect** code for this rule with the default `{ \"skipStrings\": true }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-irregular-whitespace: \"error\"*/\n\nconst thing = function()\u00a0/*<NBSP>*/{\n return 'test';\n}\n\nconst foo = function(\u00a0/*<NBSP>*/){\n return 'test';\n}\n\nconst bar = function\u00a0/*<NBSP>*/(){\n return 'test';\n}\n\nconst baz = function\u1680/*<Ogham Space Mark>*/(){\n return 'test';\n}\n\nconst qux = function() {\n return 'test';\u2002/*<ENSP>*/\n}\n\nconst quux = function() {\n return 'test';\u00a0/*<NBSP>*/\n}\n\nconst item = function() {\n // Description\u00a0<NBSP>: some descriptive text\n}\n\n/*\nDescription\u00a0<NBSP>: some descriptive text\n*/\n\nconst func = function() {\n return /\u00a0<NBSP>regexp/;\n}\n\nconst myFunc = function() {\n return `template\u2002<NBSP>string`;\n}\n```\n\n\nExamples of **correct** code for this rule with the default `{ \"skipStrings\": true }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-irregular-whitespace: \"error\"*/\n\nconst thing = function() {\n return '\u00a0<NBSP>thing';\n}\n\nconst foo = function() {\n return '\u200b<ZWSP>thing';\n}\n\nconst bar = function() {\n return 'th\u00a0<NBSP>ing';\n}\n```\n\n\n### skipComments\n\nExamples of additional **correct** code for this rule with the `{ \"skipComments\": true }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-irregular-whitespace: [\"error\", { \"skipComments\": true }]*/\n\nfunction thing() {\n // Description\u00a0<NBSP>: some descriptive text\n}\n\n/*\nDescription\u00a0<NBSP>: some descriptive text\n*/\n```\n\n\n### skipRegExps\n\nExamples of additional **correct** code for this rule with the `{ \"skipRegExps\": true }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-irregular-whitespace: [\"error\", { \"skipRegExps\": true }]*/\n\nfunction thing() {\n return /\u00a0<NBSP>regexp/;\n}\n```\n\n\n### skipTemplates\n\nExamples of additional **correct** code for this rule with the `{ \"skipTemplates\": true }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-irregular-whitespace: [\"error\", { \"skipTemplates\": true }]*/\n\nfunction thing() {\n return `template\u2002<NBSP>string`;\n}\n```\n\n\n### skipJSXText\n\nExamples of additional **correct** code for this rule with the `{ \"skipJSXText\": true }` option:\n\n**Correct code:**\n\n```jsx\n/*eslint no-irregular-whitespace: [\"error\", { \"skipJSXText\": true }]*/\n\nfunction Thing() {\n return <div>text in\u2002JSX</div>; // <NBSP> before `JSX`\n}\n```\n\n\n## When Not To Use It\n\nIf you decide that you wish to use whitespace other than tabs and spaces outside of strings in your application.",
|
|
1047
|
+
"eslint/no-loss-of-precision": "This rule would disallow the use of number literals that lose precision at runtime when converted to a JS `Number` due to 64-bit floating-point rounding.\n\n## Rule Details\n\nIn JS, `Number`s are stored as double-precision floating-point numbers according to the [IEEE 754 standard](https://en.wikipedia.org/wiki/IEEE_754). Because of this, numbers can only retain accuracy up to a certain amount of digits. If the programmer enters additional digits, those digits will be lost in the conversion to the `Number` type and will result in unexpected behavior.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-loss-of-precision: \"error\"*/\n\nconst a = 9007199254740993\nconst b = 5123000000000000000000000000001\nconst c = 1230000000000000000000000.0\nconst d = .1230000000000000000000000\nconst e = 0X20000000000001\nconst f = 0X2_000000000_0001;\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-loss-of-precision: \"error\"*/\n\nconst a = 12345\nconst b = 123.456\nconst c = 123e34\nconst d = 12300000000000000000000000\nconst e = 0x1FFFFFFFFFFFFF\nconst f = 9007199254740991\nconst g = 9007_1992547409_91\n```\n\n\n## Options\n\nThis rule has no options.",
|
|
1048
|
+
"eslint/no-misleading-character-class": "Unicode includes characters which are made by multiple code points.\nRegExp character class syntax (`/[abc]/`) cannot handle characters which are made by multiple code points as a character; those characters will be dissolved to each code point. For example, `\u2747\ufe0f` is made by `\u2747` (`U+2747`) and VARIATION SELECTOR-16 (`U+FE0F`). If this character is in a RegExp character class, it will match either `\u2747` (`U+2747`) or VARIATION SELECTOR-16 (`U+FE0F`) rather than `\u2747\ufe0f`.\n\nThis rule reports regular expressions which include multiple code point characters in character class syntax. This rule considers the following characters as multiple code point characters.\n\n**A character with combining characters:**\n\nThe combining characters are characters which belong to one of `Mc`, `Me`, and `Mn` [Unicode general categories](https://www.unicode.org/L2/L1999/UnicodeData.html#General%20Category).\n\n```js\n/^[A\u0301]$/u.test(\"A\u0301\"); //\u2192 false\n/^[\u2747\ufe0f]$/u.test(\"\u2747\ufe0f\"); //\u2192 false\n```\n\n**A character with Emoji modifiers:**\n\n```js\n/^[\ud83d\udc76\ud83c\udffb]$/u.test(\"\ud83d\udc76\ud83c\udffb\"); //\u2192 false\n/^[\ud83d\udc76\ud83c\udffd]$/u.test(\"\ud83d\udc76\ud83c\udffd\"); //\u2192 false\n```\n\n**A pair of regional indicator symbols:**\n\n```js\n/^[\ud83c\uddef\ud83c\uddf5]$/u.test(\"\ud83c\uddef\ud83c\uddf5\"); //\u2192 false\n```\n\n**Characters that ZWJ joins:**\n\n```js\n/^[\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc66]$/u.test(\"\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc66\"); //\u2192 false\n```\n\n**A surrogate pair without Unicode flag:**\n\n```js\n/^[\ud83d\udc4d]$/.test(\"\ud83d\udc4d\"); //\u2192 false\n\n// Surrogate pair is OK if with u flag.\n/^[\ud83d\udc4d]$/u.test(\"\ud83d\udc4d\"); //\u2192 true\n```\n\n## Rule Details\n\nThis rule reports regular expressions which include multiple code point characters in character class syntax.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-misleading-character-class: error */\n\n/^[A\u0301]$/u;\n/^[\u2747\ufe0f]$/u;\n/^[\ud83d\udc76\ud83c\udffb]$/u;\n/^[\ud83c\uddef\ud83c\uddf5]$/u;\n/^[\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc66]$/u;\n/^[\ud83d\udc4d]$/;\nnew RegExp(\"[\ud83c\udfb5]\");\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-misleading-character-class: error */\n\n/^[abc]$/;\n/^[\ud83d\udc4d]$/u;\n/^[\\q{\ud83d\udc76\ud83c\udffb}]$/v;\nnew RegExp(\"^[]$\");\nnew RegExp(`[A\u0301-${z}]`, \"u\"); // variable pattern\n```\n\n\n## Options\n\nThis rule has an object option:\n\n* `\"allowEscape\"`: When set to `true`, the rule allows any grouping of code points inside a character class as long as they are written using escape sequences. This option only has effect on regular expression literals and on regular expressions created with the `RegExp` constructor with a literal argument as a pattern.\n\n### allowEscape\n\nExamples of **incorrect** code for this rule with the `{ \"allowEscape\": true }` option:\n\n**Incorrect code:**\n\n```js\n/* eslint no-misleading-character-class: [\"error\", { \"allowEscape\": true }] */\n\n/[\\\ud83d\udc4d]/; // backslash can be omitted\n\nnew RegExp(\"[\\ud83d\" + \"\\udc4d]\");\n\nconst pattern = \"[\\ud83d\\udc4d]\";\nnew RegExp(pattern);\n```\n\n\nExamples of **correct** code for this rule with the `{ \"allowEscape\": true }` option:\n\n**Correct code:**\n\n```js\n/* eslint no-misleading-character-class: [\"error\", { \"allowEscape\": true }] */\n\n/[\\ud83d\\udc4d]/;\n/[\\u00B7\\u0300-\\u036F]/u;\n/[\ud83d\udc68\\u200d\ud83d\udc69]/u;\nnew RegExp(\"[\\x41\\u0301]\");\nnew RegExp(`[\\u{1F1EF}\\u{1F1F5}]`, \"u\");\nnew RegExp(\"[\\\\u{1F1EF}\\\\u{1F1F5}]\", \"u\");\n```\n\n\n## When Not To Use It\n\nYou can turn this rule off if you don't want to check RegExp character class syntax for multiple code point characters.",
|
|
1049
|
+
"eslint/no-new-native-nonconstructor": "It is a convention in JavaScript that global variables beginning with an uppercase letter typically represent classes that can be instantiated using the `new` operator, such as `new Array` and `new Map`. Confusingly, JavaScript also provides some global variables that begin with an uppercase letter that cannot be called using the `new` operator and will throw an error if you attempt to do so. These are typically functions that are related to data types and are easy to mistake for classes. Consider the following example:\n\n```js\n// throws a TypeError\nconst foo = new Symbol(\"foo\");\n\n// throws a TypeError\nconst result = new BigInt(9007199254740991);\n```\n\nBoth `new Symbol` and `new BigInt` throw a type error because they are functions and not classes. It is easy to make this mistake by assuming the uppercase letters indicate classes.\n\n## Rule Details\n\nThis rule is aimed at preventing the accidental calling of native JavaScript global functions with the `new` operator. These functions are:\n\n* `Symbol`\n* `BigInt`\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-new-native-nonconstructor: \"error\"*/\n\nconst foo = new Symbol('foo');\nconst bar = new BigInt(9007199254740991);\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-new-native-nonconstructor: \"error\"*/\n\nconst foo = Symbol('foo');\nconst bar = BigInt(9007199254740991);\n\n// Ignores shadowed Symbol.\nfunction baz(Symbol) {\n const qux = new Symbol(\"baz\");\n}\nfunction quux(BigInt) {\n const corge = new BigInt(9007199254740991);\n}\n\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nThis rule should not be used in ES3/5 environments.",
|
|
1050
|
+
"eslint/no-nonoctal-decimal-escape": "Although not being specified in the language until ECMAScript 2021, `\\8` and `\\9` escape sequences in string literals were allowed in most JavaScript engines, and treated as \"useless\" escapes:\n\n```js\n\"\\8\" === \"8\"; // true\n\"\\9\" === \"9\"; // true\n```\n\nSince ECMAScript 2021, these escape sequences are specified as [non-octal decimal escape sequences](https://tc39.es/ecma262/#prod-annexB-NonOctalDecimalEscapeSequence), retaining the same behavior.\n\nNevertheless, the ECMAScript specification treats `\\8` and `\\9` in string literals as a legacy feature. This syntax is optional if the ECMAScript host is not a web browser. Browsers still have to support it, but only in non-strict mode.\n\nRegardless of your targeted environment, these escape sequences shouldn't be used when writing new code.\n\n## Rule Details\n\nThis rule disallows `\\8` and `\\9` escape sequences in string literals.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-nonoctal-decimal-escape: \"error\"*/\n\n\"\\8\";\n\n\"\\9\";\n\nconst foo = \"w\\8less\";\n\nconst bar = \"December 1\\9\";\n\nconst baz = \"Don't use \\8 and \\9 escapes.\";\n\nconst quux = \"\\0\\8\";\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-nonoctal-decimal-escape: \"error\"*/\n\n\"8\";\n\n\"9\";\n\nconst foo = \"w8less\";\n\nconst bar = \"December 19\";\n\nconst baz = \"Don't use \\\\8 and \\\\9 escapes.\";\n\nconst quux = \"\\0\\u0038\";\n```\n\n\n## Options\n\nThis rule has no options.",
|
|
1051
|
+
"eslint/no-obj-calls": "ECMAScript provides several global objects that are intended to be used as-is. Some of these objects look as if they could be constructors due to their capitalization (such as `Math`, `JSON`, and `Temporal`) but will throw an error if you try to execute them as functions.\n\nThe [ECMAScript 5 specification](https://es5.github.io/#x15.8) makes it clear that both `Math` and `JSON` cannot be invoked:\n\n> The Math object does not have a `[[Call]]` internal property; it is not possible to invoke the Math object as a function.\n\nThe [ECMAScript 2015 specification](https://www.ecma-international.org/ecma-262/6.0/index.html#sec-reflect-object) makes it clear that `Reflect` cannot be invoked:\n\n> The Reflect object also does not have a `[[Call]]` internal method; it is not possible to invoke the Reflect object as a function.\n\nThe [ECMAScript 2017 specification](https://www.ecma-international.org/ecma-262/8.0/index.html#sec-atomics-object) makes it clear that `Atomics` cannot be invoked:\n\n> The Atomics object does not have a `[[Call]]` internal method; it is not possible to invoke the Atomics object as a function.\n\nThe [ECMAScript Internationalization API Specification](https://tc39.es/ecma402/#intl-object) makes it clear that `Intl` cannot be invoked:\n\n> The Intl object does not have a `[[Call]]` internal method; it is not possible to invoke the Intl object as a function.\n\nThe [Temporal proposal specification](https://tc39.es/proposal-temporal/#sec-temporal-objects) makes it clear that `Temporal` cannot be invoked:\n\n> The Temporal object does not have a `[[Call]]` internal method; it cannot be invoked as a function.\n\nThe [ECMAScript 2020 specification](https://tc39.es/ecma262/2020/#sec-globalthis) defines `globalThis` as the global `this` value of the current realm. Unless the host specifies otherwise, this is the\n [global object](https://tc39.es/ecma262/2020/#sec-global-object), which:\n\n> does not have a `[[Construct]]` internal method; it cannot be used as a constructor with the `new` operator.\n>\n> does not have a `[[Call]]` internal method; it cannot be invoked as a function.\n\n## Rule Details\n\nThis rule disallows calling `Math`, `JSON`, `Reflect`, `Atomics`, `Intl`, `Temporal`, and `globalThis` as functions.\n\nThis rule also disallows using these objects as constructors with the `new` operator.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-obj-calls: \"error\"*/\n\nconst math = Math();\n\nconst newMath = new Math();\n\nconst json = JSON();\n\nconst newJSON = new JSON();\n\nconst reflect = Reflect();\n\nconst newReflect = new Reflect();\n\nconst atomics = Atomics();\n\nconst newAtomics = new Atomics();\n\nconst intl = Intl();\n\nconst newIntl = new Intl();\n\nconst temporal = Temporal();\n\nconst newTemporal = new Temporal();\n\nconst globalObject = globalThis();\n\nconst newGlobalObject = new globalThis();\n\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-obj-calls: \"error\"*/\n\nfunction area(r) {\n return Math.PI * r * r;\n}\n\nconst object = JSON.parse(\"{}\");\n\nconst value = Reflect.get({ x: 1, y: 2 }, \"x\");\n\nconst first = Atomics.load(foo, 0);\n\nconst segmenterFr = new Intl.Segmenter(\"fr\", { granularity: \"word\" });\n\nconst instant = Temporal.Now.instant();\n\nconst parsed = globalThis.parseInt(\"42\", 10);\n```\n\n\n## Options\n\nThis rule has no options.",
|
|
1052
|
+
"eslint/no-octal": "Octal literals are numerals that begin with a leading zero, such as:\n\n```js\nconst num = 071; // 57\n```\n\nBecause the leading zero which identifies an octal literal has been a source of confusion and error in JavaScript code, ECMAScript 5 deprecates the use of octal numeric literals.\n\n## Rule Details\n\nThe rule disallows octal literals.\n\nIf ESLint parses code in strict mode, the parser (instead of this rule) reports the error.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-octal: \"error\"*/\n\nconst num = 071;\nconst result = 5 + 07;\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-octal: \"error\"*/\n\nconst num = \"071\";\n```\n\n\n## Options\n\nThis rule has no options.\n\n## Compatibility\n\n* **JSHint**: W115",
|
|
1053
|
+
"eslint/no-prototype-builtins": "In ECMAScript 5.1, `Object.create` was added, which enables the creation of objects with a specified `[[Prototype]]`. `Object.create(null)` is a common pattern used to create objects that will be used as a Map. This can lead to errors when it is assumed that objects will have properties from `Object.prototype`. This rule prevents calling some `Object.prototype` methods directly from an object.\n\nAdditionally, objects can have properties that shadow the builtins on `Object.prototype`, potentially causing unintended behavior or denial-of-service security vulnerabilities. For example, it would be unsafe for a webserver to parse JSON input from a client and call `hasOwnProperty` directly on the resulting object, because a malicious client could send a JSON value like `{\"hasOwnProperty\": 1}` and cause the server to crash.\n\nTo avoid subtle bugs like this, it's better to always call these methods from `Object.prototype`. For example, `foo.hasOwnProperty(\"bar\")` should be replaced with `Object.prototype.hasOwnProperty.call(foo, \"bar\")`.\n\n## Rule Details\n\nThis rule disallows calling some `Object.prototype` methods directly on object instances.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-prototype-builtins: \"error\"*/\n\nconst hasBarProperty = foo.hasOwnProperty(\"bar\");\n\nconst isPrototypeOfBar = foo.isPrototypeOf(bar);\n\nconst barIsEnumerable = foo.propertyIsEnumerable(\"bar\");\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-prototype-builtins: \"error\"*/\n\nconst hasBarProperty = Object.prototype.hasOwnProperty.call(foo, \"bar\");\n\nconst isPrototypeOfBar = Object.prototype.isPrototypeOf.call(foo, bar);\n\nconst barIsEnumerable = {}.propertyIsEnumerable.call(foo, \"bar\");\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nYou may want to turn this rule off if your code only touches objects with hardcoded keys, and you will never use an object that shadows an `Object.prototype` method or which does not inherit from `Object.prototype`.",
|
|
1054
|
+
"eslint/no-redeclare": "In JavaScript, it's possible to redeclare the same variable name using `var`. This can lead to confusion as to where the variable is actually declared and initialized.\n\n## Rule Details\n\nThis rule is aimed at eliminating variables that have multiple declarations in the same scope.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-redeclare: \"error\"*/\n\nvar a = 3;\nvar a = 10;\n\nclass C {\n foo() {\n var b = 3;\n var b = 10;\n }\n\n static {\n var c = 3;\n var c = 10;\n }\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-redeclare: \"error\"*/\n\nvar a = 3;\na = 10;\n\nclass C {\n foo() {\n var b = 3;\n b = 10;\n }\n\n static {\n var c = 3;\n c = 10;\n }\n}\n\n```\n\n\n## Options\n\nThis rule takes one optional argument, an object with a boolean property `\"builtinGlobals\"`. It defaults to `true`.\nIf set to `true`, this rule also checks redeclaration of built-in globals, such as `Object`, `Array`, `Number`...\n\n### builtinGlobals\n\nThe `\"builtinGlobals\"` option will check for redeclaration of built-in globals in global scope.\n\nExamples of **incorrect** code for the `{ \"builtinGlobals\": true }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-redeclare: [\"error\", { \"builtinGlobals\": true }]*/\n\nvar Object = 0;\n```\n\n\nNote that when using `sourceType: \"commonjs\"` (or `ecmaFeatures.globalReturn`, if using the default parser), the top scope of a program is not actually the global scope, but rather a \"module\" scope. When this is the case, declaring a variable named after a builtin global is not a redeclaration, but rather a shadowing of the global variable. In that case, the [`no-shadow`](no-shadow) rule with the `\"builtinGlobals\"` option should be used.",
|
|
1055
|
+
"eslint/no-regex-spaces": "Regular expressions can be very complex and difficult to understand, which is why it's important to keep them as simple as possible in order to avoid mistakes. One of the more error-prone things you can do with a regular expression is to use more than one space, such as:\n\n```js\nconst re = /foo bar/;\n```\n\nIn this regular expression, it's very hard to tell how many spaces are intended to be matched. It's better to use only one space and then specify how many spaces are expected, such as:\n\n```js\nconst re = /foo {3}bar/;\n```\n\nNow it is very clear that three spaces are expected to be matched.\n\n## Rule Details\n\nThis rule disallows multiple spaces in regular expression literals.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-regex-spaces: \"error\"*/\n\nconst re = /foo bar/;\nconst re1 = new RegExp(\"foo bar\");\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-regex-spaces: \"error\"*/\n\nconst re = /foo {3}bar/;\nconst re1 = new RegExp(\"foo {3}bar\");\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nIf you want to allow multiple spaces in a regular expression, then you can safely turn this rule off.",
|
|
1056
|
+
"eslint/no-self-assign": "Self assignments have no effect, so probably those are an error due to incomplete refactoring.\nThose indicate that what you should do is still remaining.\n\n```js\nfoo = foo;\n[bar, baz] = [bar, qiz];\n```\n\n## Rule Details\n\nThis rule is aimed at eliminating self assignments.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-self-assign: \"error\"*/\n\nfoo = foo;\n\n[a, b] = [a, b];\n\n[a, ...b] = [x, ...b];\n\n({a, b} = {a, x});\n\nfoo &&= foo;\nfoo ||= foo;\nfoo ??= foo;\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-self-assign: \"error\"*/\n\nfoo = bar;\n[a, b] = [b, a];\n\n// This pattern is warned by the `no-use-before-define` rule.\nlet foo = foo;\n\n// The default values have an effect.\n[foo = 1] = [foo];\n\n// non-self-assignments with properties.\nobj.a = obj.b;\nobj.a.b = obj.c.b;\nobj.a.b = obj.a.c;\nobj[a] = obj[\"a\"];\n\n// This ignores if there is a function call.\nobj.a().b = obj.a().b;\na().b = a().b;\n\n// `&=` and `|=` have an effect on non-integers.\nfoo &= foo;\nfoo |= foo;\n\n// Known limitation: this does not support computed properties except single literal or single identifier.\nobj[a + b] = obj[a + b];\nobj[\"a\" + \"b\"] = obj[\"a\" + \"b\"];\n```\n\n\n## Options\n\nThis rule has the option to check properties as well.\n\n```json\n{\n \"no-self-assign\": [\"error\", {\"props\": true}]\n}\n```\n\n* `props` - if this is `true`, `no-self-assign` rule warns self-assignments of properties. Default is `true`.\n\n### props\n\nExamples of **correct** code with the `{ \"props\": false }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-self-assign: [\"error\", {\"props\": false}]*/\n\n// self-assignments with properties.\nobj.a = obj.a;\nobj.a.b = obj.a.b;\nobj[\"a\"] = obj[\"a\"];\nobj[a] = obj[a];\n```\n\n\n## When Not To Use It\n\nIf you don't want to notify about self assignments, then it's safe to disable this rule.",
|
|
1057
|
+
"eslint/no-setter-return": "Setters cannot return values.\n\nWhile returning a value from a setter does not produce an error, the returned value is being ignored. Therefore, returning a value from a setter is either unnecessary or a possible error, since the returned value cannot be used.\n\n## Rule Details\n\nThis rule disallows returning values from setters and reports `return` statements in setter functions.\n\nOnly `return` without a value is allowed, as it's a control flow statement.\n\nThis rule checks setters in:\n\n* Object literals.\n* Class declarations and class expressions.\n* Property descriptors in `Object.create`, `Object.defineProperty`, `Object.defineProperties`, and `Reflect.defineProperty` methods of the global objects.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-setter-return: \"error\"*/\n\nconst foo = {\n set a(value) {\n this.val = value;\n return value;\n }\n};\n\nclass Foo {\n set a(value) {\n this.val = value * 2;\n return this.val;\n }\n}\n\nconst Bar = class {\n static set a(value) {\n if (value < 0) {\n this.val = 0;\n return 0;\n }\n this.val = value;\n }\n};\n\nObject.defineProperty(foo, \"bar\", {\n set(value) {\n if (value < 0) {\n return false;\n }\n this.val = value;\n }\n});\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-setter-return: \"error\"*/\n\nconst foo = {\n set a(value) {\n this.val = value;\n }\n};\n\nclass Foo {\n set a(value) {\n this.val = value * 2;\n }\n}\n\nconst Bar = class {\n static set a(value) {\n if (value < 0) {\n this.val = 0;\n return;\n }\n this.val = value;\n }\n};\n\nObject.defineProperty(foo, \"bar\", {\n set(value) {\n if (value < 0) {\n throw new Error(\"Negative value.\");\n }\n this.val = value;\n }\n});\n```\n\n\n## Options\n\nThis rule has no options.",
|
|
1058
|
+
"eslint/no-shadow-restricted-names": "ES2020 \u00a718.1 Value Properties of the Global Object (`globalThis`, `NaN`, `Infinity`, `undefined`) as well as strict mode restricted identifiers `eval` and `arguments` are considered to be restricted names in JavaScript. Defining them to mean something else can have unintended consequences and confuse others reading the code. For example, there's nothing preventing you from writing:\n\n```js\nconst undefined = \"foo\";\n```\n\nThen any code used within the same scope would not get the global `undefined`, but rather the local version with a very different meaning.\n\n## Rule Details\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-shadow-restricted-names: \"error\"*/\n\nfunction NaN(){}\n\n!function(Infinity){};\n\nconst undefined = 5;\n\ntry {} catch(eval){}\n```\n\n\n**Incorrect code:**\n\n```js\n/*eslint no-shadow-restricted-names: \"error\"*/\n\nimport NaN from \"foo\";\n\nimport { undefined } from \"bar\";\n\nclass Infinity {}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-shadow-restricted-names: \"error\"*/\n\nlet Object;\n\nfunction f(a, b){}\n\n// Exception: `undefined` may be shadowed if the variable is never assigned a value.\nlet undefined;\n```\n\n\n**Correct code:**\n\n```js\n/*eslint no-shadow-restricted-names: \"error\"*/\n\nimport { undefined as undef } from \"bar\";\n```\n\n\n## Options\n\nThis rule has an object option:\n\n* `\"reportGlobalThis\"`: `true` (default) reports declarations of `globalThis`.\n\n### reportGlobalThis\n\nExamples of **incorrect** code for the default `{ \"reportGlobalThis\": true }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-shadow-restricted-names: [\"error\", { \"reportGlobalThis\": true }]*/\n\nconst globalThis = \"foo\";\n```\n\n\n**Incorrect code:**\n\n```js\n/*eslint no-shadow-restricted-names: [\"error\", { \"reportGlobalThis\": true }]*/\n\nfunction globalThis() {}\n```\n\n\n**Incorrect code:**\n\n```js\n/*eslint no-shadow-restricted-names: [\"error\", { \"reportGlobalThis\": true }]*/\n\nimport { globalThis } from \"bar\";\n```\n\n\n**Incorrect code:**\n\n```js\n/*eslint no-shadow-restricted-names: [\"error\", { \"reportGlobalThis\": true }]*/\n\nclass globalThis {}\n```\n\n\nExamples of **correct** code for the default `{ \"reportGlobalThis\": true }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-shadow-restricted-names: [\"error\", { \"reportGlobalThis\": true }]*/\n\nconst foo = globalThis;\n\nfunction bar() {\n return globalThis;\n}\n\nimport { globalThis as baz } from \"foo\";\n```\n\n\nExamples of **correct** code for the `{ \"reportGlobalThis\": false }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-shadow-restricted-names: [\"error\", { \"reportGlobalThis\": false }]*/\n\nconst globalThis = \"foo\";\n```\n\n\n**Correct code:**\n\n```js\n/*eslint no-shadow-restricted-names: [\"error\", { \"reportGlobalThis\": false }]*/\n\nfunction globalThis() {}\n```\n\n\n**Correct code:**\n\n```js\n/*eslint no-shadow-restricted-names: [\"error\", { \"reportGlobalThis\": false }]*/\n\nimport { globalThis } from \"bar\";\n```\n\n\n**Correct code:**\n\n```js\n/*eslint no-shadow-restricted-names: [\"error\", { \"reportGlobalThis\": false }]*/\n\nclass globalThis {}\n```",
|
|
1059
|
+
"eslint/no-sparse-arrays": "Sparse arrays contain empty slots, most frequently due to multiple commas being used in an array literal, such as:\n\n```js\nconst items = [,,];\n```\n\nWhile the `items` array in this example has a `length` of 2, there are actually no values in `items[0]` or `items[1]`. The fact that the array literal is valid with only commas inside, coupled with the `length` being set and actual item values not being set, make sparse arrays confusing for many developers. Consider the following:\n\n```js\nconst colors = [ \"red\",, \"blue\" ];\n```\n\nIn this example, the `colors` array has a `length` of 3. But did the developer intend for there to be an empty spot in the middle of the array? Or is it a typo?\n\nThe confusion around sparse arrays defined in this manner is enough that it's recommended to avoid using them unless you are certain that they are useful in your code.\n\n## Rule Details\n\nThis rule disallows sparse array literals which have \"holes\" where commas are not preceded by elements. It does not apply to a trailing comma following the last element.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-sparse-arrays: \"error\"*/\n\nconst items = [,];\nconst colors = [ \"red\",, \"blue\" ];\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-sparse-arrays: \"error\"*/\n\nconst items = [];\nconst arr = new Array(23);\n\n// trailing comma (after the last element) is not a problem\nconst colors = [ \"red\", \"blue\", ];\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nIf you want to use sparse arrays, then it is safe to disable this rule.",
|
|
1060
|
+
"eslint/no-this-before-super": "In the constructor of derived classes, if `this`/`super` are used before `super()` calls, it raises a reference error.\n\nThis rule checks `this`/`super` keywords in constructors, then reports those that are before `super()`.\n\n## Rule Details\n\nThis rule is aimed to flag `this`/`super` keywords before `super()` callings.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-this-before-super: \"error\"*/\n\nclass A1 extends B {\n constructor() {\n this.a = 0;\n super();\n }\n}\n\nclass A2 extends B {\n constructor() {\n this.foo();\n super();\n }\n}\n\nclass A3 extends B {\n constructor() {\n super.foo();\n super();\n }\n}\n\nclass A4 extends B {\n constructor() {\n super(this.foo());\n }\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-this-before-super: \"error\"*/\n\nclass A1 {\n constructor() {\n this.a = 0; // OK, this class doesn't have an `extends` clause.\n }\n}\n\nclass A2 extends B {\n constructor() {\n super();\n this.a = 0; // OK, this is after `super()`.\n }\n}\n\nclass A3 extends B {\n foo() {\n this.a = 0; // OK. this is not in a constructor.\n }\n}\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nIf you don't want to be notified about using `this`/`super` before `super()` in constructors, you can safely disable this rule.",
|
|
1061
|
+
"eslint/no-undef": "This rule can help you locate potential ReferenceErrors resulting from misspellings of variable and parameter names, or accidental implicit globals (for example, from forgetting the `var` keyword in a `for` loop initializer).\n\n## Rule Details\n\nAny reference to an undeclared variable causes a warning, unless the variable is explicitly mentioned in a `/*global ...*/` comment, or specified in the [`globals` key in the configuration file](../use/configure/language-options#specify-globals). A common use case for these is if you intentionally use globals that are defined elsewhere (e.g. in a script sourced from HTML).\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-undef: \"error\"*/\n\nconst foo = someFunction();\nconst bar = a + 1;\n```\n\n\nExamples of **correct** code for this rule with `global` declaration:\n\n**Correct code:**\n\n```js\n/*global someFunction, a*/\n/*eslint no-undef: \"error\"*/\n\nconst foo = someFunction();\nconst bar = a + 1;\n```\n\n\nNote that this rule does not disallow assignments to read-only global variables.\nSee [no-global-assign](no-global-assign) if you also want to disallow those assignments.\n\nThis rule also does not disallow redeclarations of global variables.\nSee [no-redeclare](no-redeclare) if you also want to disallow those redeclarations.\n\n## Options\n\n* `typeof` set to true will warn for variables used inside typeof check (Default false).\n\n### typeof\n\nExamples of **correct** code for the default `{ \"typeof\": false }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-undef: \"error\"*/\n\nif (typeof UndefinedIdentifier === \"undefined\") {\n // do something ...\n}\n```\n\n\nYou can use this option if you want to prevent `typeof` check on a variable which has not been declared.\n\nExamples of **incorrect** code for the `{ \"typeof\": true }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-undef: [\"error\", { \"typeof\": true }] */\n\nif(typeof a === \"string\"){}\n```\n\n\nExamples of **correct** code for the `{ \"typeof\": true }` option with `global` declaration:\n\n**Correct code:**\n\n```js\n/*global a*/\n/*eslint no-undef: [\"error\", { \"typeof\": true }] */\n\nif(typeof a === \"string\"){}\n```\n\n\n## When Not To Use It\n\nIf explicit declaration of global variables is not to your taste.\n\n## Compatibility\n\nThis rule provides compatibility with treatment of global variables in [JSHint](https://jshint.com/) and [JSLint](https://www.jslint.com).",
|
|
1062
|
+
"eslint/no-unexpected-multiline": "Semicolons are usually optional in JavaScript, because of automatic semicolon insertion (ASI). You can require or disallow semicolons with the [semi](./semi) rule.\n\nThe rules for ASI are relatively straightforward: As once described by Isaac Schlueter, a newline character always ends a statement, just like a semicolon, **except** where one of the following is true:\n\n* The statement has an unclosed paren, array literal, or object literal or ends in some other way that is not a valid way to end a statement. (For instance, ending with `.` or `,`.)\n* The line is `--` or `++` (in which case it will decrement/increment the next token.)\n* It is a `for()`, `while()`, `do`, `if()`, or `else`, and there is no `{`\n* The next line starts with `[`, `(`, `+`, `*`, `/`, `-`, `,`, `.`, or some other binary operator that can only be found between two tokens in a single expression.\n\nIn the exceptions where a newline does **not** end a statement, a typing mistake to omit a semicolon causes two unrelated consecutive lines to be interpreted as one expression. Especially for a coding style without semicolons, readers might overlook the mistake. Although syntactically correct, the code might throw exceptions when it is executed.\n\n## Rule Details\n\nThis rule disallows confusing multiline expressions where a newline looks like it is ending a statement, but is not.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unexpected-multiline: \"error\"*/\n\nconst foo = bar\n(1 || 2).baz();\n\nconst hello = 'world'\n[1, 2, 3].forEach(addNumber);\n\nconst x = function() {}\n`hello`\n\nconst y = function() {}\ny\n`hello`\n\nconst z = foo\n/regex/g.test(bar)\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-unexpected-multiline: \"error\"*/\n\nconst foo = bar;\n(1 || 2).baz();\n\nconst baz = bar\n;(1 || 2).baz()\n\nconst hello = 'world';\n[1, 2, 3].forEach(addNumber);\n\nconst hi = 'world'\nvoid [1, 2, 3].forEach(addNumber);\n\nconst x = function() {};\n`hello`\n\nconst tag = function() {}\ntag `hello`\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nYou can turn this rule off if you are confident that you will not accidentally introduce code like this.\n\nNote that the patterns considered problems are **not** flagged by the [semi](semi) rule.",
|
|
1063
|
+
"eslint/no-unreachable": "Because the `return`, `throw`, `continue`, and `break` statements unconditionally exit a block of code, any statements after them cannot be executed. Unreachable statements are usually a mistake.\n\n```js\nfunction fn() {\n x = 1;\n return x;\n x = 3; // this will never execute\n}\n```\n\nAnother kind of mistake is defining instance fields in a subclass whose constructor doesn't call `super()`. Instance fields of a subclass are only added to the instance after `super()`. If there are no `super()` calls, their definitions are never applied and therefore are unreachable code.\n\n```js\nclass C extends B {\n #x; // this will never be added to instances\n\n constructor() {\n return {};\n }\n}\n```\n\n## Rule Details\n\nThis rule disallows unreachable code after `return`, `throw`, `continue`, and `break` statements. This rule also flags definitions of instance fields in subclasses whose constructors don't have `super()` calls.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unreachable: \"error\"*/\n\nfunction foo() {\n return true;\n console.log(\"done\");\n}\n\nfunction bar() {\n throw new Error(\"Oops!\");\n console.log(\"done\");\n}\n\nwhile(value) {\n break;\n console.log(\"done\");\n}\n\nthrow new Error(\"Oops!\");\nconsole.log(\"done\");\n\nfunction baz() {\n if (Math.random() < 0.5) {\n return;\n } else {\n throw new Error();\n }\n console.log(\"done\");\n}\n\nfor (;;) {}\nconsole.log(\"done\");\n```\n\n\nExamples of **correct** code for this rule, because of JavaScript function and variable hoisting:\n\n**Correct code:**\n\n```js\n/*eslint no-unreachable: \"error\"*/\n\nfunction foo() {\n return bar();\n function bar() {\n return 1;\n }\n}\n\nfunction bar() {\n return x;\n var x;\n}\n\nswitch (foo) {\n case 1:\n break;\n var x;\n}\n```\n\n\nExamples of additional **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unreachable: \"error\"*/\n\nclass C extends B {\n #x; // unreachable\n #y = 1; // unreachable\n a; // unreachable\n b = 1; // unreachable\n\n constructor() {\n return {};\n }\n}\n```\n\n\nExamples of additional **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-unreachable: \"error\"*/\n\nclass D extends B {\n #x;\n #y = 1;\n a;\n b = 1;\n\n constructor() {\n super();\n }\n}\n\nclass E extends B {\n #x;\n #y = 1;\n a;\n b = 1;\n\n // implicit constructor always calls `super()`\n}\n\nclass F extends B {\n static #x;\n static #y = 1;\n static a;\n static b = 1;\n\n constructor() {\n return {};\n }\n}\n```\n\n\n## Options\n\nThis rule has no options.",
|
|
1064
|
+
"eslint/no-unsafe-finally": "JavaScript suspends the control flow statements of `try` and `catch` blocks until the execution of `finally` block finishes. So, when `return`, `throw`, `break`, or `continue` is used in `finally`, control flow statements inside `try` and `catch` are overwritten, which is considered as unexpected behavior. Such as:\n\n```js\n// We expect this function to return 1;\n(() => {\n try {\n return 1; // 1 is returned but suspended until finally block ends\n } catch(err) {\n return 2;\n } finally {\n return 3; // 3 is returned before 1, which we did not expect\n }\n})();\n\n// > 3\n```\n\n```js\n// We expect this function to throw an error, then return\n(() => {\n try {\n throw new Error(\"Try\"); // error is thrown but suspended until finally block ends\n } finally {\n return 3; // 3 is returned before the error is thrown, which we did not expect\n }\n})();\n\n// > 3\n```\n\n```js\n// We expect this function to throw Try(...) error from the catch block\n(() => {\n try {\n throw new Error(\"Try\")\n } catch(err) {\n throw err; // The error thrown from try block is caught and rethrown\n } finally {\n throw new Error(\"Finally\"); // Finally(...) is thrown, which we did not expect\n }\n})();\n\n// > Uncaught Error: Finally(...)\n```\n\n```js\n// We expect this function to return 0 from try block.\n(() => {\n label: try {\n return 0; // 0 is returned but suspended until finally block ends\n } finally {\n break label; // It breaks out the try-finally block, before 0 is returned.\n }\n return 1;\n})();\n\n// > 1\n```\n\n## Rule Details\n\nThis rule disallows `return`, `throw`, `break`, and `continue` statements inside `finally` blocks. It allows indirect usages, such as in `function` or `class` definitions.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unsafe-finally: \"error\"*/\nlet foo = function() {\n try {\n return 1;\n } catch(err) {\n return 2;\n } finally {\n return 3;\n }\n};\n```\n\n\n**Incorrect code:**\n\n```js\n/*eslint no-unsafe-finally: \"error\"*/\nlet foo = function() {\n try {\n return 1;\n } catch(err) {\n return 2;\n } finally {\n throw new Error;\n }\n};\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-unsafe-finally: \"error\"*/\nlet foo = function() {\n try {\n return 1;\n } catch(err) {\n return 2;\n } finally {\n console.log(\"hola!\");\n }\n};\n```\n\n\n**Correct code:**\n\n```js\n/*eslint no-unsafe-finally: \"error\"*/\nlet foo = function() {\n try {\n return 1;\n } catch(err) {\n return 2;\n } finally {\n let a = function() {\n return \"hola!\";\n }\n }\n};\n```\n\n\n**Correct code:**\n\n```js\n/*eslint no-unsafe-finally: \"error\"*/\nlet foo = function(a) {\n try {\n return 1;\n } catch(err) {\n return 2;\n } finally {\n switch(a) {\n case 1: {\n console.log(\"hola!\")\n break;\n }\n }\n }\n};\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nIf you want to allow control flow operations in `finally` blocks, you can turn this rule off.\n\nNote that [using `return` with `try`/`finally` in generator functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator/return#using_return_with_try...finally) can be used to override the value returned.\nIf you want to use this feature of generator functions, you can disable this rule using an `eslint-disable` comment.",
|
|
1065
|
+
"eslint/no-unsafe-negation": "Just as developers might type `-a + b` when they mean `-(a + b)` for the negative of a sum, they might type `!key in object` by mistake when they almost certainly mean `!(key in object)` to test that a key is not in an object. `!obj instanceof Ctor` is similar.\n\n## Rule Details\n\nThis rule disallows negating the left operand of the following relational operators:\n\n* [`in` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in).\n* [`instanceof` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof).\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unsafe-negation: \"error\"*/\n\nif (!key in object) {\n // operator precedence makes it equivalent to (!key) in object\n // and type conversion makes it equivalent to (key ? \"false\" : \"true\") in object\n}\n\nif (!obj instanceof Ctor) {\n // operator precedence makes it equivalent to (!obj) instanceof Ctor\n // and it equivalent to always false since boolean values are not objects.\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-unsafe-negation: \"error\"*/\n\nif (!(key in object)) {\n // key is not in object\n}\n\nif (!(obj instanceof Ctor)) {\n // obj is not an instance of Ctor\n}\n```\n\n\n### Exception\n\nFor rare situations when negating the left operand is intended, this rule allows an exception.\nIf the whole negation is explicitly wrapped in parentheses, the rule will not report a problem.\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-unsafe-negation: \"error\"*/\n\nif ((!foo) in object) {\n // allowed, because the negation is explicitly wrapped in parentheses\n // it is equivalent to (foo ? \"false\" : \"true\") in object\n // this is allowed as an exception for rare situations when that is the intended meaning\n}\n\nif((\"\" + !foo) in object) {\n // you can also make the intention more explicit, with type conversion\n}\n```\n\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unsafe-negation: \"error\"*/\n\nif (!(foo) in object) {\n // this is not an allowed exception\n}\n```\n\n\n## Options\n\nThis rule has an object option:\n\n* `\"enforceForOrderingRelations\": false` (default) allows negation of the left-hand side of ordering relational operators (`<`, `>`, `<=`, `>=`)\n* `\"enforceForOrderingRelations\": true` disallows negation of the left-hand side of ordering relational operators\n\n### enforceForOrderingRelations\n\nWith this option set to `true` the rule is additionally enforced for:\n\n* `<` operator.\n* `>` operator.\n* `<=` operator.\n* `>=` operator.\n\nThe purpose is to avoid expressions such as `! a < b` (which is equivalent to `(a ? 0 : 1) < b`) when what is really intended is `!(a < b)`.\n\nExamples of additional **incorrect** code for this rule with the `{ \"enforceForOrderingRelations\": true }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unsafe-negation: [\"error\", { \"enforceForOrderingRelations\": true }]*/\n\nif (! a < b) {}\n\nwhile (! a > b) {}\n\nfoo = ! a <= b;\n\nfoo = ! a >= b;\n```\n\n\n## When Not To Use It\n\nIf you don't want to notify unsafe logical negations, then it's safe to disable this rule.",
|
|
1066
|
+
"eslint/no-unsafe-optional-chaining": "The optional chaining (`?.`) expression can short-circuit with a return value of `undefined`. Therefore, treating an evaluated optional chaining expression as a function, object, number, etc., can cause TypeError or unexpected results. For example:\n\n```js\nconst obj = undefined;\n\n1 in obj?.foo; // TypeError\nwith (obj?.foo); // TypeError\nfor (bar of obj?.foo); // TypeError\nbar instanceof obj?.foo; // TypeError\nconst { bar } = obj?.foo; // TypeError\n```\n\nAlso, parentheses limit the scope of short-circuiting in chains. For example:\n\n```js\nconst obj = undefined;\n\n(obj?.foo)(); // TypeError\n(obj?.foo).bar; // TypeError\n```\n\n## Rule Details\n\nThis rule aims to detect some cases where the use of optional chaining doesn't prevent runtime errors. In particular, it flags optional chaining expressions in positions where short-circuiting to `undefined` causes throwing a TypeError afterward.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unsafe-optional-chaining: \"error\"*/\n\n(obj?.foo)();\n\n(obj?.foo).bar;\n\n(foo?.()).bar;\n\n(foo?.()).bar();\n\n(obj?.foo ?? obj?.bar)();\n\n(foo || obj?.foo)();\n\n(obj?.foo && foo)();\n\n(foo ? obj?.foo : bar)();\n\n(foo, obj?.bar).baz;\n\n(obj?.foo)`template`;\n\nnew (obj?.foo)();\n\n[...obj?.foo];\n\nbar(...obj?.foo);\n\n1 in obj?.foo;\n\nbar instanceof obj?.foo;\n\nfor (bar of obj?.foo);\n\nconst { bar } = obj?.foo;\n\n[{ bar } = obj?.foo] = [];\n\nwith (obj?.foo);\n\nclass A extends obj?.foo {}\n\nconst a = class A extends obj?.foo {};\n\nfunction* gen() {\n yield* obj?.foo;\n}\n\nasync function foo () {\n const { bar } = await obj?.foo;\n (await obj?.foo)();\n (await obj?.foo).bar;\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-unsafe-optional-chaining: \"error\"*/\n\n(obj?.foo)?.();\n\nobj?.foo();\n\n(obj?.foo ?? bar)();\n\nobj?.foo.bar;\n\nobj.foo?.bar;\n\nfoo?.()?.bar;\n\n(obj?.foo ?? bar)`template`;\n\nnew (obj?.foo ?? bar)();\n\nconst baz = {...obj?.foo};\n\nconst { bar } = obj?.foo || baz;\n\nfunction* gen() {\n yield obj?.foo;\n yield* obj?.foo ?? [];\n}\n\nasync function foo () {\n const { bar } = await obj?.foo || baz;\n (await obj?.foo)?.();\n (await obj?.foo)?.bar;\n}\n```\n\n\n## Options\n\nThis rule has an object option:\n\n* `disallowArithmeticOperators`: Disallow arithmetic operations on optional chaining expressions (Default `false`). If this is `true`, this rule warns arithmetic operations on optional chaining expressions, which possibly result in `NaN`.\n\n### disallowArithmeticOperators\n\nWith this option set to `true` the rule is enforced for:\n\n* Unary operators: `-`, `+`\n* Arithmetic operators: `+`, `-`, `/`, `*`, `%`, `**`\n* Assignment operators: `+=`, `-=`, `/=`, `*=`, `%=`, `**=`\n\nExamples of additional **incorrect** code for this rule with the `{ \"disallowArithmeticOperators\": true }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unsafe-optional-chaining: [\"error\", { \"disallowArithmeticOperators\": true }]*/\n\n+obj?.foo;\n-obj?.foo;\n\nobj?.foo + bar;\nobj?.foo - bar;\nobj?.foo / bar;\nobj?.foo * bar;\nobj?.foo % bar;\nobj?.foo ** bar;\n\nbaz += obj?.foo;\nbaz -= obj?.foo;\nbaz /= obj?.foo;\nbaz *= obj?.foo;\nbaz %= obj?.foo;\nbaz **= obj?.foo;\n\nasync function foo () {\n +await obj?.foo;\n await obj?.foo + bar;\n baz += await obj?.foo;\n}\n```",
|
|
1067
|
+
"eslint/no-unused-labels": "Labels that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring.\n\n```js\nOUTER_LOOP:\nfor (const student of students) {\n if (checkScores(student.scores)) {\n continue;\n }\n doSomething(student);\n}\n```\n\nIn this case, probably removing `OUTER_LOOP:` had been forgotten.\nSuch labels take up space in the code and can lead to confusion by readers.\n\n## Rule Details\n\nThis rule is aimed at eliminating unused labels.\n\nProblems reported by this rule can be fixed automatically, except when there are any comments between the label and the following statement, or when removing a label would cause the following statement to become a directive such as `\"use strict\"`.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unused-labels: \"error\"*/\n\nA: var foo = 0;\n\nB: {\n foo();\n}\n\nC:\nfor (let i = 0; i < 10; ++i) {\n foo();\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-labels: \"error\"*/\n\nA: {\n if (foo()) {\n break A;\n }\n bar();\n}\n\nB:\nfor (let i = 0; i < 10; ++i) {\n if (foo()) {\n break B;\n }\n bar();\n}\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nIf you don't want to be notified about unused labels, then it's safe to disable this rule.",
|
|
1068
|
+
"eslint/no-unused-private-class-members": "Private class members that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such class members take up space in the code and can lead to confusion by readers.\n\n## Rule Details\n\nThis rule reports unused private class members.\n\n* A private field or method is considered to be unused if its value is never read.\n* A private accessor is considered to be unused if it is never accessed (read or write).\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unused-private-class-members: \"error\"*/\n\nclass A {\n #unusedMember = 5;\n}\n\nclass B {\n #usedOnlyInWrite = 5;\n method() {\n this.#usedOnlyInWrite = 42;\n }\n}\n\nclass C {\n #usedOnlyToUpdateItself = 5;\n method() {\n this.#usedOnlyToUpdateItself++;\n }\n}\n\nclass D {\n #unusedMethod() {}\n}\n\nclass E {\n get #unusedAccessor() {}\n set #unusedAccessor(value) {}\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-private-class-members: \"error\"*/\n\nclass A {\n #usedMember = 42;\n method() {\n return this.#usedMember;\n }\n}\n\nclass B {\n #usedMethod() {\n return 42;\n }\n anotherMethod() {\n return this.#usedMethod();\n }\n}\n\nclass C {\n get #usedAccessor() {}\n set #usedAccessor(value) {}\n \n method() {\n this.#usedAccessor = 42;\n }\n}\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nIf you don't want to be notified about unused private class members, you can safely turn this rule off.",
|
|
1069
|
+
"eslint/no-unused-vars": "Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such variables take up space in the code and can lead to confusion by readers.\n\n## Rule Details\n\nThis rule is aimed at eliminating unused variables, functions, and function parameters.\n\nA variable `foo` is considered to be used if any of the following are true:\n\n* It is called (`foo()`) or constructed (`new foo()`)\n* It is read (`let bar = foo`)\n* It is passed into a function as an argument (`doSomething(foo)`)\n* It is read inside of a function that is passed to another function (`doSomething(function() { foo(); })`)\n\nA variable is *not* considered to be used if it is only ever declared (`let foo = 5`) or assigned to (`foo = 7`).\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unused-vars: \"error\"*/\n/*global some_unused_var*/\n\n// It checks variables you have defined as global\nsome_unused_var = 42;\n\nlet x;\n\n// Write-only variables are not considered as used.\nlet y = 10;\ny = 5;\n\n// A read for a modification of itself is not considered as used.\nlet z = 0;\nz = z + 1;\n\n// By default, unused arguments cause warnings.\n(function(foo) {\n return 5;\n})();\n\n// Unused recursive functions also cause warnings.\nfunction fact(n) {\n if (n < 2) return 1;\n return n * fact(n - 1);\n}\n\n// When a function definition destructures an array, unused entries from the array also cause warnings.\nfunction getY([x, y]) {\n return y;\n}\ngetY([\"a\", \"b\"]);\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-vars: \"error\"*/\n\nconst x = 10;\nalert(x);\n\n// foo is considered used here\nmyFunc(function foo() {\n // ...\n}.bind(this));\n\n(function(foo) {\n return foo;\n})();\n\nvar myFunc;\nmyFunc = setTimeout(function() {\n // myFunc is considered used\n myFunc();\n}, 50);\n\n// Only the second argument from the destructured array is used.\nfunction getY([, y]) {\n return y;\n}\ngetY([\"a\", \"b\"]);\n```\n\n\n### exported\n\nIn environments outside of CommonJS or ECMAScript modules, you may use `var` to create a global variable that may be used by other scripts. You can use the `/* exported variableName */` comment block to indicate that this variable is being exported and therefore should not be considered unused.\n\nNote that `/* exported */` has no effect for any of the following:\n\n* when `languageOptions.sourceType` is `module` (default) or `commonjs`\n* when `languageOptions.parserOptions.ecmaFeatures.globalReturn` is `true`\n\nThe line comment `// exported variableName` will not work as `exported` is not line-specific.\n\n```js\n/* exported global_var */\n\nvar global_var = 42;\n```\n\nExamples of **correct** code for `/* exported variableName */` operation with `no-unused-vars`:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-vars: \"error\"*/\n/* exported global_var */\n\nvar global_var = 42;\n```\n\n\n## Options\n\nThis rule takes one argument which can be a string or an object. The string settings are the same as those of the `vars` property (explained below).\n\nBy default this rule is enabled with `all` option for caught errors and variables, and `after-used` for arguments.\n\n```json\n{\n \"rules\": {\n \"no-unused-vars\": [\"error\", {\n \"vars\": \"all\",\n \"args\": \"after-used\",\n \"caughtErrors\": \"all\",\n \"ignoreRestSiblings\": false,\n \"ignoreUsingDeclarations\": false,\n \"reportUsedIgnorePattern\": false\n }]\n }\n}\n```\n\n### vars\n\nThe `vars` option has two settings:\n\n* `\"all\"` checks all variables for usage, including those in the global scope. However, it excludes variables targeted by other options like `args` and `caughtErrors`. This is the default setting.\n* `\"local\"` allows variables in the global scope to be unused.\n\n#### vars: local\n\nExamples of **correct** code for the `{ \"vars\": \"local\" }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-vars: [\"error\", { \"vars\": \"local\" }]*/\n/*global some_unused_var */\n\nsome_unused_var = 42;\n```\n\n\nExamples of **correct** code for the `{ \"vars\": \"local\" }` option with `\"languageOptions\": { \"sourceType\": \"script\" }`:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-vars: [\"error\", { \"vars\": \"local\" }]*/\n\nconst foo = 42;\n\nlet bar;\n\nlet baz = 42;\n\nvar qux;\n\nvar quux = 42;\n```\n\n\n### varsIgnorePattern\n\nThe `varsIgnorePattern` option specifies exceptions not to check for usage: variables whose names match a regexp pattern. For example, variables whose names contain `ignored` or `Ignored`. However, it excludes variables targeted by other options like `argsIgnorePattern` and `caughtErrorsIgnorePattern`.\n\nExamples of **correct** code for the `{ \"varsIgnorePattern\": \"[iI]gnored\" }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"[iI]gnored\" }]*/\n\nconst firstVarIgnored = 1;\nconst secondVar = 2;\nconsole.log(secondVar);\n```\n\n\n### args\n\nThe `args` option has three settings:\n\n* `after-used` - unused positional arguments that occur before the last used argument will not be checked, but all named arguments and all positional arguments after the last used argument will be checked.\n* `all` - all named arguments must be used.\n* `none` - do not check arguments.\n\n#### args: after-used\n\nExamples of **incorrect** code for the default `{ \"args\": \"after-used\" }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unused-vars: [\"error\", { \"args\": \"after-used\" }]*/\n\n// 2 errors, for the parameters after the last used parameter (bar)\n// \"baz\" is defined but never used\n// \"qux\" is defined but never used\n(function(foo, bar, baz, qux) {\n return bar;\n})();\n```\n\n\nExamples of **correct** code for the default `{ \"args\": \"after-used\" }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-vars: [\"error\", {\"args\": \"after-used\"}]*/\n\n(function(foo, bar, baz, qux) {\n return qux;\n})();\n```\n\n\n#### args: all\n\nExamples of **incorrect** code for the `{ \"args\": \"all\" }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unused-vars: [\"error\", { \"args\": \"all\" }]*/\n\n// 2 errors\n// \"foo\" is defined but never used\n// \"baz\" is defined but never used\n(function(foo, bar, baz) {\n return bar;\n})();\n```\n\n\n#### args: none\n\nExamples of **correct** code for the `{ \"args\": \"none\" }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-vars: [\"error\", { \"args\": \"none\" }]*/\n\n(function(foo, bar, baz) {\n return bar;\n})();\n```\n\n\n### argsIgnorePattern\n\nThe `argsIgnorePattern` option specifies exceptions not to check for usage: arguments whose names match a regexp pattern. For example, variables whose names begin with an underscore.\n\nExamples of **correct** code for the `{ \"argsIgnorePattern\": \"^_\" }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-vars: [\"error\", { \"argsIgnorePattern\": \"^_\" }]*/\n\nfunction foo(x, _y) {\n return x + 1;\n}\nfoo();\n```\n\n\n### caughtErrors\n\nThe `caughtErrors` option is used for `catch` block arguments validation.\n\nIt has two settings:\n\n* `all` - all named arguments must be used. This is the default setting.\n* `none` - do not check error objects.\n\n#### caughtErrors: all\n\nNot specifying this option is equivalent of assigning it to `all`.\n\nExamples of **incorrect** code for the `{ \"caughtErrors\": \"all\" }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unused-vars: [\"error\", { \"caughtErrors\": \"all\" }]*/\n\n// 1 error\n// \"err\" is defined but never used\ntry {\n //...\n} catch (err) {\n console.error(\"errors\");\n}\n```\n\n\n#### caughtErrors: none\n\nExamples of **correct** code for the `{ \"caughtErrors\": \"none\" }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-vars: [\"error\", { \"caughtErrors\": \"none\" }]*/\n\ntry {\n //...\n} catch (err) {\n console.error(\"errors\");\n}\n```\n\n\n### caughtErrorsIgnorePattern\n\nThe `caughtErrorsIgnorePattern` option specifies exceptions not to check for usage: catch arguments whose names match a regexp pattern. For example, variables whose names begin with a string 'ignore'.\n\nExamples of **correct** code for the `{ \"caughtErrorsIgnorePattern\": \"^ignore\" }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-vars: [\"error\", { \"caughtErrors\": \"all\", \"caughtErrorsIgnorePattern\": \"^ignore\" }]*/\n\ntry {\n //...\n} catch (ignoreErr) {\n console.error(\"errors\");\n}\n```\n\n\n### destructuredArrayIgnorePattern\n\nThe `destructuredArrayIgnorePattern` option specifies exceptions not to check for usage: elements of array destructuring patterns whose names match a regexp pattern. For example, variables whose names begin with an underscore.\n\nExamples of **correct** code for the `{ \"destructuredArrayIgnorePattern\": \"^_\" }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-vars: [\"error\", { \"destructuredArrayIgnorePattern\": \"^_\" }]*/\n\nconst [a, _b, c] = [\"a\", \"b\", \"c\"];\nconsole.log(a+c);\n\nconst { x: [_a, foo] } = bar;\nconsole.log(foo);\n\nfunction baz([_c, x]) {\n x;\n}\nbaz();\n\nfunction test({p: [_q, r]}) {\n r;\n}\ntest();\n\nlet _m, n;\nfoo.forEach(item => {\n [_m, n] = item;\n console.log(n);\n});\n\nlet _o, p;\n_o = 1;\n[_o, p] = foo;\np;\n```\n\n\n### ignoreRestSiblings\n\nThe `ignoreRestSiblings` option is a boolean (default: `false`). Using a [Rest Property](https://github.com/tc39/proposal-object-rest-spread) it is possible to \"omit\" properties from an object, but by default the sibling properties are marked as \"unused\". With this option enabled the rest property's siblings are ignored.\n\nExamples of **correct** code for the `{ \"ignoreRestSiblings\": true }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-vars: [\"error\", { \"ignoreRestSiblings\": true }]*/\n\n// 'foo' and 'bar' were ignored because they have a rest property sibling.\nconst { foo, ...rest } = data;\nconsole.log(rest);\n\n// OR\n\nlet bar;\n({ bar, ...rest } = data);\n```\n\n\n### ignoreClassWithStaticInitBlock\n\nThe `ignoreClassWithStaticInitBlock` option is a boolean (default: `false`). Static initialization blocks allow you to initialize static variables and execute code during the evaluation of a class definition, meaning the static block code is executed without creating a new instance of the class. When set to `true`, this option ignores classes containing static initialization blocks.\n\nExamples of **incorrect** code for the `{ \"ignoreClassWithStaticInitBlock\": true }` option\n\n**Incorrect code:**\n\n```js\n/*eslint no-unused-vars: [\"error\", { \"ignoreClassWithStaticInitBlock\": true }]*/\n\nclass Foo {\n static myProperty = \"some string\";\n static mymethod() {\n return \"some string\";\n }\n}\n\nclass Bar {\n static {\n let baz; // unused variable\n }\n}\n```\n\n\nExamples of **correct** code for the `{ \"ignoreClassWithStaticInitBlock\": true }` option\n\n**Correct code:**\n\n```js\n/*eslint no-unused-vars: [\"error\", { \"ignoreClassWithStaticInitBlock\": true }]*/\n\nclass Foo {\n static {\n let bar = \"some string\";\n\n console.log(bar);\n }\n}\n```\n\n\n### ignoreUsingDeclarations\n\nThe `ignoreUsingDeclarations` option is a boolean (default: `false`). Explicit resource management allows automatic teardown of disposables by calling `Symbol.dispose` or `Symbol.asyncDispose` method implicitly at the end of the variable's scope. When this option is set to `true`, this rule ignores variables declared with `using` or `await using`.\n\nExamples of **incorrect** code for the `{ \"ignoreUsingDeclarations\": true }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unused-vars: [\"error\", { \"ignoreUsingDeclarations\": true }]*/\nconst resource = getResource();\n```\n\n\nExamples of **correct** code for the `{ \"ignoreUsingDeclarations\": true }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-vars: [\"error\", { \"ignoreUsingDeclarations\": true }]*/\n\nusing syncResource = getSyncResource();\nawait using asyncResource = getAsyncResource();\n```\n\n\n### reportUsedIgnorePattern\n\nThe `reportUsedIgnorePattern` option is a boolean (default: `false`).\nUsing this option will report variables that match any of the valid ignore\npattern options (`varsIgnorePattern`, `argsIgnorePattern`, `caughtErrorsIgnorePattern`, or\n`destructuredArrayIgnorePattern`) if they have been used.\n\nExamples of **incorrect** code for the `{ \"reportUsedIgnorePattern\": true }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unused-vars: [\"error\", { \"reportUsedIgnorePattern\": true, \"varsIgnorePattern\": \"[iI]gnored\" }]*/\n\nconst firstVarIgnored = 1;\nconst secondVar = 2;\nconsole.log(firstVarIgnored, secondVar);\n```\n\n\nExamples of **correct** code for the `{ \"reportUsedIgnorePattern\": true }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-vars: [\"error\", { \"reportUsedIgnorePattern\": true, \"varsIgnorePattern\": \"[iI]gnored\" }]*/\n\nconst firstVar = 1;\nconst secondVar = 2;\nconsole.log(firstVar, secondVar);\n```\n\n\n## When Not To Use It\n\nIf you don't want to be notified about unused variables or function arguments, you can safely turn this rule off.",
|
|
1070
|
+
"eslint/no-useless-backreference": "In JavaScript regular expressions, it's syntactically valid to define a backreference to a group that belongs to another alternative part of the pattern, a backreference to a group that appears after the backreference, a backreference to a group that contains that backreference, or a backreference to a group that is inside a negative lookaround. However, by the specification, in any of these cases the backreference always ends up matching only zero-length (the empty string), regardless of the context in which the backreference and the group appear.\n\nBackreferences that always successfully match zero-length and cannot match anything else are useless. They are basically ignored and can be removed without changing the behavior of the regular expression.\n\n```js\nconst regex = /^(?:(a)|\\1b)$/;\n\nregex.test(\"a\"); // true\nregex.test(\"b\"); // true!\nregex.test(\"ab\"); // false\n\nconst equivalentRegex = /^(?:(a)|b)$/;\n\nequivalentRegex.test(\"a\"); // true\nequivalentRegex.test(\"b\"); // true\nequivalentRegex.test(\"ab\"); // false\n```\n\nUseless backreference is a possible error in the code. It usually indicates that the regular expression does not work as intended.\n\n## Rule Details\n\nThis rule aims to detect and disallow the following backreferences in regular expression:\n\n* Backreference to a group that is in another alternative, e.g., `/(a)|\\1b/`. In such constructed regular expression, the backreference is expected to match what's been captured in, at that point, a non-participating group.\n* Backreference to a group that appears later in the pattern, e.g., `/\\1(a)/`. The group hasn't captured anything yet, and ECMAScript doesn't support forward references. Inside lookbehinds, which match backward, the opposite applies and this rule disallows backreference to a group that appears before in the same lookbehind, e.g., `/(?<=(a)\\1)b/`.\n* Backreference to a group from within the same group, e.g., `/(\\1)/`. Similar to the previous, the group hasn't captured anything yet, and ECMAScript doesn't support nested references.\n* Backreference to a group that is in a negative lookaround, if the backreference isn't in the same negative lookaround, e.g., `/a(?!(b)).\\1/`. A negative lookaround (lookahead or lookbehind) succeeds only if its pattern cannot match, meaning that the group has failed.\n\nBy the ECMAScript specification, all backreferences listed above are valid, always succeed to match zero-length, and cannot match anything else. Consequently, they don't produce parsing or runtime errors, but also don't affect the behavior of their regular expressions. They are syntactically valid but useless.\n\nThis might be surprising to developers coming from other languages where some of these backreferences can be used in a meaningful way.\n\n```js\n// in some other languages, this pattern would successfully match \"aab\"\n\n/^(?:(a)(?=a)|\\1b)+$/.test(\"aab\"); // false\n```\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-useless-backreference: \"error\"*/\n\n/^(?:(a)|\\1b)$/; // reference to (a) into another alternative\n\n/^(?:(a)|b(?:c|\\1))$/; // reference to (a) into another alternative\n\n/^(?:a|b(?:(c)|\\1))$/; // reference to (c) into another alternative\n\n/\\1(a)/; // forward reference to (a)\n\nRegExp('(a)\\\\2(b)'); // forward reference to (b)\n\n/(?:a)(b)\\2(c)/; // forward reference to (c)\n\n/\\k<foo>(?<foo>a)/; // forward reference to (?<foo>a)\n\n/(?<=(a)\\1)b/; // backward reference to (a) from within the same lookbehind\n\n/(?<!(a)\\1)b/; // backward reference to (a) from within the same lookbehind\n\nnew RegExp('(\\\\1)'); // nested reference to (\\1)\n\n/^((a)\\1)$/; // nested reference to ((a)\\1)\n\n/a(?<foo>(.)b\\1)/; // nested reference to (?<foo>(.)b\\1)\n\n/a(?!(b)).\\1/; // reference to (b) into a negative lookahead\n\n/(?<!(a))b\\1/; // reference to (a) into a negative lookbehind\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-useless-backreference: \"error\"*/\n\n/^(?:(a)|(b)\\2)$/; // reference to (b)\n\n/(a)\\1/; // reference to (a)\n\nRegExp('(a)\\\\1(b)'); // reference to (a)\n\n/(a)(b)\\2(c)/; // reference to (b)\n\n/(?<foo>a)\\k<foo>/; // reference to (?<foo>a)\n\n/(?<=\\1(a))b/; // reference to (a), correctly before the group as they're in the same lookbehind\n\n/(?<=(a))b\\1/; // reference to (a), correctly after the group as the backreference isn't in the lookbehind\n\nnew RegExp('(.)\\\\1'); // reference to (.)\n\n/^(?:(a)\\1)$/; // reference to (a)\n\n/^((a)\\2)$/; // reference to (a)\n\n/a(?<foo>(.)b\\2)/; // reference to (.)\n\n/a(?!(b|c)\\1)./; // reference to (b|c), correct as it's from within the same negative lookahead\n\n/(?<!\\1(a))b/; // reference to (a), correct as it's from within the same negative lookbehind\n```\n\n\nPlease note that this rule does not aim to detect and disallow a potentially erroneous use of backreference syntax in regular expressions, like the use in character classes or an attempt to reference a group that doesn't exist. Depending on the context, a `\\1`...`\\9` sequence that is not a syntactically valid backreference may produce syntax error, or be parsed as something else (e.g., as a legacy octal escape sequence).\n\nExamples of additional **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-useless-backreference: \"error\"*/\n\n// comments describe behavior in a browser\n\n/^[\\1](a)$/.test(\"\\x01a\"); // true. In a character class, \\1 is treated as an octal escape sequence.\n/^\\1$/.test(\"\\x01\"); // true. Since the group 1 doesn't exist, \\1 is treated as an octal escape sequence.\n/^(a)\\1\\2$/.test(\"aa\\x02\"); // true. In this case, \\1 is a backreference, \\2 is an octal escape sequence.\n```\n\n\n## Options\n\nThis rule has no options.",
|
|
1071
|
+
"eslint/no-useless-catch": "A `catch` clause that only rethrows the original error is redundant, and has no effect on the runtime behavior of the program. These redundant clauses can be a source of confusion and code bloat, so it's better to disallow these unnecessary `catch` clauses.\n\n## Rule Details\n\nThis rule reports `catch` clauses that only `throw` the caught error.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-useless-catch: \"error\"*/\n\ntry {\n doSomethingThatMightThrow();\n} catch (e) {\n throw e;\n}\n\ntry {\n doSomethingThatMightThrow();\n} catch (e) {\n throw e;\n} finally {\n cleanUp();\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-useless-catch: \"error\"*/\n\ntry {\n doSomethingThatMightThrow();\n} catch (e) {\n doSomethingBeforeRethrow();\n throw e;\n}\n\ntry {\n doSomethingThatMightThrow();\n} catch (e) {\n handleError(e);\n}\n\ntry {\n doSomethingThatMightThrow();\n} finally {\n cleanUp();\n}\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nIf you don't want to be notified about unnecessary catch clauses, you can safely disable this rule.",
|
|
1072
|
+
"eslint/no-useless-escape": "Escaping non-special characters in strings, template literals, and regular expressions doesn't have any effect, as demonstrated in the following example:\n\n```js\nlet foo = \"hol\\a\"; // > foo = \"hola\"\nlet bar = `${foo}\\!`; // > bar = \"hola!\"\nlet baz = /\\:/ // same functionality with /:/\n```\n\n## Rule Details\n\nThis rule flags escapes that can be safely removed without changing behavior.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-useless-escape: \"error\"*/\n\n\"\\'\";\n'\\\"';\n\"\\#\";\n\"\\e\";\n`\\\"`;\n`\\\"${foo}\\\"`;\n`\\#{foo}`;\n/\\!/;\n/\\@/;\n/[\\[]/;\n/[a-z\\-]/;\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-useless-escape: \"error\"*/\n\n\"\\\"\";\n'\\'';\n\"\\x12\";\n\"\\u00a9\";\n\"\\371\";\n\"xs\\u2111\";\n`\\``;\n`\\${${foo}}`;\n`$\\{${foo}}`;\n/\\\\/g;\n/\\t/g;\n/\\w\\$\\*\\^\\./;\n/[[]/;\n/[\\]]/;\n/[a-z-]/;\n```\n\n\n## Options\n\nThis rule has an object option:\n\n* `allowRegexCharacters` - An array of characters that should be allowed to have unnecessary escapes in regular expressions. This is useful for characters like `-` where escaping can prevent accidental character ranges. For example, in `/[0\\-]/`, the escape is technically unnecessary but helps prevent the pattern from becoming a range if another character is added later (e.g., `/[0\\-9]/` vs `/[0-9]/`).\n\n### allowRegexCharacters\n\nExamples of **incorrect** code for the `{ \"allowRegexCharacters\": [\"-\"] }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-useless-escape: [\"error\", { \"allowRegexCharacters\": [\"-\"] }]*/\n\n/\\!/;\n/\\@/;\n/[a-z\\^]/;\n```\n\n\nExamples of **correct** code for the `{ \"allowRegexCharacters\": [\"-\"] }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-useless-escape: [\"error\", { \"allowRegexCharacters\": [\"-\"] }]*/\n\n/[0\\-]/;\n/[\\-9]/;\n/a\\-b/;\n```\n\n\n## When Not To Use It\n\nIf you don't want to be notified about unnecessary escapes, you can safely disable this rule.",
|
|
1073
|
+
"eslint/no-with": "The `with` statement is potentially problematic because it adds members of an object to the current scope, making it impossible to tell what a variable inside the block actually refers to.\n\n## Rule Details\n\nThis rule disallows `with` statements.\n\nIf ESLint parses code in strict mode, the parser (instead of this rule) reports the error.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-with: \"error\"*/\n\nwith (point) {\n r = Math.sqrt(x * x + y * y); // is r a member of point?\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-with: \"error\"*/\n\nconst r = ({x, y}) => Math.sqrt(x * x + y * y);\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nIf you intentionally use `with` statements then you can disable this rule.",
|
|
1074
|
+
"eslint/require-yield": "## Rule Details\n\nThis rule generates warnings for generator functions that do not have the `yield` keyword.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint require-yield: \"error\"*/\n\nfunction* foo() {\n return 10;\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint require-yield: \"error\"*/\n\nfunction* foo() {\n yield 5;\n return 10;\n}\n\nfunction bar() {\n return 10;\n}\n\n// This rule does not warn on empty generator functions.\nfunction* baz() { }\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nIf you don't want to notify generator functions that have no `yield` expression, then it's safe to disable this rule.",
|
|
1075
|
+
"eslint/use-isnan": "In JavaScript, `NaN` is a special value of the `Number` type. It's used to represent any of the \"not-a-number\" values represented by the double-precision 64-bit format as specified by the IEEE Standard for Binary Floating-Point Arithmetic.\n\nBecause `NaN` is unique in JavaScript by not being equal to anything, including itself, the results of comparisons to `NaN` are confusing:\n\n* `NaN === NaN` or `NaN == NaN` evaluate to `false`\n* `NaN !== NaN` or `NaN != NaN` evaluate to `true`\n\nTherefore, use `Number.isNaN()` or global `isNaN()` functions to test whether a value is `NaN`.\n\n## Rule Details\n\nThis rule disallows comparisons to `NaN`.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint use-isnan: \"error\"*/\n\nif (foo == NaN) {\n // ...\n}\n\nif (foo != NaN) {\n // ...\n}\n\nif (foo == Number.NaN) {\n // ...\n}\n\nif (foo != Number.NaN) {\n // ...\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint use-isnan: \"error\"*/\n\nif (isNaN(foo)) {\n // ...\n}\n\nif (!isNaN(foo)) {\n // ...\n}\n```\n\n\n## Options\n\nThis rule has an object option, with two options:\n\n* `\"enforceForSwitchCase\": true` (default) additionally disallows `case NaN` and `switch(NaN)` in `switch` statements.\n* `\"enforceForIndexOf\": true` additionally disallows the use of `indexOf` and `lastIndexOf` methods with `NaN`. Default is `false`, meaning that this rule by default does not warn about `indexOf(NaN)` or `lastIndexOf(NaN)` method calls.\n\n### enforceForSwitchCase\n\nThe `switch` statement internally uses the `===` comparison to match the expression's value to a case clause.\nTherefore, it can never match `case NaN`. Also, `switch(NaN)` can never match a case clause.\n\nExamples of **incorrect** code for this rule with `\"enforceForSwitchCase\"` option set to `true` (default):\n\n**Incorrect code:**\n\n```js\n/*eslint use-isnan: [\"error\", {\"enforceForSwitchCase\": true}]*/\n\nswitch (foo) {\n case NaN:\n bar();\n break;\n case 1:\n baz();\n break;\n // ...\n}\n\nswitch (NaN) {\n case a:\n bar();\n break;\n case b:\n baz();\n break;\n // ...\n}\n\nswitch (foo) {\n case Number.NaN:\n bar();\n break;\n case 1:\n baz();\n break;\n // ...\n}\n\nswitch (Number.NaN) {\n case a:\n bar();\n break;\n case b:\n baz();\n break;\n // ...\n}\n```\n\n\nExamples of **correct** code for this rule with `\"enforceForSwitchCase\"` option set to `true` (default):\n\n**Correct code:**\n\n```js\n/*eslint use-isnan: [\"error\", {\"enforceForSwitchCase\": true}]*/\n\nif (Number.isNaN(foo)) {\n bar();\n} else {\n switch (foo) {\n case 1:\n baz();\n break;\n // ...\n }\n}\n\nif (Number.isNaN(a)) {\n bar();\n} else if (Number.isNaN(b)) {\n baz();\n} // ...\n```\n\n\nExamples of **correct** code for this rule with `\"enforceForSwitchCase\"` option set to `false`:\n\n**Correct code:**\n\n```js\n/*eslint use-isnan: [\"error\", {\"enforceForSwitchCase\": false}]*/\n\nswitch (foo) {\n case NaN:\n bar();\n break;\n case 1:\n baz();\n break;\n // ...\n}\n\nswitch (NaN) {\n case a:\n bar();\n break;\n case b:\n baz();\n break;\n // ...\n}\n\nswitch (foo) {\n case Number.NaN:\n bar();\n break;\n case 1:\n baz();\n break;\n // ...\n}\n\nswitch (Number.NaN) {\n case a:\n bar();\n break;\n case b:\n baz();\n break;\n // ...\n}\n```\n\n\n### enforceForIndexOf\n\nThe following methods internally use the `===` comparison to match the given value with an array element:\n\n* [`Array.prototype.indexOf`](https://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.indexof)\n* [`Array.prototype.lastIndexOf`](https://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.lastindexof)\n\nTherefore, for any array `foo`, `foo.indexOf(NaN)` and `foo.lastIndexOf(NaN)` will always return `-1`.\n\nSet `\"enforceForIndexOf\"` to `true` if you want this rule to report `indexOf(NaN)` and `lastIndexOf(NaN)` method calls.\n\nExamples of **incorrect** code for this rule with `\"enforceForIndexOf\"` option set to `true`:\n\n**Incorrect code:**\n\n```js\n/*eslint use-isnan: [\"error\", {\"enforceForIndexOf\": true}]*/\n\nconst hasNaN = myArray.indexOf(NaN) >= 0;\n\nconst firstIndex = myArray.indexOf(NaN);\n\nconst lastIndex = myArray.lastIndexOf(NaN);\n\nconst indexWithSequenceExpression = myArray.indexOf((doStuff(), NaN));\n\nconst firstIndexFromSecondElement = myArray.indexOf(NaN, 1);\n\nconst lastIndexFromSecondElement = myArray.lastIndexOf(NaN, 1);\n```\n\n\nExamples of **correct** code for this rule with `\"enforceForIndexOf\"` option set to `true`:\n\n**Correct code:**\n\n```js\n/*eslint use-isnan: [\"error\", {\"enforceForIndexOf\": true}]*/\n\nfunction myIsNaN(val) {\n return typeof val === \"number\" && isNaN(val);\n}\n\nfunction indexOfNaN(arr) {\n for (let i = 0; i < arr.length; i++) {\n if (myIsNaN(arr[i])) {\n return i;\n }\n }\n return -1;\n}\n\nfunction lastIndexOfNaN(arr) {\n for (let i = arr.length - 1; i >= 0; i--) {\n if (myIsNaN(arr[i])) {\n return i;\n }\n }\n return -1;\n}\n\nconst hasNaN = myArray.some(myIsNaN);\n\nconst hasNaN1 = indexOfNaN(myArray) >= 0;\n\nconst firstIndex = indexOfNaN(myArray);\n\nconst lastIndex = lastIndexOfNaN(myArray);\n\n// ES2015\nconst hasNaN2 = myArray.some(Number.isNaN);\n\n// ES2015\nconst firstIndex1 = myArray.findIndex(Number.isNaN);\n\n// ES2016\nconst hasNaN3 = myArray.includes(NaN);\n```\n\n\n#### Known Limitations\n\nThis option checks methods with the given names, *even if* the object which has the method is *not* an array.",
|
|
1076
|
+
"eslint/valid-typeof": "For a vast majority of use cases, the result of the `typeof` operator is one of the following string literals: `\"undefined\"`, `\"object\"`, `\"boolean\"`, `\"number\"`, `\"string\"`, `\"function\"`, `\"symbol\"`, and `\"bigint\"`. It is usually a typing mistake to compare the result of a `typeof` operator to other string literals.\n\n## Rule Details\n\nThis rule enforces comparing `typeof` expressions to valid string literals.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint valid-typeof: \"error\"*/\n\ntypeof foo === \"strnig\"\ntypeof foo == \"undefimed\"\ntypeof bar != \"nunber\"\ntypeof bar !== \"fucntion\"\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint valid-typeof: \"error\"*/\n\ntypeof foo === \"string\"\ntypeof bar == \"undefined\"\ntypeof foo === baz\ntypeof bar === typeof qux\n```\n\n\n## Options\n\nThis rule has an object option:\n\n* `\"requireStringLiterals\": true` allows the comparison of `typeof` expressions with only string literals or other `typeof` expressions, and disallows comparisons to any other value. Default is `false`.\n\n### requireStringLiterals\n\nExamples of **incorrect** code with the `{ \"requireStringLiterals\": true }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint valid-typeof: [\"error\", { \"requireStringLiterals\": true }]*/\n\ntypeof foo === undefined\ntypeof bar == Object\ntypeof baz === \"strnig\"\ntypeof qux === \"some invalid type\"\ntypeof baz === anotherVariable\ntypeof foo == 5\n```\n\n\nExamples of **correct** code with the `{ \"requireStringLiterals\": true }` option:\n\n**Correct code:**\n\n```js\n/*eslint valid-typeof: [\"error\", { \"requireStringLiterals\": true }]*/\n\ntypeof foo === \"undefined\"\ntypeof bar == \"object\"\ntypeof baz === \"string\"\ntypeof bar === typeof qux\n```\n\n\n## When Not To Use It\n\nYou may want to turn this rule off if you will be using the `typeof` operator on host objects.",
|
|
1077
|
+
"eslint/security/detect-buffer-noassert": "# Detects calls to \"buffer\" with \"noAssert\" flag set (`security/detect-buffer-noassert`)\n\n\u26a0\ufe0f This rule _warns_ in the \u2705 `recommended` config.\n\n<!-- end auto-generated rule header -->\n\nDetect calls to [`buffer`](https://nodejs.org/api/buffer.html) with `noAssert` flag set.\n\nFrom the Node.js API docs: \"Setting `noAssert` to true skips validation of the `offset`. This allows the `offset` to be beyond the end of the `Buffer`.\"",
|
|
1078
|
+
"eslint/security/detect-child-process": "# Detects instances of \"child_process\" & non-literal \"exec()\" calls (`security/detect-child-process`)\n\n\u26a0\ufe0f This rule _warns_ in the \u2705 `recommended` config.\n\n<!-- end auto-generated rule header -->\n\nDetect instances of [`child_process`](https://nodejs.org/api/child_process.html) & non-literal [`exec()`](https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback)\n\nMore information: [Avoiding Command Injection in Node.js](../avoid-command-injection-node.md)",
|
|
1079
|
+
"eslint/security/detect-disable-mustache-escape": "# Detects \"object.escapeMarkup = false\", which can be used with some template engines to disable escaping of HTML entities (`security/detect-disable-mustache-escape`)\n\n\u26a0\ufe0f This rule _warns_ in the \u2705 `recommended` config.\n\n<!-- end auto-generated rule header -->\n\nThis can lead to Cross-Site Scripting (XSS) vulnerabilities.\n\nMore information: [OWASP XSS](<https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)>)",
|
|
1080
|
+
"eslint/security/detect-eval-with-expression": "# Detects \"eval(variable)\" which can allow an attacker to run arbitrary code inside your process (`security/detect-eval-with-expression`)\n\n\u26a0\ufe0f This rule _warns_ in the \u2705 `recommended` config.\n\n<!-- end auto-generated rule header -->\n\nMore information: [What are the security issues with eval in JavaScript?](http://security.stackexchange.com/questions/94017/what-are-the-security-issues-with-eval-in-javascript)",
|
|
1081
|
+
"eslint/security/detect-new-buffer": "# Detects instances of new Buffer(argument) where argument is any non-literal value (`security/detect-new-buffer`)\n\n\u26a0\ufe0f This rule _warns_ in the \u2705 `recommended` config.\n\n<!-- end auto-generated rule header -->\n\n`new Buffer()` now emits a deprecation warning in Node.js.\n\nMore information: [new Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660)",
|
|
1082
|
+
"eslint/security/detect-no-csrf-before-method-override": "# Detects Express \"csrf\" middleware setup before \"method-override\" middleware (`security/detect-no-csrf-before-method-override`)\n\n\u26a0\ufe0f This rule _warns_ in the \u2705 `recommended` config.\n\n<!-- end auto-generated rule header -->\n\nThis can allow `GET` requests (which are not checked by `csrf`) to turn into `POST` requests later.\n\nMore information: [Bypass Connect CSRF protection by abusing methodOverride Middleware](../bypass-connect-csrf-protection-by-abusing.md)",
|
|
1083
|
+
"eslint/security/detect-non-literal-fs-filename": "# Detects variable in filename argument of \"fs\" calls, which might allow an attacker to access anything on your system (`security/detect-non-literal-fs-filename`)\n\n\u26a0\ufe0f This rule _warns_ in the \u2705 `recommended` config.\n\n<!-- end auto-generated rule header -->\n\nMore information: [OWASP Path Traversal](https://www.owasp.org/index.php/Path_Traversal)",
|
|
1084
|
+
"eslint/security/detect-non-literal-regexp": "# Detects \"RegExp(variable)\", which might allow an attacker to DOS your server with a long-running regular expression (`security/detect-non-literal-regexp`)\n\n\u26a0\ufe0f This rule _warns_ in the \u2705 `recommended` config.\n\n<!-- end auto-generated rule header -->\n\nMore information: [Regular Expression DoS and Node.js](../regular-expression-dos-and-node.md)",
|
|
1085
|
+
"eslint/security/detect-non-literal-require": "# Detects \"require(variable)\", which might allow an attacker to load and run arbitrary code, or access arbitrary files on disk (`security/detect-non-literal-require`)\n\n\u26a0\ufe0f This rule _warns_ in the \u2705 `recommended` config.\n\n<!-- end auto-generated rule header -->\n\nMore information: [Where does Node.js and require look for modules?](http://www.bennadel.com/blog/2169-where-does-node-js-and-require-look-for-modules.htm)",
|
|
1086
|
+
"eslint/security/detect-object-injection": "# Detects \"variable[key]\" as a left- or right-hand assignment operand (`security/detect-object-injection`)\n\n\u26a0\ufe0f This rule _warns_ in the \u2705 `recommended` config.\n\n<!-- end auto-generated rule header -->\n\nJavaScript allows you to use expressions to access object properties in addition to using dot notation. So instead of writing this:\n\n```js\nobject.name = 'foo';\n```\n\nYou can write this:\n\n```js\nobject['name'] = 'foo';\n```\n\nSquare bracket notation allows any expression to be used in place of an identifier, so you can also do this:\n\n```js\nconst key = 'name';\nobject[key] = 'foo';\n```\n\nBy doing so, you've now obfuscated the property name from the reader, which makes it easy for a malicious actor to replace the value of `key` and change the behavior of the code.\n\nThis rule flags any expression in the form of `object[expression]` no matter where it occurs. Examples of patterns this will be flagged are:\n\n```js\nobject[key] = value;\n\nvalue = object[key];\n\ndoSomething(object[key]);\n```\n\nMore information: [The Dangers of Square Bracket Notation](../the-dangers-of-square-bracket-notation.md)",
|
|
1087
|
+
"eslint/security/detect-possible-timing-attacks": "# Detects insecure comparisons (`==`, `!=`, `!==` and `===`), which check input sequentially (`security/detect-possible-timing-attacks`)\n\n\u26a0\ufe0f This rule _warns_ in the \u2705 `recommended` config.\n\n<!-- end auto-generated rule header -->",
|
|
1088
|
+
"eslint/security/detect-pseudoRandomBytes": "# Detects if \"pseudoRandomBytes()\" is in use, which might not give you the randomness you need and expect (`security/detect-pseudoRandomBytes`)\n\n\u26a0\ufe0f This rule _warns_ in the \u2705 `recommended` config.\n\n<!-- end auto-generated rule header -->",
|
|
1089
|
+
"eslint/security/detect-unsafe-regex": "# Detects potentially unsafe regular expressions, which may take a very long time to run, blocking the event loop (`security/detect-unsafe-regex`)\n\n\u26a0\ufe0f This rule _warns_ in the \u2705 `recommended` config.\n\n<!-- end auto-generated rule header -->\n\nMore information: [Regular Expression DoS and Node.js](../regular-expression-dos-and-node.md)",
|
|
1090
|
+
"eslint/security/detect-bidi-characters": "# Detects trojan source attacks that employ unicode bidi attacks to inject malicious code (`security/detect-bidi-characters`)\n\n\u26a0\ufe0f This rule _warns_ in the \u2705 `recommended` config.\n\n<!-- end auto-generated rule header -->\n\nDetects cases of [trojan source attacks](https://trojansource.codes) that employ unicode bidi attacks to inject malicious code\n\n## Why is Trojan Source important?\n\nThe following publication on the topic of unicode characters attacks, dubbed [Trojan Source: Invisible Vulnerabilities](https://trojansource.codes/trojan-source.pdf), has caused a lot of concern from potential supply chain attacks where adversaries are able to inject malicious code into the source code of a project, slipping by unseen in the code review process.\n\n### An example\n\nAs an example, take the following code where `RLO`, `LRI`, `PDI`, `IRI` are placeholders to visualise the respective dangerous unicode characters:\n\n```js\n#!/usr/bin/env node\n\nvar accessLevel = 'user';\n\nif (accessLevel != 'userRLO LRI// Check if adminPDI IRI') {\n console.log('You are an admin.');\n}\n```\n\nThe code above, will be rendered by a text editor as follows:\n\n```js\n#!/usr/bin/env node\n\nvar accessLevel = 'user';\n\nif (accessLevel != 'user') {\n // Check if admin\n console.log('You are an admin.');\n}\n```\n\nBy looking at the rendered code above, a user reviewing this code might not notice the injected malicious unicode characters which are actually changing the semantic and the behaviour of the actual code.\n\n### More information\n\nFor more information on the topic, you're welcome to read on the official website [trojansource.codes](https://trojansource.codes/) and the following [source code repository](https://github.com/nickboucher/trojan-source/) which contains the source code of the publication.\n\n### References\n\n- <https://certitude.consulting/blog/en/invisible-backdoor/>\n- <https://github.com/lirantal/anti-trojan-source/>\n- <https://github.com/lirantal/eslint-plugin-anti-trojan-source>",
|
|
1091
|
+
"eslint/security/detect-invisible-characters": "# Detects invisible characters that have no visible glyph and can be used to hide malicious code (`security/detect-invisible-characters`)\n\n\u26a0\ufe0f This rule _warns_ in the \u2705 `recommended` config.\n\n<!-- end auto-generated rule header -->\n\nDetects the presence of invisible characters (characters that have no visible glyph) in source code and comments. Because such characters are rendered as nothing by editors and code review tools, an attacker can use them to hide malicious code that passes human review unnoticed (an \"invisible backdoor\").\n\nThis rule currently detects:\n\n- `U+3164` HANGUL FILLER\n- `U+FFA0` HALFWIDTH HANGUL FILLER\n\nBoth are valid JavaScript source characters (in strings, comments, and even identifiers) yet display as nothing, making them dangerous.\n\n## Why is this important?\n\nAttacks that rely on visually deceptive or invisible unicode characters have been used to smuggle logic past code review. Unlike [trojan source](https://trojansource.codes/) bidirectional attacks (covered by [`detect-bidi-characters`](./detect-bidi-characters.md)), these characters do not reorder text. They simply render as empty space, so a reviewer sees nothing where a malicious token actually lives.\n\n### An example\n\nIn the snippet below the two identifiers look identical, but the second one contains a hidden `U+3164` character between `adm` and `in`. They are therefore two different variables, and the `admin` a reviewer trusts is not the one that ends up being used.\n\n```js\nconst admin = false;\nconst admin = true; // the second `admin` actually contains a hidden U+3164 character\n```\n\n## Known limitations\n\n- This rule only flags invisible characters that appear literally in the source. A visible escape sequence such as `\"\\u3164\"` is not itself an invisible character in the source text, so it is not reported (and it stays plainly readable during review anyway).\n- Because `U+3164` is sometimes used as a blank placeholder in Korean-language content (for example, empty-looking usernames or visual spacing), the rule may report intentional uses in such codebases. The rule cannot distinguish an intentional placeholder from a hidden one.\n\n## Further Reading\n\n- <https://certitude.consulting/blog/en/invisible-backdoor/>\n- <https://trojansource.codes/>",
|
|
1092
|
+
"eslint/eqeqeq": "It is considered good practice to use the type-safe equality operators `===` and `!==` instead of their regular counterparts `==` and `!=`.\n\nThe reason for this is that `==` and `!=` do type coercion which follows the rather obscure [Abstract Equality Comparison Algorithm](https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3).\nFor instance, the following statements are all considered `true`:\n\n* `[] == false`\n* `[] == ![]`\n* `3 == \"03\"`\n\nIf one of those occurs in an innocent-looking statement such as `a == b` the actual problem is very difficult to spot.\n\n## Rule Details\n\nThis rule is aimed at eliminating the type-unsafe equality operators.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint eqeqeq: \"error\"*/\n\nif (x == 42) { }\n\nif (\"\" == text) { }\n\nif (obj.getStuff() != undefined) { }\n```\n\n\nThe `--fix` option on the command line automatically fixes some problems reported by this rule. A problem is only fixed if one of the operands is a `typeof` expression, or if both operands are literals with the same type.\n\nIn other cases a suggestion is offered which can change runtime behavior if the operands have different types.\n\n## Options\n\n### always\n\nThe `\"always\"` option (default) enforces the use of `===` and `!==` in every situation (except when you opt-in to more specific handling of `null` [see below]).\n\nExamples of **incorrect** code for the `\"always\"` option:\n\n**Incorrect code:**\n\n```js\n/*eslint eqeqeq: [\"error\", \"always\"]*/\n\na == b\nfoo == true\nbananas != 1\nvalue == undefined\ntypeof foo == 'undefined'\n'hello' != 'world'\n0 == 0\ntrue == true\nfoo == null\n\n```\n\n\nExamples of **correct** code for the `\"always\"` option:\n\n**Correct code:**\n\n```js\n/*eslint eqeqeq: [\"error\", \"always\"]*/\n\na === b\nfoo === true\nbananas !== 1\nvalue === undefined\ntypeof foo === 'undefined'\n'hello' !== 'world'\n0 === 0\ntrue === true\nfoo === null\n\n```\n\n\nThis rule optionally takes a second argument, which should be an object with the following supported properties:\n\n* `\"null\"`: Customize how this rule treats `null` literals. Possible values:\n * `always` (default) - Always use `===` or `!==`.\n * `never` - Never use `===` or `!==` with `null`.\n * `ignore` - Do not apply this rule to `null`.\n\n### smart\n\nThe `\"smart\"` option enforces the use of `===` and `!==` except for these cases:\n\n* Comparing two literal values.\n* Evaluating the value of `typeof`.\n* Comparing against `null`.\n\nExamples of **incorrect** code for the `\"smart\"` option:\n\n**Incorrect code:**\n\n```js\n/*eslint eqeqeq: [\"error\", \"smart\"]*/\n\n// comparing two variables requires ===\na == b\n\n// only one side is a literal\nfoo == true\nbananas != 1\n\n// comparing to undefined requires ===\nvalue == undefined\n```\n\n\nExamples of **correct** code for the `\"smart\"` option:\n\n**Correct code:**\n\n```js\n/*eslint eqeqeq: [\"error\", \"smart\"]*/\n\ntypeof foo == 'undefined'\n'hello' != 'world'\n0 == 0\ntrue == true\nfoo == null\n```\n\n\n### allow-null\n\n**Deprecated:** Instead of using this option use `\"always\"` and pass a `\"null\"` option property with value `\"ignore\"`. This will tell ESLint to always enforce strict equality except when comparing with the `null` literal.\n\n```js\n[\"error\", \"always\", {\"null\": \"ignore\"}]\n```\n\n## When Not To Use It\n\nIf you don't want to enforce a style for using equality operators, then it's safe to disable this rule.",
|
|
1093
|
+
"eslint/no-var": "ECMAScript 6 allows programmers to create variables with block scope instead of function scope using the `let`\nand `const` keywords. Block scope is common in many other programming languages and helps programmers avoid mistakes\nsuch as:\n\n```js\nvar count = people.length;\nvar enoughFood = sandwiches.length >= count;\n\nif (enoughFood) {\n var count = sandwiches.length; // accidentally overriding the count variable\n console.log(\"We have \" + count + \" sandwiches for everyone. Plenty for all!\");\n}\n\n// our count variable is no longer accurate\nconsole.log(\"We have \" + count + \" people and \" + sandwiches.length + \" sandwiches!\");\n```\n\n## Rule Details\n\nThis rule is aimed at discouraging the use of `var` and encouraging the use of `const` or `let` instead.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-var: \"error\"*/\n\nvar x = \"y\";\nvar CONFIG = {};\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-var: \"error\"*/\n\nlet x = \"y\";\nconst CONFIG = {};\n```\n\n\nThis rule additionally supports TypeScript type syntax. There are multiple ways to declare global variables in TypeScript. Only using `var` works for all cases. See this [TypeScript playground](https://www.typescriptlang.org/play/?#code/PQgEB4CcFMDNpgOwMbVAGwJYCMC8AiAEwHsBbfUYAPgFgAoew6ZdAQxlAHN1jtX1QAb3qhRGaABdQAGUkAuUAGcJkTIk4ixAN3agAauwXLV6+ptFqJCWK1SgA6mpIB3IebGjHiIyrUa6HgC+9MEMdGDcvPygtqiKivSyEvQGkPReZuHAoM5OxK6ckvS5iC4AdEnFec5lqVWl+WUZYWAlLkpFdG2NSaC4oADkA-XlqX2Dw13VTWrjQ5kRPHzoACoAFpiKXJ2Ry+ubFTtL-PuKtez0uycbZ830i1GrNx3JdFdPB73982-HH2djb6Td6nGaIOaTe7ZRTQdCwbavGFww6I2Gwc5pOhI9F3LIdOEvejYlEQolojGkrHkryU+jQAAeAAdiJApIJAkA) for reference.\n\nExamples of **incorrect** TypeScript code for this rule:\n\n**Incorrect code:**\n\n```ts\n/*eslint no-var: \"error\"*/\n\ndeclare var x: number\n\ndeclare namespace ns {\n\tvar x: number\n}\n\ndeclare module 'module' {\n\tvar x: number\n}\n```\n\n\nExamples of **correct** TypeScript code for this rule:\n\n**Correct code:**\n\n```ts\n/*eslint no-var: \"error\"*/\n\ndeclare global {\n declare var x: number\n}\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nIn addition to non-ES6 environments, existing JavaScript projects that are beginning to introduce ES6 into their\ncodebase may not want to apply this rule if the cost of migrating from `var` to `let` is too costly.",
|
|
1094
|
+
"eslint/prefer-const": "If a variable is never reassigned, using the `const` declaration is better.\n\n`const` declaration tells readers, \"this variable is never reassigned,\" reducing cognitive load and improving maintainability.\n\n## Rule Details\n\nThis rule is aimed at flagging variables that are declared using the `let` keyword, but never reassigned after the initial assignment.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint prefer-const: \"error\"*/\n\n// it's initialized and never reassigned.\nlet a = 3;\nconsole.log(a);\n\nlet b;\nb = 0;\nconsole.log(b);\n\nclass C {\n static {\n let a;\n a = 0;\n console.log(a);\n }\n}\n\n// `i` is redefined (not reassigned) on each loop step.\nfor (let i in [1, 2, 3]) {\n console.log(i);\n}\n\n// `a` is redefined (not reassigned) on each loop step.\nfor (let a of [1, 2, 3]) {\n console.log(a);\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint prefer-const: \"error\"*/\n\n// using const.\nconst a = 0;\n\n// it's never initialized.\nlet b;\nconsole.log(b);\n\n// it's reassigned after initialized.\nlet c;\nc = 0;\nc = 1;\nconsole.log(c);\n\n// it's initialized in a different block from the declaration.\nlet d;\nif (true) {\n d = 0;\n}\nconsole.log(d);\n\n// it's initialized in a different scope.\nlet e;\nclass C {\n #x;\n static {\n e = obj => obj.#x;\n }\n}\n\n// it's initialized at a place that we cannot write a variable declaration.\nlet f;\nif (true) f = 0;\nconsole.log(f);\n\n// `i` gets a new binding each iteration\nfor (const i in [1, 2, 3]) {\n console.log(i);\n}\n\n// `a` gets a new binding each iteration\nfor (const a of [1, 2, 3]) {\n console.log(a);\n}\n\n// `end` is never reassigned, but we cannot separate the declarations without modifying the scope.\nfor (let i = 0, end = 10; i < end; ++i) {\n console.log(i);\n}\n\n// `predicate` is only assigned once but cannot be separately declared as `const`\nlet predicate;\n[object.type, predicate] = foo();\n\n// `g` is only assigned once but cannot be separately declared as `const`\nlet g;\nconst h = {};\n({ g, c: h.c } = func());\n\n// suggest to use `no-var` rule.\nvar i = 3;\nconsole.log(i);\n```\n\n\n## Options\n\n```json\n{\n \"prefer-const\": [\"error\", {\n \"destructuring\": \"any\",\n \"ignoreReadBeforeAssign\": false\n }]\n}\n```\n\n### destructuring\n\nThe kind of the way to address variables in destructuring.\nThere are 2 values:\n\n* `\"any\"` (default) - If any variables in destructuring should be `const`, this rule warns for those variables.\n* `\"all\"` - If all variables in destructuring should be `const`, this rule warns for those variables. Otherwise, ignores them.\n\nExamples of **incorrect** code for the default `{\"destructuring\": \"any\"}` option:\n\n**Incorrect code:**\n\n```js\n/*eslint prefer-const: \"error\"*/\n\nlet {a, b} = obj; /*error 'b' is never reassigned, use 'const' instead.*/\na = a + 1;\n```\n\n\nExamples of **correct** code for the default `{\"destructuring\": \"any\"}` option:\n\n**Correct code:**\n\n```js\n/*eslint prefer-const: \"error\"*/\n\n// using const.\nconst {a: a0, b} = obj;\nconst a = a0 + 1;\n\n// all variables are reassigned.\nlet {c, d} = obj;\nc = c + 1;\nd = d + 1;\n```\n\n\nExamples of **incorrect** code for the `{\"destructuring\": \"all\"}` option:\n\n**Incorrect code:**\n\n```js\n/*eslint prefer-const: [\"error\", {\"destructuring\": \"all\"}]*/\n\n// all of `a` and `b` should be const, so those are warned.\nlet {a, b} = obj; /*error 'a' is never reassigned, use 'const' instead.\n 'b' is never reassigned, use 'const' instead.*/\n```\n\n\nExamples of **correct** code for the `{\"destructuring\": \"all\"}` option:\n\n**Correct code:**\n\n```js\n/*eslint prefer-const: [\"error\", {\"destructuring\": \"all\"}]*/\n\n// 'b' is never reassigned, but all of `a` and `b` should not be const, so those are ignored.\nlet {a, b} = obj;\na = a + 1;\n```\n\n\n### ignoreReadBeforeAssign\n\nThis is an option to avoid conflicting with `no-use-before-define` rule (without `\"nofunc\"` option).\nIf `true` is specified, this rule will ignore variables that are read between the declaration and the first assignment.\nDefault is `false`.\n\nExamples of **correct** code for the `{\"ignoreReadBeforeAssign\": true}` option:\n\n**Correct code:**\n\n```js\n/*eslint prefer-const: [\"error\", {\"ignoreReadBeforeAssign\": true}]*/\n\nlet timer;\nfunction initialize() {\n if (foo()) {\n clearInterval(timer);\n }\n}\ntimer = setInterval(initialize, 100);\n```\n\n\nExamples of **correct** code for the default `{\"ignoreReadBeforeAssign\": false}` option:\n\n**Correct code:**\n\n```js\n/*eslint prefer-const: [\"error\", {\"ignoreReadBeforeAssign\": false}]*/\n\nconst timer = setInterval(initialize, 100);\nfunction initialize() {\n if (foo()) {\n clearInterval(timer);\n }\n}\n```\n\n\n## When Not To Use It\n\nIf you don't want to be notified about variables that are never reassigned after initial assignment, you can safely disable this rule.",
|
|
1095
|
+
"eslint/no-eval": "JavaScript's `eval()` function is potentially dangerous and is often misused. Using `eval()` on untrusted code can open a program up to several different injection attacks. The use of `eval()` in most contexts can be substituted for a better, alternative approach to a problem.\n\n```js\nconst obj = { x: \"foo\" },\n key = \"x\",\n value = eval(\"obj.\" + key);\n```\n\n## Rule Details\n\nThis rule is aimed at preventing potentially dangerous, unnecessary, and slow code by disallowing the use of the `eval()` function. As such, it will warn whenever the `eval()` function is used.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-eval: \"error\"*/\n\nconst obj = { x: \"foo\" },\n key = \"x\",\n value = eval(\"obj.\" + key);\n\n(0, eval)(\"const a = 0\");\n\nconst foo = eval;\nfoo(\"const a = 0\");\n\n// This `this` is the global object.\nthis.eval(\"const a = 0\");\n```\n\n\nExample of additional **incorrect** code for this rule with `window` global variable:\n\n**Incorrect code:**\n\n```js\n/*eslint no-eval: \"error\"*/\n/*global window*/\n\nwindow.eval(\"const a = 0\");\n```\n\n\nExample of additional **incorrect** code for this rule with `global` global variable:\n\n**Incorrect code:**\n\n```js\n/*eslint no-eval: \"error\"*/\n/*global global*/\n\nglobal.eval(\"const a = 0\");\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-eval: \"error\"*/\n\nconst obj = { x: \"foo\" },\n key = \"x\",\n value = obj[key];\n\nclass A {\n foo() {\n // This is a user-defined method.\n this.eval(\"const a = 0\");\n }\n\n eval() {\n }\n\n static {\n // This is a user-defined static method.\n this.eval(\"const a = 0\");\n }\n\n static eval() {\n }\n}\n```\n\n\n## Options\n\n### allowIndirect\n\nThis rule has an option to allow [\"indirect eval\"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#direct_and_indirect_eval).\nIndirect calls to `eval` are less dangerous than direct calls to `eval` because they cannot dynamically change the scope. Because of this, they also will not negatively impact performance to the degree of direct `eval`.\n\n```js\n{\n \"no-eval\": [\"error\", {\"allowIndirect\": true}] // default is false\n}\n```\n\nExample of **incorrect** code for this rule with the `{\"allowIndirect\": true}` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-eval: [\"error\", {\"allowIndirect\": true} ]*/\n\nconst obj = { x: \"foo\" },\n key = \"x\",\n value = eval(\"obj.\" + key);\n```\n\n\nExamples of **correct** code for this rule with the `{\"allowIndirect\": true}` option:\n\n**Correct code:**\n\n```js\n/*eslint no-eval: [\"error\", {\"allowIndirect\": true} ]*/\n\n(0, eval)(\"const a = 0\");\n\nconst foo = eval;\nfoo(\"const a = 0\");\n\nthis.eval(\"const a = 0\");\n```\n\n\n**Correct code:**\n\n```js\n/*eslint no-eval: [\"error\", {\"allowIndirect\": true} ]*/\n/*global window*/\n\nwindow.eval(\"const a = 0\");\n```\n\n\n**Correct code:**\n\n```js\n/*eslint no-eval: [\"error\", {\"allowIndirect\": true} ]*/\n/*global global*/\n\nglobal.eval(\"const a = 0\");\n```\n\n\n## Known Limitations\n\n* This rule is warning every `eval()` even if the `eval` is not global's.\n This behavior is in order to detect calls of direct `eval`. Such as:\n\n ```js\n module.exports = function(eval) {\n // If the value of this `eval` is built-in `eval` function, this is a\n // call of direct `eval`.\n eval(\"const a = 0\");\n };\n ```\n\n* This rule cannot catch renaming the global object. Such as:\n\n ```js\n const foo = window;\n foo.eval(\"const a = 0\");\n ```",
|
|
1096
|
+
"eslint/no-implied-eval": "It's considered a good practice to avoid using `eval()` in JavaScript. There are security and performance implications involved with doing so, which is why many linters (including ESLint) recommend disallowing `eval()`. However, there are some other ways to pass a string and have it interpreted as JavaScript code that have similar concerns.\n\nThe first is using `setTimeout()`, `setInterval()` or `execScript()` (Internet Explorer only), all of which can accept a string of JavaScript code as their first argument. For example:\n\n```js\nsetTimeout(\"alert('Hi!');\", 100);\n```\n\nThis is considered an implied `eval()` because a string of JavaScript code is\n passed in to be interpreted. The same can be done with `setInterval()` and `execScript()`. Both interpret the JavaScript code in the global scope. For both `setTimeout()` and `setInterval()`, the first argument can also be a function, and that is considered safer and is more performant:\n\n```js\nsetTimeout(function() {\n alert(\"Hi!\");\n}, 100);\n```\n\nThe best practice is to always use a function for the first argument of `setTimeout()` and `setInterval()` (and avoid `execScript()`).\n\n## Rule Details\n\nThis rule aims to eliminate implied `eval()` through the use of `setTimeout()`, `setInterval()` or `execScript()`. As such, it will warn when either function is used with a string as the first argument.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-implied-eval: \"error\"*/\n/*global window, setTimeout, setInterval, execScript*/\n\nsetTimeout(\"alert('Hi!');\", 100);\n\nsetInterval(\"alert('Hi!');\", 100);\n\nexecScript(\"alert('Hi!')\");\n\nwindow.setTimeout(\"count = 5\", 10);\n\nwindow.setInterval(\"foo = bar\", 10);\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-implied-eval: \"error\"*/\n/*global setTimeout, setInterval*/\n\nsetTimeout(function() {\n alert(\"Hi!\");\n}, 100);\n\nsetInterval(function() {\n alert(\"Hi!\");\n}, 100);\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nIf you want to allow `setTimeout()` and `setInterval()` with string arguments, then you can safely disable this rule.",
|
|
1097
|
+
"eslint/no-new-func": "It's possible to create functions in JavaScript from strings at runtime using the `Function` constructor, such as:\n\n```js\nconst a = new Function(\"a\", \"b\", \"return a + b\");\nconst b = Function(\"a\", \"b\", \"return a + b\");\nconst c = Function.call(null, \"a\", \"b\", \"return a + b\");\nconst d = Function.apply(null, [\"a\", \"b\", \"return a + b\"]);\nconst x = Function.bind(null, \"a\", \"b\", \"return a + b\")();\n```\n\nThis is considered by many to be a bad practice due to the difficulty in debugging and reading these types of functions. In addition, Content-Security-Policy (CSP) directives may disallow the use of `eval()` and similar methods for creating code from strings.\n\n## Rule Details\n\nThis error is raised to highlight the use of a bad practice. By passing a string to the `Function` constructor, you are requiring the engine to parse that string much in the way it has to when you call the `eval` function.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-new-func: \"error\"*/\n\nconst a = new Function(\"a\", \"b\", \"return a + b\");\nconst b = Function(\"a\", \"b\", \"return a + b\");\nconst c = Function.call(null, \"a\", \"b\", \"return a + b\");\nconst d = Function.apply(null, [\"a\", \"b\", \"return a + b\"]);\nconst x = Function.bind(null, \"a\", \"b\", \"return a + b\")();\nconst y = Function.bind(null, \"a\", \"b\", \"return a + b\"); // assuming that the result of Function.bind(...) will be eventually called.\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-new-func: \"error\"*/\n\nconst x = function (a, b) {\n return a + b;\n};\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nIn more advanced cases where you really need to use the `Function` constructor.",
|
|
1098
|
+
"eslint/no-throw-literal": "It is considered good practice to only `throw` the `Error` object itself or an object using the `Error` object as base objects for user-defined exceptions.\nThe fundamental benefit of `Error` objects is that they automatically keep track of where they were built and originated.\n\nThis rule restricts what can be thrown as an exception. When it was first created, it only prevented literals from being thrown (hence the name), but it has now been expanded to only allow expressions which have a possibility of being an `Error` object.\n\n## Rule Details\n\nThis rule is aimed at maintaining consistency when throwing exception by disallowing to throw literals and other expressions which cannot possibly be an `Error` object.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-throw-literal: \"error\"*/\n\nthrow \"error\";\n\nthrow 0;\n\nthrow undefined;\n\nthrow null;\n\nconst err = new Error();\nthrow \"an \" + err;\n// err is recast to a string literal\n\nconst er2 = new Error();\nthrow `${err2}`\n\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-throw-literal: \"error\"*/\n\nthrow new Error();\n\nthrow new Error(\"error\");\n\nconst e = new Error(\"error\");\nthrow e;\n\ntry {\n throw new Error(\"error\");\n} catch (e) {\n throw e;\n}\n```\n\n\n## Options\n\nThis rule has no options.\n\n## Known Limitations\n\nDue to the limits of static analysis, this rule cannot guarantee that you will only throw `Error` objects.\n\nExamples of **correct** code for this rule, but which do not throw an `Error` object:\n\n**Correct code:**\n\n```js\n/*eslint no-throw-literal: \"error\"*/\n\nconst err = \"error\";\nthrow err;\n\nfunction foo(bar) {\n console.log(bar);\n}\nthrow foo(\"error\");\n\nthrow new String(\"error\");\n\nconst baz = {\n bar: \"error\"\n};\nthrow baz.bar;\n```",
|
|
1099
|
+
"eslint/no-unused-expressions": "An unused expression which has no effect on the state of the program indicates a logic error.\n\nFor example, `n + 1;` is not a syntax error, but it might be a typing mistake where a programmer meant an assignment statement `n += 1;` instead. Sometimes, such unused expressions may be eliminated by some build tools in production environment, which possibly breaks application logic.\n\n## Rule Details\n\nThis rule aims to eliminate unused expressions which have no effect on the state of the program.\n\nThis rule does not apply to function calls or constructor calls with the `new` operator, because they could have *side effects* on the state of the program.\n\n```js\nlet i = 0;\nfunction increment() { i += 1; }\nincrement(); // return value is unused, but i changed as a side effect\n\nlet nThings = 0;\nfunction Thing() { nThings += 1; }\nnew Thing(); // constructed object is unused, but nThings changed as a side effect\n```\n\nThis rule does not apply to directives (which are in the form of literal string expressions such as `\"use strict\";` at the beginning of a script, module, or function) when using ES5+ environments. In ES3 environments, directives are treated as unused expressions by default, but this behavior can be changed using the `ignoreDirectives` option.\n\nSequence expressions (those using a comma, such as `a = 1, b = 2`) are always considered unused unless their return value is assigned or used in a condition evaluation, or a function call is made with the sequence expression value.\n\n## Options\n\nThis rule, in its default state, does not require any arguments. If you would like to enable one or more of the following you may pass an object with the options set as follows:\n\n* `allowShortCircuit` set to `true` will allow you to use short circuit evaluations in your expressions (Default: `false`).\n* `allowTernary` set to `true` will enable you to use ternary operators in your expressions similarly to short circuit evaluations (Default: `false`).\n* `allowTaggedTemplates` set to `true` will enable you to use tagged template literals in your expressions (Default: `false`).\n* `enforceForJSX` set to `true` will flag unused JSX element expressions (Default: `false`).\n* `ignoreDirectives` set to `true` will prevent directives from being reported as unused expressions when linting with `ecmaVersion: 3` (Default: `false`).\n\nThese options allow unused expressions *only if all* of the code paths either directly change the state (for example, assignment statement) or could have *side effects* (for example, function call).\n\nExamples of **incorrect** code for the default `{ \"allowShortCircuit\": false, \"allowTernary\": false }` options:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unused-expressions: \"error\"*/\n\n0\n\nif(0) 0\n\n{0}\n\nf(0), {}\n\na && b()\n\na, b()\n\nc = a, b;\n\na() && function namedFunctionInExpressionContext () {f();}\n\n(function anIncompleteIIFE () {});\n\ninjectGlobal`body{ color: red; }`\n\n```\n\n\nExamples of **correct** code for the default `{ \"allowShortCircuit\": false, \"allowTernary\": false }` options:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-expressions: \"error\"*/\n\n{} // In this context, this is a block statement, not an object literal\n\n{ myLabel: foo() } // In this context, this is a block statement with a label and expression, not an object literal\n\nfunction namedFunctionDeclaration () {}\n\n(function aGenuineIIFE () {}());\n\nf()\n\na = 0\n\nnew C\n\ndelete a.b\n\nvoid a\n```\n\n\nNote that one or more string expression statements (with or without semi-colons) will only be considered as unused if they are not in the beginning of a script, module, or function (alone and uninterrupted by other statements). Otherwise, they will be treated as part of a \"directive prologue\", a section potentially usable by JavaScript engines. This includes \"strict mode\" directives.\n\nExamples of **correct** code for this rule in regard to directives:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-expressions: \"error\"*/\n\n\"use strict\";\n\"use asm\"\n\"use stricter\";\n\"use babel\"\n\"any other strings like this in the directive prologue\";\n\"this is still the directive prologue\";\n\nfunction foo() {\n \"bar\";\n}\n\nclass Foo {\n someMethod() {\n \"use strict\";\n }\n}\n```\n\n\nExamples of **incorrect** code for this rule in regard to directives:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unused-expressions: \"error\"*/\n\ndoSomething();\n\"use strict\"; // this isn't in a directive prologue, because there is a non-directive statement before it\n\nfunction foo() {\n \"bar\" + 1;\n}\n\nclass Foo {\n static {\n \"use strict\"; // class static blocks do not have directive prologues\n }\n}\n```\n\n\n### allowShortCircuit\n\nExamples of **incorrect** code for the `{ \"allowShortCircuit\": true }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unused-expressions: [\"error\", { \"allowShortCircuit\": true }]*/\n\na || b\n```\n\n\nExamples of **correct** code for the `{ \"allowShortCircuit\": true }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-expressions: [\"error\", { \"allowShortCircuit\": true }]*/\n\na && b()\na() || (b = c)\n```\n\n\n### allowTernary\n\nExamples of **incorrect** code for the `{ \"allowTernary\": true }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unused-expressions: [\"error\", { \"allowTernary\": true }]*/\n\na ? b : 0\na ? b : c()\n```\n\n\nExamples of **correct** code for the `{ \"allowTernary\": true }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-expressions: [\"error\", { \"allowTernary\": true }]*/\n\na ? b() : c()\na ? (b = c) : d()\n```\n\n\n### allowShortCircuit and allowTernary\n\nExamples of **correct** code for the `{ \"allowShortCircuit\": true, \"allowTernary\": true }` options:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-expressions: [\"error\", { \"allowShortCircuit\": true, \"allowTernary\": true }]*/\n\na ? b() || (c = d) : e()\n```\n\n\n### allowTaggedTemplates\n\nExamples of **incorrect** code for the `{ \"allowTaggedTemplates\": true }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unused-expressions: [\"error\", { \"allowTaggedTemplates\": true }]*/\n\n`some untagged template string`;\n```\n\n\nExamples of **correct** code for the `{ \"allowTaggedTemplates\": true }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-expressions: [\"error\", { \"allowTaggedTemplates\": true }]*/\n\ntag`some tagged template string`;\n```\n\n\n### enforceForJSX\n\nJSX is most-commonly used in the React ecosystem, where it is compiled to `React.createElement` expressions. Though free from side-effects, these calls are not automatically flagged by the `no-unused-expressions` rule. If you're using React, or any other side-effect-free JSX pragma, this option can be enabled to flag these expressions.\n\nExamples of **incorrect** code for the `{ \"enforceForJSX\": true }` option:\n\n**Incorrect code:**\n\n```jsx\n/*eslint no-unused-expressions: [\"error\", { \"enforceForJSX\": true }]*/\n\n<MyComponent />;\n\n<></>;\n```\n\n\nExamples of **correct** code for the `{ \"enforceForJSX\": true }` option:\n\n**Correct code:**\n\n```jsx\n/*eslint no-unused-expressions: [\"error\", { \"enforceForJSX\": true }]*/\n\nconst myComponentPartial = <MyComponent />;\n\nconst myFragment = <></>;\n```\n\n\n### ignoreDirectives\n\nWhen set to `false` (default), this rule reports directives (like `\"use strict\"`) as unused expressions when linting with `ecmaVersion: 3`. This default behavior exists because ES3 environments do not formally support directives, meaning such strings are effectively unused expressions in that specific context.\n\nSet this option to `true` to prevent directives from being reported as unused, even when `ecmaVersion: 3` is specified. This option is primarily useful for projects that need to maintain a single codebase containing directives while supporting both older ES3 environments and modern (ES5+) environments.\n\n**Note:** In ES5+ environments, directives are always ignored regardless of this setting.\n\nExamples of **incorrect** code for the `{ \"ignoreDirectives\": false }` option and `ecmaVersion: 3`:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unused-expressions: [\"error\", { \"ignoreDirectives\": false }]*/\n\n\"use strict\";\n\"use asm\"\n\"use stricter\";\n\"use babel\"\n\"any other strings like this in the directive prologue\";\n\"this is still the directive prologue\";\n\nfunction foo() {\n \"bar\";\n}\n```\n\n\nExamples of **correct** code for the `{ \"ignoreDirectives\": true }` option and `ecmaVersion: 3`:\n\n**Correct code:**\n\n```js\n/*eslint no-unused-expressions: [\"error\", { \"ignoreDirectives\": true }]*/\n\n\"use strict\";\n\"use asm\"\n\"use stricter\";\n\"use babel\"\n\"any other strings like this in the directive prologue\";\n\"this is still the directive prologue\";\n\nfunction foo() {\n \"bar\";\n}\n```\n\n\n### TypeScript Support\n\nThis rule supports TypeScript-specific expressions and follows these guidelines:\n\n1. Directives (like `'use strict'`) are allowed in module and namespace declarations\n2. Type-related expressions are treated as unused if their wrapped value expressions are unused:\n * Type assertions (`x as number`, `<number>x`)\n * Non-null assertions (`x!`)\n * Type instantiations (`Set<number>`)\n\n**Note**: Although type expressions never have runtime side effects (e.g., `x!` is equivalent to `x` at runtime), they can be used to assert types for testing purposes.\n\nExamples of **correct** code for this rule when using TypeScript:\n\n**Correct code:**\n\n```ts\n/* eslint no-unused-expressions: \"error\" */\n\n// Type expressions wrapping function calls are allowed\nfunction getSet() {\n return Set;\n}\ngetSet()<number>;\ngetSet() as Set<unknown>;\ngetSet()!;\n\n// Directives in modules and namespaces\nmodule Foo {\n 'use strict';\n 'hello world';\n}\n\nnamespace Bar {\n 'use strict';\n export class Baz {}\n}\n```\n\n\nExamples of **incorrect** code for this rule when using TypeScript:\n\n**Incorrect code:**\n\n```ts\n/* eslint no-unused-expressions: \"error\" */\n\n// Standalone type expressions\nSet<number>;\n1 as number;\nwindow!;\n\n// Expressions inside namespaces\nnamespace Bar {\n 123;\n}\n```",
|
|
1100
|
+
"eslint/consistent-return": "Unlike statically-typed languages which enforce that a function returns a specified type of value, JavaScript allows different code paths in a function to return different types of values.\n\nA confusing aspect of JavaScript is that a function returns `undefined` if any of the following are true:\n\n* It does not execute a `return` statement before it exits.\n* It executes `return` which does not specify a value explicitly.\n* It executes `return undefined`.\n* It executes `return void` followed by an expression (for example, a function call).\n* It executes `return` followed by any other expression which evaluates to `undefined`.\n\nIf any code paths in a function return a value explicitly but some code path do not return a value explicitly, it might be a typing mistake, especially in a large function. In the following example:\n\n* A code path through the function returns a Boolean value `true`.\n* Another code path does not return a value explicitly, therefore returns `undefined` implicitly.\n\n```js\nfunction doSomething(condition) {\n if (condition) {\n return true;\n } else {\n return;\n }\n}\n```\n\n## Rule Details\n\nThis rule requires `return` statements to either always or never specify values. This rule ignores function definitions where the name begins with an uppercase letter, because constructors (when invoked with the `new` operator) return the instantiated object implicitly if they do not return another object explicitly.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint consistent-return: \"error\"*/\n\nfunction doSomething(condition) {\n if (condition) {\n return true;\n } else {\n return;\n }\n}\n\nfunction doSomethingElse(condition) {\n if (condition) {\n return true;\n }\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint consistent-return: \"error\"*/\n\nfunction doSomething(condition) {\n if (condition) {\n return true;\n } else {\n return false;\n }\n}\n\nfunction Foo() {\n if (!(this instanceof Foo)) {\n return new Foo();\n }\n\n this.a = 0;\n}\n```\n\n\n## Options\n\nThis rule has an object option:\n\n* `\"treatUndefinedAsUnspecified\": false` (default) always either specify values or return `undefined` implicitly only.\n* `\"treatUndefinedAsUnspecified\": true` always either specify values or return `undefined` explicitly or implicitly.\n\n### treatUndefinedAsUnspecified\n\nExamples of **incorrect** code for this rule with the default `{ \"treatUndefinedAsUnspecified\": false }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint consistent-return: [\"error\", { \"treatUndefinedAsUnspecified\": false }]*/\n\nfunction foo(callback) {\n if (callback) {\n return void callback();\n }\n // no return statement\n}\n\nfunction bar(condition) {\n if (condition) {\n return undefined;\n }\n // no return statement\n}\n```\n\n\nExamples of **incorrect** code for this rule with the `{ \"treatUndefinedAsUnspecified\": true }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint consistent-return: [\"error\", { \"treatUndefinedAsUnspecified\": true }]*/\n\nfunction foo(callback) {\n if (callback) {\n return void callback();\n }\n return true;\n}\n\nfunction bar(condition) {\n if (condition) {\n return undefined;\n }\n return true;\n}\n```\n\n\nExamples of **correct** code for this rule with the `{ \"treatUndefinedAsUnspecified\": true }` option:\n\n**Correct code:**\n\n```js\n/*eslint consistent-return: [\"error\", { \"treatUndefinedAsUnspecified\": true }]*/\n\nfunction foo(callback) {\n if (callback) {\n return void callback();\n }\n // no return statement\n}\n\nfunction bar(condition) {\n if (condition) {\n return undefined;\n }\n // no return statement\n}\n```\n\n\n## When Not To Use It\n\nIf you want to allow functions to have different `return` behavior depending on code branching, then it is safe to disable this rule.",
|
|
1101
|
+
"eslint/default-case-last": "A `switch` statement can optionally have a `default` clause.\n\nIf present, it's usually the last clause, but it doesn't need to be. It is also allowed to put the `default` clause before all `case` clauses, or anywhere between. The behavior is mostly the same as if it was the last clause. The `default` block will be still executed only if there is no match in the `case` clauses (including those defined after the `default`), but there is also the ability to \"fall through\" from the `default` clause to the following clause in the list. However, such flow is not common and it would be confusing to the readers.\n\nEven if there is no \"fall through\" logic, it's still unexpected to see the `default` clause before or between the `case` clauses. By convention, it is expected to be the last clause.\n\nIf a `switch` statement should have a `default` clause, it's considered a best practice to define it as the last clause.\n\n## Rule Details\n\nThis rule enforces `default` clauses in `switch` statements to be last.\n\nIt applies only to `switch` statements that already have a `default` clause.\n\nThis rule does not enforce the existence of `default` clauses. See [default-case](default-case) if you also want to enforce the existence of `default` clauses in `switch` statements.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint default-case-last: \"error\"*/\n\nswitch (foo) {\n default:\n bar();\n break;\n case \"a\":\n baz();\n break;\n}\n\nswitch (foo) {\n case 1:\n bar();\n break;\n default:\n baz();\n break;\n case 2:\n quux();\n break;\n}\n\nswitch (foo) {\n case \"x\":\n bar();\n break;\n default:\n case \"y\":\n baz();\n break;\n}\n\nswitch (foo) {\n default:\n break;\n case -1:\n bar();\n break;\n}\n\nswitch (foo) {\n default:\n doSomethingIfNotZero();\n case 0:\n doSomethingAnyway();\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint default-case-last: \"error\"*/\n\nswitch (foo) {\n case \"a\":\n baz();\n break;\n default:\n bar();\n break;\n}\n\nswitch (foo) {\n case 1:\n bar();\n break;\n case 2:\n quux();\n break;\n default:\n baz();\n break;\n}\n\nswitch (foo) {\n case \"x\":\n bar();\n break;\n case \"y\":\n default:\n baz();\n break;\n}\n\nswitch (foo) {\n case -1:\n bar();\n break;\n}\n\nif (foo !== 0) {\n doSomethingIfNotZero();\n}\ndoSomethingAnyway();\n```\n\n\n## Options\n\nThis rule has no options.",
|
|
1102
|
+
"eslint/no-shadow": "Shadowing is the process by which a local variable shares the same name as a variable in its containing scope. For example:\n\n```js\nconst a = 3;\nfunction b() {\n const a = 10;\n}\n```\n\nIn this case, the variable `a` inside of `b()` is shadowing the variable `a` in the global scope. This can cause confusion while reading the code and it's impossible to access the global variable.\n\n## Rule Details\n\nThis rule aims to eliminate shadowed variable declarations.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-shadow: \"error\"*/\n\nconst a = 3;\nfunction b() {\n const a = 10;\n}\n\nconst c = function () {\n const a = 10;\n}\n\nfunction d(a) {\n a = 10;\n}\nd(a);\n\nif (true) {\n const a = 5;\n}\n\nconst f = wrap(function f() {});\n\nconst C = wrap(class C {});\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-shadow: \"error\"*/\n\nconst a = 3;\nfunction b(c) {\n const d = 10;\n if (c) {\n const e = 20;\n }\n}\n\n/*\n * Function and class names are allowed to shadow a variable\n * if the function/class expression is assigned to the variable\n * as its initializer or default value.\n */\nconst f = function f() {};\nconst g = foo ? (bar || function g() {}) : baz;\nconst { h = function h() {} } = obj;\nfunction qux(i = function i() {}) {}\nconst C = class C {};\n```\n\n\n## Options\n\nThis rule takes one option, an object, with the following properties:\n- `\"builtinGlobals\"`\n- `\"hoist\"`\n- `\"allow\"`\n- `\"ignoreOnInitialization\"`\n- `\"ignoreTypeValueShadow\"` (TypeScript only)\n- `\"ignoreFunctionTypeParameterNameValueShadow\"` (TypeScript only)\n\n```json\n{\n \"no-shadow\": [\"error\", { \"builtinGlobals\": false, \"hoist\": \"functions\", \"allow\": [], \"ignoreOnInitialization\": false }]\n}\n```\n\n### builtinGlobals\n\nThe `builtinGlobals` option is `false` by default.\nIf it is `true`, the rule prevents shadowing of built-in global variables: `Object`, `Array`, `Number`, and so on.\n\nExamples of **incorrect** code for the `{ \"builtinGlobals\": true }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-shadow: [\"error\", { \"builtinGlobals\": true }]*/\n\nfunction foo() {\n const Object = 0;\n}\n```\n\n\n### hoist\n\nThe `hoist` option has five settings:\n\n- `functions` (by default) - reports shadowing before the outer functions are defined.\n- `all` - reports all shadowing before the outer variables/functions are defined.\n- `never` - never report shadowing before the outer variables/functions are defined.\n- `types` (TypeScript only) - reports shadowing before the outer types are defined.\n- `functions-and-types` (TypeScript only) - reports shadowing before the outer functions and types are defined.\n\n#### hoist: functions\n\nExamples of **incorrect** code for the default `{ \"hoist\": \"functions\" }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-shadow: [\"error\", { \"hoist\": \"functions\" }]*/\n\nif (true) {\n const b = 6;\n}\n\nfunction b() {}\n```\n\n\nAlthough `const b` in the `if` statement is before the *function* declaration in the outer scope, it is incorrect.\n\nExamples of **correct** code for the default `{ \"hoist\": \"functions\" }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-shadow: [\"error\", { \"hoist\": \"functions\" }]*/\n\nif (true) {\n const a = 3;\n}\n\nconst a = 5;\n```\n\n\nBecause `const a` in the `if` statement is before the *variable* declaration in the outer scope, it is correct.\n\n#### hoist: all\n\nExamples of **incorrect** code for the `{ \"hoist\": \"all\" }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-shadow: [\"error\", { \"hoist\": \"all\" }]*/\n\nif (true) {\n const a = 3;\n const b = 6;\n}\n\nconst a = 5;\nfunction b() {}\n```\n\n\n#### hoist: never\n\nExamples of **correct** code for the `{ \"hoist\": \"never\" }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-shadow: [\"error\", { \"hoist\": \"never\" }]*/\n\nif (true) {\n const a = 3;\n const b = 6;\n}\n\nconst a = 5;\nfunction b() {}\n```\n\n\nBecause `const a` and `const b` in the `if` statement are before the declarations in the outer scope, they are correct.\n\n#### hoist: types\n\nExamples of **incorrect** code for the `{ \"hoist\": \"types\" }` option:\n\n**Incorrect code:**\n\n```ts\n/*eslint no-shadow: [\"error\", { \"hoist\": \"types\" }]*/\n\ntype Bar<Foo> = 1;\ntype Foo = 1;\n```\n\n\n#### hoist: functions-and-types\n\nExamples of **incorrect** code for the `{ \"hoist\": \"functions-and-types\" }` option:\n\n**Incorrect code:**\n\n```ts\n/*eslint no-shadow: [\"error\", { \"hoist\": \"functions-and-types\" }]*/\n\n// types\ntype Bar<Foo> = 1;\ntype Foo = 1;\n\n// functions\nif (true) {\n const b = 6;\n}\n\nfunction b() {}\n```\n\n\n### allow\n\nThe `allow` option is an array of identifier names for which shadowing is allowed. For example, `\"resolve\"`, `\"reject\"`, `\"done\"`, `\"cb\"`.\n\nExamples of **correct** code for the `{ \"allow\": [\"done\"] }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-shadow: [\"error\", { \"allow\": [\"done\"] }]*/\n\nimport async from 'async';\n\nfunction foo(done) {\n async.map([1, 2], function (e, done) {\n done(null, e * 2)\n }, done);\n}\n\nfoo(function (err, result) {\n console.log({ err, result });\n});\n```\n\n\n### ignoreOnInitialization\n\nThe `ignoreOnInitialization` option is `false` by default. If it is `true`, it prevents reporting shadowing of variables in their initializers when the shadowed variable is presumably still uninitialized.\n\nThe shadowed variable must be on the left side. The shadowing variable must be on the right side and declared in a callback function or in an IIFE.\n\nExamples of **incorrect** code for the `{ \"ignoreOnInitialization\": \"true\" }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-shadow: [\"error\", { \"ignoreOnInitialization\": true }]*/\n\nconst x = x => x;\n```\n\n\nBecause the shadowing variable `x` will shadow the already initialized shadowed variable `x`.\n\nExamples of **correct** code for the `{ \"ignoreOnInitialization\": true }` option:\n\n**Correct code:**\n\n```js\n/*eslint no-shadow: [\"error\", { \"ignoreOnInitialization\": true }]*/\n\nconst x = foo(x => x)\n\nconst y = (y => y)()\n```\n\n\nThe rationale for callback functions is the assumption that they will be called during the initialization, so that at the time when the shadowing variable will be used, the shadowed variable has not yet been initialized.\n\n### ignoreTypeValueShadow\n\nWhether to ignore types named the same as a variable. Default: `true`.\n\nThis is generally safe because you cannot use variables in type locations without a typeof operator, so there's little risk of confusion.\n\nExamples of **correct** code with `{ \"ignoreTypeValueShadow\": true }`:\n\n**Correct code:**\n\n```ts\n/*eslint no-shadow: [\"error\", { \"ignoreTypeValueShadow\": true }]*/\n\ntype Foo = number;\ninterface Bar {\n prop: number;\n}\n\nfunction f() {\n const Foo = 1;\n const Bar = 'test';\n}\n```\n\n\n**Note:** Shadowing specifically refers to two identical identifiers that are in different, nested scopes. This is different from redeclaration, which is when two identical identifiers are in the same scope. Redeclaration is covered by the [`no-redeclare`](/rules/no-redeclare) rule instead.\n\n\n### ignoreFunctionTypeParameterNameValueShadow\n\nWhether to ignore function parameters named the same as a variable. Default: `true`.\n\nEach of a function type's arguments creates a value variable within the scope of the function type. This is done so that you can reference the type later using the typeof operator:\n\n```ts\ntype Func = (test: string) => typeof test;\n\ndeclare const fn: Func;\nconst result = fn('str'); // typeof result === string\n```\n\nThis means that function type arguments shadow value variable names in parent scopes:\n\n```ts\nlet test = 1;\ntype TestType = typeof test; // === number\ntype Func = (test: string) => typeof test; // this \"test\" references the argument, not the variable\n\ndeclare const fn: Func;\nconst result = fn('str'); // typeof result === string\n```\n\nIf you do not use the `typeof` operator in a function type return type position, you can safely turn this option on.\n\nExamples of **correct** code with `{ \"ignoreFunctionTypeParameterNameValueShadow\": true }`:\n\n**Correct code:**\n\n```ts\n/*eslint no-shadow: [\"error\", { \"ignoreFunctionTypeParameterNameValueShadow\": true }]*/\n\nconst test = 1;\ntype Func = (test: string) => typeof test;\n```\n\n\n### Why does the rule report on enum members that share the same name as a variable in a parent scope?\n\nThis isn't a bug \u2014 the rule is working exactly as intended! The report is correct because of a lesser-known aspect of enums: enum members introduce a variable within the enum's own scope, allowing them to be referenced without needing a qualifier.\n\nHere's a simple example to explain:\n\n```ts\nconst A = 2;\nenum Test {\n A = 1,\n B = A,\n}\n\nconsole.log(Test.B); // what should be logged?\n```\n\nAt first glance, you might think it should log `2`, because the outer variable A's value is `2`. However, it actually logs `1`, the value of `Test.A`. This happens because inside the enum `B = A` is treated as `B = Test.A`. Due to this behavior, the enum member has shadowed the outer variable declaration.",
|
|
1103
|
+
"eslint/no-return-assign": "One of the interesting, and sometimes confusing, aspects of JavaScript is that assignment can happen at almost any point. Because of this, an errant equals sign can end up causing assignment when the true intent was to do a comparison. This is especially true when using a `return` statement. For example:\n\n```js\nfunction doSomething() {\n return foo = bar + 2;\n}\n```\n\nIt is difficult to tell the intent of the `return` statement here. It's possible that the function is meant to return the result of `bar + 2`, but then why is it assigning to `foo`? It's also possible that the intent was to use a comparison operator such as `==` and that this code is an error.\n\nBecause of this ambiguity, it's considered a best practice to not use assignment in `return` statements.\n\n## Rule Details\n\nThis rule aims to eliminate assignments from `return` statements. As such, it will warn whenever an assignment is found as part of `return`.\n\n## Options\n\nThe rule takes one option, a string, which must contain one of the following values:\n\n* `except-parens` (default): Disallow assignments unless they are enclosed in parentheses.\n* `always`: Disallow all assignments.\n\n### except-parens\n\nThis is the default option.\nIt disallows assignments unless they are enclosed in parentheses.\n\nExamples of **incorrect** code for the default `\"except-parens\"` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-return-assign: \"error\"*/\n\nfunction doSomething() {\n return foo = bar + 2;\n}\n\nfunction doSomethingElse() {\n return foo += 2;\n}\n\nconst foo = (a, b) => a = b\n\nconst bar = (a, b, c) => (a = b, c == b)\n\nfunction doSomethingMore() {\n return foo = bar && foo > 0;\n}\n```\n\n\nExamples of **correct** code for the default `\"except-parens\"` option:\n\n**Correct code:**\n\n```js\n/*eslint no-return-assign: \"error\"*/\n\nfunction doSomething() {\n return foo == bar + 2;\n}\n\nfunction doSomethingElse() {\n return foo === bar + 2;\n}\n\nfunction doSomethingMore() {\n return (foo = bar + 2);\n}\n\nconst foo = (a, b) => (a = b)\n\nconst bar = (a, b, c) => ((a = b), c == b)\n\nfunction doAnotherThing() {\n return (foo = bar) && foo > 0;\n}\n```\n\n\n### always\n\nThis option disallows all assignments in `return` statements.\nAll assignments are treated as problems.\n\nExamples of **incorrect** code for the `\"always\"` option:\n\n**Incorrect code:**\n\n```js\n/*eslint no-return-assign: [\"error\", \"always\"]*/\n\nfunction doSomething() {\n return foo = bar + 2;\n}\n\nfunction doSomethingElse() {\n return foo += 2;\n}\n\nfunction doSomethingMore() {\n return (foo = bar + 2);\n}\n```\n\n\nExamples of **correct** code for the `\"always\"` option:\n\n**Correct code:**\n\n```js\n/*eslint no-return-assign: [\"error\", \"always\"]*/\n\nfunction doSomething() {\n return foo == bar + 2;\n}\n\nfunction doSomethingElse() {\n return foo === bar + 2;\n}\n```\n\n\n## When Not To Use It\n\nIf you want to allow the use of assignment operators in a `return` statement, then you can safely disable this rule.",
|
|
1104
|
+
"eslint/no-self-compare": "Comparing a variable against itself is usually an error, either a typo or refactoring error. It is confusing to the reader and may potentially introduce a runtime error.\n\nThe only time you would compare a variable against itself is when you are testing for `NaN`. However, it is far more appropriate to use `typeof x === 'number' && isNaN(x)` or the [Number.isNaN ES2015 function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN) for that use case rather than leaving the reader of the code to determine the intent of self comparison.\n\n## Rule Details\n\nThis error is raised to highlight a potentially confusing and potentially pointless piece of code. There are almost no situations in which you would need to compare something to itself.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-self-compare: \"error\"*/\n\nlet x = 10;\nif (x === x) {\n x = 20;\n}\n```\n\n\n## Options\n\nThis rule has no options.\n\n## Known Limitations\n\nThis rule works by directly comparing the tokens on both sides of the operator. It flags them as problematic if they are structurally identical. However, it doesn't consider possible side effects or that functions may return different objects even when called with the same arguments. As a result, it can produce false positives in some cases, such as:\n\n**Incorrect code:**\n\n```js\n/*eslint no-self-compare: \"error\"*/\n\nfunction parseDate(dateStr) {\n return new Date(dateStr);\n}\n\nif (parseDate('December 17, 1995 03:24:00') === parseDate('December 17, 1995 03:24:00')) {\n // do something\n}\n\nlet counter = 0;\nfunction incrementUnlessReachedMaximum() {\n return Math.min(counter += 1, 10);\n}\n\nif (incrementUnlessReachedMaximum() === incrementUnlessReachedMaximum()) {\n // ...\n}\n```",
|
|
1105
|
+
"eslint/no-unmodified-loop-condition": "Variables in a loop condition often are modified in the loop.\nIf not, it's possibly a mistake.\n\n```js\nwhile (node) {\n doSomething(node);\n}\n```\n\n```js\nwhile (node) {\n doSomething(node);\n node = node.parent;\n}\n```\n\n## Rule Details\n\nThis rule finds references which are inside of loop conditions, then checks the\nvariables of those references are modified in the loop.\n\nBy default, if a reference is inside of a binary expression or a ternary expression, this rule checks\nthe result of the expression instead. The `checkConditionalExpressions` option stops the rule from\ngrouping references solely because they belong to the same ternary expression.\nIf a reference is inside of a dynamic expression (e.g. `CallExpression`,\n`YieldExpression`, ...), this rule ignores it.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unmodified-loop-condition: \"error\"*/\n\nlet node = something;\n\nwhile (node) {\n doSomething(node);\n}\nnode = other;\n\nfor (let j = 0; j < 5;) {\n doSomething(j);\n}\n\nwhile (node !== root) {\n doSomething(node);\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-unmodified-loop-condition: \"error\"*/\n\nwhile (node) {\n doSomething(node);\n node = node.parent;\n}\n\nfor (let j = 0; j < items.length; ++j) {\n doSomething(items[j]);\n}\n\n// OK, the result of this binary expression is changed in this loop.\nwhile (node !== root) {\n doSomething(node);\n node = node.parent;\n}\n\n// OK, the result of this ternary expression is changed in this loop.\nwhile (node ? A : B) {\n doSomething(node);\n node = node.parent;\n}\n\n// A property might be a getter which has side effect...\n// Or \"doSomething\" can modify \"obj.foo\".\nwhile (obj.foo) {\n doSomething(obj);\n}\n\n// A function call can return various values.\nwhile (check(obj)) {\n doSomething(obj);\n}\n```\n\n\n## Options\n\nThis rule has an object option:\n\n* `\"checkConditionalExpressions\": false` (default) checks the result of an entire ternary expression\n* `\"checkConditionalExpressions\": true` each branch in a ternary expression is checked independently\n\nExamples of **incorrect** code for this rule with the `{ \"checkConditionalExpressions\": true }` option:\n\n**Incorrect code:**\n\n```js\n/* eslint no-unmodified-loop-condition: [\"error\", { \"checkConditionalExpressions\": true }] */\n\nlet chunk = getInitialChunk();\nlet done = false;\n\nwhile (chunk ? !done : false) {\n chunk = nextOrNull();\n}\n```\n\n\n## When Not To Use It\n\nIf you don't want to notified about references inside of loop conditions, then it's safe to disable this rule.",
|
|
1106
|
+
"eslint/no-unreachable-loop": "A loop that can never reach the second iteration is a possible error in the code.\n\n```js\nfor (let i = 0; i < arr.length; i++) {\n if (arr[i].name === myName) {\n doSomething(arr[i]);\n // break was supposed to be here\n }\n break;\n}\n```\n\nIn rare cases where only one iteration (or at most one iteration) is intended behavior, the code should be refactored to use `if` conditionals instead of `while`, `do-while` and `for` loops. It's considered a best practice to avoid using loop constructs for such cases.\n\n## Rule Details\n\nThis rule aims to detect and disallow loops that can have at most one iteration, by performing static code path analysis on loop bodies.\n\nIn particular, this rule will disallow a loop with a body that exits the loop in all code paths. If all code paths in the loop's body will end with either a `break`, `return` or a `throw` statement, the second iteration of such loop is certainly unreachable, regardless of the loop's condition.\n\nThis rule checks `while`, `do-while`, `for`, `for-in` and `for-of` loops. You can optionally disable checks for each of these constructs.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-unreachable-loop: \"error\"*/\n\nwhile (foo) {\n doSomething(foo);\n foo = foo.parent;\n break;\n}\n\nfunction verifyList(head) {\n let item = head;\n do {\n if (verify(item)) {\n return true;\n } else {\n return false;\n }\n } while (item);\n}\n\nfunction findSomething(arr) {\n for (let i = 0; i < arr.length; i++) {\n if (isSomething(arr[i])) {\n return arr[i];\n } else {\n throw new Error(\"Doesn't exist.\");\n }\n }\n}\n\nfor (key in obj) {\n if (key.startsWith(\"_\")) {\n break;\n }\n firstKey = key;\n firstValue = obj[key];\n break;\n}\n\nfor (foo of bar) {\n if (foo.id === id) {\n doSomething(foo);\n }\n break;\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-unreachable-loop: \"error\"*/\n\nwhile (foo) {\n doSomething(foo);\n foo = foo.parent;\n}\n\nfunction verifyList(head) {\n let item = head;\n do {\n if (verify(item)) {\n item = item.next;\n } else {\n return false;\n }\n } while (item);\n\n return true;\n}\n\nfunction findSomething(arr) {\n for (let i = 0; i < arr.length; i++) {\n if (isSomething(arr[i])) {\n return arr[i];\n }\n }\n throw new Error(\"Doesn't exist.\");\n}\n\nfor (key in obj) {\n if (key.startsWith(\"_\")) {\n continue;\n }\n firstKey = key;\n firstValue = obj[key];\n break;\n}\n\nfor (foo of bar) {\n if (foo.id === id) {\n doSomething(foo);\n break;\n }\n}\n```\n\n\nPlease note that this rule is not designed to check loop conditions, and will not warn in cases such as the following examples.\n\nExamples of additional **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-unreachable-loop: \"error\"*/\n\ndo {\n doSomething();\n} while (false)\n\nfor (let i = 0; i < 1; i++) {\n doSomething(i);\n}\n\nfor (const a of [1]) {\n doSomething(a);\n}\n```\n\n\n## Options\n\nThis rule has an object option, with one option:\n\n* `\"ignore\"` - an optional array of loop types that will be ignored by this rule.\n\n### ignore\n\nYou can specify up to 5 different elements in the `\"ignore\"` array:\n\n* `\"WhileStatement\"` - to ignore all `while` loops.\n* `\"DoWhileStatement\"` - to ignore all `do-while` loops.\n* `\"ForStatement\"` - to ignore all `for` loops (does not apply to `for-in` and `for-of` loops).\n* `\"ForInStatement\"` - to ignore all `for-in` loops.\n* `\"ForOfStatement\"` - to ignore all `for-of` loops.\n\nExamples of **correct** code for this rule with the `\"ignore\"` option:\n\n**Correct code:**\n\n```js\n/*eslint no-unreachable-loop: [\"error\", { \"ignore\": [\"ForInStatement\", \"ForOfStatement\"] }]*/\n\nfor (let key in obj) {\n hasEnumerableProperties = true;\n break;\n}\n\nfor (const a of b) break;\n```\n\n\n## Known Limitations\n\nStatic code path analysis, in general, does not evaluate conditions. Due to this fact, this rule might miss reporting cases such as the following:\n\n```js\nfor (let i = 0; i < 10; i++) {\n doSomething(i);\n if (true) {\n break;\n }\n}\n```",
|
|
1107
|
+
"eslint/no-template-curly-in-string": "ECMAScript 6 allows programmers to create strings containing variable or expressions using template literals, instead of string concatenation, by writing expressions like `${variable}` between two backtick quotes (\\`). It can be easy to use the wrong quotes when wanting to use template literals, by writing `\"${variable}\"`, and end up with the literal value `\"${variable}\"` instead of a string containing the value of the injected expressions.\n\n## Rule Details\n\nThis rule aims to warn when a regular string contains what looks like a template literal placeholder. It will warn when it finds a string containing the template literal placeholder (`${something}`) that uses either `\"` or `'` for the quotes.\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/*eslint no-template-curly-in-string: \"error\"*/\n\"Hello ${name}!\";\n'Hello ${name}!';\n\"Time: ${12 * 60 * 60 * 1000}\";\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/*eslint no-template-curly-in-string: \"error\"*/\n`Hello ${name}!`;\n`Time: ${12 * 60 * 60 * 1000}`;\n\ntemplateFunction`Hello ${name}`;\n```\n\n\n## Options\n\nThis rule has no options.\n\n## When Not To Use It\n\nThis rule should not be used in ES3/5 environments.",
|
|
1108
|
+
"eslint/require-atomic-updates": "When writing asynchronous code, it is possible to create subtle race condition bugs. Consider the following example:\n\n```js\nlet totalLength = 0;\n\nasync function addLengthOfSinglePage(pageNum) {\n totalLength += await getPageLength(pageNum);\n}\n\nPromise.all([addLengthOfSinglePage(1), addLengthOfSinglePage(2)]).then(() => {\n console.log('The combined length of both pages is', totalLength);\n});\n```\n\nThis code looks like it will sum the results of calling `getPageLength(1)` and `getPageLength(2)`, but in reality the final value of `totalLength` will only be the length of one of the two pages. The bug is in the statement `totalLength += await getPageLength(pageNum);`. This statement first reads an initial value of `totalLength`, then calls `getPageLength(pageNum)` and waits for that Promise to fulfill. Finally, it sets the value of `totalLength` to the sum of `await getPageLength(pageNum)` and the *initial* value of `totalLength`. If the `totalLength` variable is updated in a separate function call during the time that the `getPageLength(pageNum)` Promise is pending, that update will be lost because the new value is overwritten without being read.\n\nOne way to fix this issue would be to ensure that `totalLength` is read at the same time as it's updated, like this:\n\n```js\nasync function addLengthOfSinglePage(pageNum) {\n const lengthOfThisPage = await getPageLength(pageNum);\n\n totalLength += lengthOfThisPage;\n}\n```\n\nAnother solution would be to avoid using a mutable variable reference at all:\n\n```js\nPromise.all([getPageLength(1), getPageLength(2)]).then(pageLengths => {\n const totalLength = pageLengths.reduce((accumulator, length) => accumulator + length, 0);\n\n console.log('The combined length of both pages is', totalLength);\n});\n```\n\n## Rule Details\n\nThis rule aims to report assignments to variables or properties in cases where the assignments may be based on outdated values.\n\n### Variables\n\nThis rule reports an assignment to a variable when it detects the following execution flow in a generator or async function:\n\n1. The variable is read.\n2. A `yield` or `await` pauses the function.\n3. After the function is resumed, a value is assigned to the variable from step 1.\n\nThe assignment in step 3 is reported because it may be incorrectly resolved because the value of the variable from step 1 may have changed between steps 2 and 3. In particular, if the variable can be accessed from other execution contexts (for example, if it is not a local variable and therefore other functions can change it), the value of the variable may have changed elsewhere while the function was paused in step 2.\n\nNote that the rule does not report the assignment in step 3 in any of the following cases:\n\n* If the variable is read again between steps 2 and 3.\n* If the variable cannot be accessed while the function is paused (for example, if it's a local variable).\n\nExamples of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/* eslint require-atomic-updates: error */\n\nlet result;\n\nasync function foo() {\n result += await something;\n}\n\nasync function bar() {\n result = result + await something;\n}\n\nasync function baz() {\n result = result + doSomething(await somethingElse);\n}\n\nasync function qux() {\n if (!result) {\n result = await initialize();\n }\n}\n\nfunction* generator() {\n result += yield;\n}\n```\n\n\nExamples of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/* eslint require-atomic-updates: error */\n\nlet result;\n\nasync function foobar() {\n result = await something + result;\n}\n\nasync function baz() {\n const tmp = doSomething(await somethingElse);\n result += tmp;\n}\n\nasync function qux() {\n if (!result) {\n const tmp = await initialize();\n if (!result) {\n result = tmp;\n }\n }\n}\n\nasync function quux() {\n let localVariable = 0;\n localVariable += await something;\n}\n\nfunction* generator() {\n result = (yield) + result;\n}\n```\n\n\n### Properties\n\nThis rule reports an assignment to a property through a variable when it detects the following execution flow in a generator or async function:\n\n1. The variable or object property is read.\n2. A `yield` or `await` pauses the function.\n3. After the function is resumed, a value is assigned to a property.\n\nThis logic is similar to the logic for variables, but stricter because the property in step 3 doesn't have to be the same as the property in step 1. It is assumed that the flow depends on the state of the object as a whole.\n\nExample of **incorrect** code for this rule:\n\n**Incorrect code:**\n\n```js\n/* eslint require-atomic-updates: error */\n\nasync function foo(obj) {\n if (!obj.done) {\n obj.something = await getSomething();\n }\n}\n```\n\n\nExample of **correct** code for this rule:\n\n**Correct code:**\n\n```js\n/* eslint require-atomic-updates: error */\n\nasync function foo(obj) {\n if (!obj.done) {\n const tmp = await getSomething();\n if (!obj.done) {\n obj.something = tmp;\n }\n }\n}\n```\n\n\n## Options\n\nThis rule has an object option:\n\n* `\"allowProperties\"`: When set to `true`, the rule does not report assignments to properties. Default is `false`.\n\n### allowProperties\n\nExample of **correct** code for this rule with the `{ \"allowProperties\": true }` option:\n\n**Correct code:**\n\n```js\n/* eslint require-atomic-updates: [\"error\", { \"allowProperties\": true }] */\n\nasync function foo(obj) {\n if (!obj.done) {\n obj.something = await getSomething();\n }\n}\n```\n\n\n## When Not To Use It\n\nIf you don't use async or generator functions, you don't need to enable this rule.",
|
|
1109
|
+
"eslint/max-depth": "Many developers consider code difficult to read if blocks are nested beyond a certain depth.\n\n## Rule Details\n\nThis rule enforces a maximum depth that blocks can be nested to reduce code complexity.\n\n## Options\n\nThis rule has a number or object option:\n\n* `\"max\"` (default `4`) enforces a maximum depth that blocks can be nested\n\n**Deprecated:** The object property `maximum` is deprecated; please use the object property `max` instead.\n\n### max\n\nExamples of **incorrect** code for this rule with the default `{ \"max\": 4 }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint max-depth: [\"error\", 4]*/\n\nfunction foo() {\n for (;;) { // Nested 1 deep\n while (true) { // Nested 2 deep\n if (true) { // Nested 3 deep\n if (true) { // Nested 4 deep\n if (true) { // Nested 5 deep\n }\n }\n }\n }\n }\n}\n```\n\n\nExamples of **correct** code for this rule with the default `{ \"max\": 4 }` option:\n\n**Correct code:**\n\n```js\n/*eslint max-depth: [\"error\", 4]*/\n\nfunction foo() {\n for (;;) { // Nested 1 deep\n while (true) { // Nested 2 deep\n if (true) { // Nested 3 deep\n if (true) { // Nested 4 deep\n }\n }\n }\n }\n}\n```\n\n\nNote that class static blocks do not count as nested blocks, and that the depth in them is calculated separately from the enclosing context.\n\nExamples of **incorrect** code for this rule with `{ \"max\": 2 }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint max-depth: [\"error\", 2]*/\n\nfunction foo() {\n if (true) { // Nested 1 deep\n class C {\n static {\n if (true) { // Nested 1 deep\n if (true) { // Nested 2 deep\n if (true) { // Nested 3 deep\n }\n }\n }\n }\n }\n }\n}\n```\n\n\nExamples of **correct** code for this rule with `{ \"max\": 2 }` option:\n\n**Correct code:**\n\n```js\n/*eslint max-depth: [\"error\", 2]*/\n\nfunction foo() {\n if (true) { // Nested 1 deep\n class C {\n static {\n if (true) { // Nested 1 deep\n if (true) { // Nested 2 deep\n }\n }\n }\n }\n }\n}\n```",
|
|
1110
|
+
"eslint/max-params": "Functions that take numerous parameters can be difficult to read and write because it requires the memorization of what each parameter is, its type, and the order they should appear in. As a result, many coders adhere to a convention that caps the number of parameters a function can take.\n\n```js\nfunction foo (bar, baz, qux, qxx) { // four parameters, may be too many\n doSomething();\n}\n```\n\n## Rule Details\n\nThis rule enforces a maximum number of parameters allowed in function definitions.\n\n## Options\n\nThis rule has a number or object option:\n\n* `\"max\"` (default `3`) enforces a maximum number of parameters in function definitions\n* `\"countThis\"` (default `\"except-void\"`, possible values `\"always\"`, `\"never\"` or `\"except-void\"`) whether to count a `this` declaration (TypeScript only)\n\n**Deprecated:** The object property `maximum` is deprecated; please use the object property `max` instead.\n**Deprecated:** The object property `countVoidThis` is deprecated; please use `countThis: \"except-void\"` instead of `countVoidThis: false`, and `countThis: \"always\"` instead of `countVoidThis: true`.\n\n### max\n\nExamples of **incorrect** code for this rule with the default `{ \"max\": 3 }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint max-params: [\"error\", 3]*/\n\nfunction foo1 (bar, baz, qux, qxx) {\n doSomething();\n}\n\nlet foo2 = (bar, baz, qux, qxx) => {\n doSomething();\n};\n```\n\n\nExamples of **correct** code for this rule with the default `{ \"max\": 3 }` option:\n\n**Correct code:**\n\n```js\n/*eslint max-params: [\"error\", 3]*/\n\nfunction foo1 (bar, baz, qux) {\n doSomething();\n}\n\nlet foo2 = (bar, baz, qux) => {\n doSomething();\n};\n```\n\n\n### countThis (TypeScript only)\n\nThis rule has a TypeScript-specific option `countThis` that allows you to count a `this` declaration.\nValid values are:\n\n* `\"always\"`: any `this` type annotation will count as a parameter\n* `\"never\"`: `this` won't ever be counted\n* `\"except-void\"`: `this` will be counted only if its type is not `void`. Equivalent to the deprecated `countVoidThis: false`.\n\nExamples of **correct** TypeScript code for this rule:\n\n**Correct code:**\n\n```ts\n/*eslint max-params: [\"error\", { \"max\": 2, \"countThis\": \"except-void\" }]*/\n\nfunction hasNoThis(this: void, first: string, second: string) {\n\t// ...\n}\n```\n\n\n**Correct code:**\n\n```ts\n/*eslint max-params: [\"error\", { \"max\": 2, \"countThis\": \"never\" }]*/\n\nfunction hasThis(this: unknown[], first: string, second: string) {\n\t// ...\n}\n```\n\n\nExamples of **incorrect** TypeScript code for this rule:\n\n**Incorrect code:**\n\n```ts\n/*eslint max-params: [\"error\", { \"max\": 2, \"countThis\": \"always\" }]*/\n\nfunction hasNoThis(this: void, first: string, second: string) {\n\t// ...\n}\n```\n\n\n**Incorrect code:**\n\n```ts\n/*eslint max-params: [\"error\", { \"max\": 2, \"countThis\": \"except-void\" }]*/\n\nfunction hasThis(this: unknown[], first: string, second: string) {\n\t// ...\n}\n```",
|
|
1111
|
+
"eslint/max-nested-callbacks": "Many JavaScript libraries use the callback pattern to manage asynchronous operations. A program of any complexity will most likely need to manage several asynchronous operations at various levels of concurrency. A common pitfall that is easy to fall into is nesting callbacks, which makes code more difficult to read the deeper the callbacks are nested.\n\n```js\nfoo(function () {\n bar(function () {\n baz(function() {\n qux(function () {\n\n });\n });\n });\n});\n```\n\n## Rule Details\n\nThis rule enforces a maximum depth that callbacks can be nested to increase code clarity.\n\n## Options\n\nThis rule has a number or object option:\n\n* `\"max\"` (default `10`) enforces a maximum depth that callbacks can be nested\n* `\"checkConstructorCallCallbacks\"` (default `false`) also check callbacks passed to a constructor call\n\n**Deprecated:** The object property `maximum` is deprecated; please use the object property `max` instead.\n\n### max\n\nExamples of **incorrect** code for this rule with the `{ \"max\": 3 }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint max-nested-callbacks: [\"error\", 3]*/\n\nfoo1(function() {\n foo2(function() {\n foo3(function() {\n foo4(function() {\n // Do something\n });\n });\n });\n});\n```\n\n\nExamples of **correct** code for this rule with the `{ \"max\": 3 }` option:\n\n**Correct code:**\n\n```js\n/*eslint max-nested-callbacks: [\"error\", 3]*/\n\nfoo1(handleFoo1);\n\nfunction handleFoo1() {\n foo2(handleFoo2);\n}\n\nfunction handleFoo2() {\n foo3(handleFoo3);\n}\n\nfunction handleFoo3() {\n foo4(handleFoo4);\n}\n\nfunction handleFoo4() {\n foo5();\n}\n```\n\n\n### checkConstructorCallCallbacks\n\nExamples of **incorrect** code for this rule with the `{ \"checkConstructorCallCallbacks\": true }` option:\n\n**Incorrect code:**\n\n```js\n/*eslint max-nested-callbacks: [\"error\", { \"checkConstructorCallCallbacks\": true, \"max\": 1 }]*/\n\nsetTimeout(() => {\n new Promise(function nested() {});\n});\n```\n\n\nExamples of **correct** code for this rule with the `{ \"checkConstructorCallCallbacks\": true }` option:\n\n**Correct code:**\n\n```js\n/*eslint max-nested-callbacks: [\"error\", { \"checkConstructorCallCallbacks\": true, \"max\": 1 }]*/\n\nfunction handler() {\n new Promise(() => {});\n}\n\nsetTimeout(handler);\n```",
|
|
1112
|
+
"jsx-a11y/jsx-a11y/alt-text": "# jsx-a11y/alt-text\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nEnforce that all elements that require alternative text have meaningful information to relay back to the end user. This is a critical component of accessibility for screen reader users in order for them to understand the content's purpose on the page. By default, this rule checks for alternative text on the following elements: `<img>`, `<area>`, `<input type=\"image\">`, and `<object>`.\n\n## How to resolve\n\n### `<img>`\n\nAn `<img>` must have the `alt` prop set with meaningful text or as an empty string to indicate that it is an image for decoration.\n\nFor images that are being used as icons for a button or control, the `alt` prop should be set to an empty string (`alt=\"\"`).\n\n```jsx\n<button>\n <img src=\"icon.png\" alt=\"\" />\n Save\n\n</button>\n```\n\nThe content of an `alt` attribute is used to calculate the accessible label of an element, whereas the text content is used to produce a label for the element. For this reason, adding a label to an icon can produce a confusing or duplicated label on a control that already has appropriate text content.\n\n### `<object>`\n\nAdd alternative text to all embedded `<object>` elements using either inner text, setting the `title` prop, or using the `aria-label` or `aria-labelledby` props.\n\n### `<input type=\"image\">`\n\nAll `<input type=\"image\">` elements must have a non-empty `alt` prop set with a meaningful description of the image or have the `aria-label` or `aria-labelledby` props set.\n\n### `<area>`\n\nAll clickable `<area>` elements within an image map have an `alt`, `aria-label` or `aria-labelledby` prop that describes the purpose of the link.\n\n## Rule options\n\nThis rule takes one optional object argument of type object:\n\n```json\n{\n \"rules\": {\n \"jsx-a11y/alt-text\": [ 2, {\n \"elements\": [ \"img\", \"object\", \"area\", \"input[type=\\\"image\\\"]\" ],\n \"img\": [\"Image\"],\n \"object\": [\"Object\"],\n \"area\": [\"Area\"],\n \"input[type=\\\"image\\\"]\": [\"InputImage\"]\n }],\n }\n}\n```\n\nThe `elements` option is a whitelist for DOM elements to check for alternative text. If an element is removed from the default set of elements (noted above), any custom components for that component will also be ignored. In order to indicate any custom wrapper components that should be checked, you can map the DOM element to an array of JSX custom components. This is a good use case when you have a wrapper component that simply renders an `img` element, for instance (like in React):\n\n```jsx\n// Image.js\nconst Image = props => {\n const {\n alt,\n ...otherProps\n } = props;\n\n return (\n <img alt={alt} {...otherProps} />\n );\n}\n\n...\n\n// Header.js (for example)\n...\nreturn (\n <header>\n <Image alt=\"Logo\" src=\"logo.jpg\" />\n </header>\n\n);\n```\n\nNote that passing props as spread attribute without explicitly the necessary accessibility props defined will cause this rule to fail. Explicitly pass down the set of props needed for rule to pass. Use `Image` component above as a reference for destructuring and applying the prop. **It is a good thing to explicitly pass props that you expect to be passed for self-documentation.** For example:\n\n#### Bad\n\n```jsx\nfunction Foo(props) {\n return <img {...props} />\n}\n```\n\n#### Good\n\n```jsx\nfunction Foo({ alt, ...props}) {\n return <img alt={alt} {...props} />\n}\n\n// OR\n\nfunction Foo(props) {\n const {\n alt,\n\n ...otherProps\n } = props;\n\n return <img alt={alt} {...otherProps} />\n}\n```\n\n### Succeed\n\n```jsx\n<img src=\"foo\" alt=\"Foo eating a sandwich.\" />\n<img src=\"foo\" alt={\"Foo eating a sandwich.\"} />\n<img src=\"foo\" alt={altText} />\n<img src=\"foo\" alt={`${person} smiling`} />\n<img src=\"foo\" alt=\"\" />\n\n<object aria-label=\"foo\" />\n<object aria-labelledby=\"id1\" />\n<object>Meaningful description</object>\n<object title=\"An object\" />\n\n<area aria-label=\"foo\" />\n<area aria-labelledby=\"id1\" />\n\n<area alt=\"This is descriptive!\" />\n\n<input type=\"image\" alt=\"This is descriptive!\" />\n<input type=\"image\" aria-label=\"foo\" />\n<input type=\"image\" aria-labelledby=\"id1\" />\n\n```\n\n### Fail\n\n```jsx\n<img src=\"foo\" />\n<img {...props} />\n<img {...props} alt /> // Has no value\n<img {...props} alt={undefined} /> // Has no value\n<img {...props} alt={`${undefined}`} /> // Has no value\n<img src=\"foo\" role=\"presentation\" /> // Avoid ARIA if it can be achieved without\n\n<img src=\"foo\" role=\"none\" /> // Avoid ARIA if it can be achieved without\n\n<object {...props} />\n\n\n<area {...props} />\n\n<input type=\"image\" {...props} />\n```\n\n## Accessibility guidelines\n\n- [WCAG 1.1.1](https://www.w3.org/WAI/WCAG21/Understanding/non-text-content.html)\n\n### Resources\n\n- [axe-core, object-alt](https://dequeuniversity.com/rules/axe/3.2/object-alt)\n- [axe-core, image-alt](https://dequeuniversity.com/rules/axe/3.2/image-alt)\n- [axe-core, input-image-alt](https://dequeuniversity.com/rules/axe/3.2/input-image-alt)\n- [axe-core, area-alt](https://dequeuniversity.com/rules/axe/3.2/area-alt)",
|
|
1113
|
+
"jsx-a11y/jsx-a11y/anchor-has-content": "# jsx-a11y/anchor-has-content\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nEnforce that anchors have content and that the content is accessible to screen readers. Accessible means that it is not hidden using the `aria-hidden` prop. Refer to the references to learn about why this is important.\n\nAlternatively, you may use the `title` prop or the `aria-label` prop.\n\n## Rule options\n\nThis rule takes one optional object argument of type object:\n\n```json\n{\n \"rules\": {\n \"jsx-a11y/anchor-has-content\": [ 2, {\n \"components\": [ \"Anchor\" ],\n }],\n }\n}\n```\n\nFor the `components` option, these strings determine which JSX elements (**always including** `<a>`) should be checked for having content. This is a good use case when you have a wrapper component that simply renders an `a` element (like in React):\n\n```js\n// Anchor.js\nconst Anchor = props => {\n return (\n <a {...props}>{ props.children }</a>\n );\n}\n\n...\n\n// CreateAccount.js (for example)\n...\nreturn (\n <Anchor>Create Account</Anchor>\n);\n```\n\n\n### Succeed\n```jsx\n<a>Anchor Content!</a>\n<a><TextWrapper /></a>\n<a dangerouslySetInnerHTML={{ __html: 'foo' }} />\n<a title='foo' />\n<a aria-label='foo' />\n```\n\n### Fail\n```jsx\n<a />\n<a><TextWrapper aria-hidden /></a>\n```\n## Accessibility guidelines\n- [WCAG 2.4.4](https://www.w3.org/WAI/WCAG21/Understanding/link-purpose-in-context)\n- [WCAG 4.1.2](https://www.w3.org/WAI/WCAG21/Understanding/name-role-value)\n\n### Resources\n- [axe-core, link-name](https://dequeuniversity.com/rules/axe/3.2/link-name)",
|
|
1114
|
+
"jsx-a11y/jsx-a11y/anchor-is-valid": "# jsx-a11y/anchor-is-valid\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nThe HTML `<a>` element, with a valid `href` attribute, is formally defined as representing a **hyperlink**. That is, a link between one HTML document and another, or between one location inside an HTML document and another location inside the same document.\n\nIn fact, the interactive, underlined `<a>` element has become so synonymous with web navigation that this expectation has become entrenched inside browsers, assistive technologies such as screen readers and in how people generally expect the internet to behave. In short, anchors should navigate.\n\nThe use of JavaScript frameworks and libraries, like _React_, has made it very easy to add or subtract functionality from the standard HTML elements. This has led to _anchors_ often being used in applications based on how they look and function instead of what they represent.\n\nWhilst it is possible, for example, to turn the `<a>` element into a fully functional `<button>` element with ARIA, the native user agent implementations of HTML elements are to be preferred over custom ARIA solutions.\n\n## How do I resolve this error?\n\n### Case: I want to perform an action and need a clickable UI element\n\nThe native user agent implementations of the `<a>` and `<button>` elements not only differ in how they look and how they act when activated, but also in how the user is expected to interact with them. Both are perfectly clickable when using a mouse, but keyboard users expect `<a>` to activate on `enter` only and `<button>` to activate on _both_ `enter` and `space`.\n\nThis is exacerbated by the expectation sighted users have of how _buttons_ and _anchors_ work based on their appearance. Therefore we find that using _anchors_ as _buttons_ can easily create confusion without a relatively complicated ARIA and CSS implementation that only serves to create an element HTML already offers and browsers already implement fully accessibly.\n\nWe are aware that sometimes _anchors_ are used instead of _buttons_ to achieve a specific visual design. When using the `<button>` element this can still be achieved with styling but, due to the meaning many people attach to the standard underlined `<a>` due its appearance, please reconsider this in the design.\n\nConsider the following:\n\n```jsx\n<a href=\"javascript:void(0)\" onClick={foo}>Perform action</a>\n<a href=\"#\" onClick={foo}>Perform action</a>\n<a onClick={foo}>Perform action</a>\n```\n\nAll these _anchor_ implementations indicate that the element is only used to execute JavaScript code. All the above should be replaced with:\n\n```jsx\n<button onClick={foo}>Perform action</button>\n```\n\n### Case: I want navigable links\n\nAn `<a>` element without an `href` attribute no longer functions as a hyperlink. That means that it can no longer accept keyboard focus or be clicked on. The documentation for [no-noninteractive-tabindex](no-noninteractive-tabindex.md) explores this further. Preferably use another element (such as `div` or `span`) for display of text.\n\nTo properly function as a hyperlink, the `href` attribute should be present and also contain a valid _URL_. _JavaScript_ strings, empty values or using only **#** are not considered valid `href` values.\n\nValid `href` attributes values are:\n\n```jsx\n<a href=\"/some/valid/uri\">Navigate to page</a>\n<a href=\"/some/valid/uri#top\">Navigate to page and location</a>\n<a href=\"#top\">Navigate to internal page location</a>\n```\n\n### Case: I need the HTML to be interactive, don't I need to use an a tag for that?\n\nAn `<a>` tag is not inherently interactive. Without an href attribute, it really is no different from a `<span>`.\n\nLet's look at an example that is not accessible by all users:\n\n```jsx\n<a\n className=\"thing\"\n onMouseEnter={() => this.setState({ showSomething: true })}\n>\n {label}\n</a>\n```\n\nIf you need to create an interface element that the user can click on, consider using a button:\n\n```jsx\n<button\n className=\"thing\"\n onClick={() => this.setState({ showSomething: true })}\n>\n {label}\n</button>\n```\n\nIf you want to navigate while providing the user with extra functionality, for example in the `onMouseEnter` event, use an anchor with an `href` attribute containing a URL or path as its value.\n\n```jsx\n<a\n href={someValidPath}\n className=\"thing\"\n onMouseEnter={() => this.setState({ showSomething: true })}\n>\n {label}\n</a>\n```\n\nIf you need to create an interface element that the user can mouse over or mouse out of, consider using a div element. In this case, you may need to apply a role of presentation or an interactive role. Interactive ARIA roles include `button`, `link`, `checkbox`, `menuitem`, `menuitemcheckbox`, `menuitemradio`, `option`, `radio`, `searchbox`, `switch` and `textbox`.\n\n```jsx\n<div\n role=\"menuitem\"\n className=\"thing\"\n onClick={() => this.setState({ showSomething: true })}\n onMouseEnter={() => this.setState({ showSomething: true })}\n>\n {label}\n</div>\n```\n\nIn the example immediately above an `onClick` event handler was added to provide the same experience mouse users enjoy to keyboard-only and touch-screen users. Never fully rely on mouse events alone to expose functionality.\n\n### Case: I use Next.js and I'm getting this error inside of `<Link>`s\n\nThis is a [known issue](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/issues/402) with Next.js's decision to construct internal links by nesting an href-free `<a>` tag inside of a `<Link>` component. Next.js is also [aware of the issue](https://github.com/vercel/next.js/issues/5533) and has an [RFC](https://github.com/vercel/next.js/discussions/8207) working towards a solution.\n\nUntil the Next.js API can be updated to a more performant and standard setup, you have a few workaround options:\n\n1. If you have only a few `Link`s, or they're clustered in just a few files like `nav.tsx`, you can use disable macros like `{/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}` to turn off validation of this rule for those usages.\n\n2. You can use the `Link` component's `passHref` prop to override a dummy `href` on the `<a>`:\n```typescript\n<Link href=\"/my-amazing-page\" passHref>\n <a href=\"replace\">Go to my amazing page</a>\n</Link>\n```\n\n3. You can invest in a custom component that wraps the creation of the `Link` and `a`. You can then add your new custom component to the list of components to validate to ensure that your links are all created with a navigable href. A sample custom component is shared [here](https://gist.github.com/zackdotcomputer/d7af9901e7db87364aad7fbfadb5c99b) and it would be used like this:\n```typescript\n// Internally, LinkTo handles the making of the Link and A, collecting the\n// need for a lint workaround into a single file.\n// Externally, LinkTo can be linted using this rule, ensuring it will always\n// have a valid href prop.\n<LinkTo href=\"/my-amazing-page\">Go to my amazing page</LinkTo>\n```\n\n### Case: I understand the previous cases but still need an element resembling a link that is purely clickable\n\nWe recommend, without reserve, that elements resembling anchors should navigate. This will provide a superior user experience to a larger group of users out there.\n\nHowever, we understand that developers are not always in total control of the visual design of web applications. In cases where it is imperative to provide an element resembling an anchor that purely acts as a click target with no navigation as result, we would like to recommend a compromise.\n\nAgain change the element to a `<button>`:\n\n```jsx\n<button\n type=\"button\"\n className=\"link-button\"\n onClick={() => this.setState({ showSomething: true })}\n>\n Press me, I look like a link\n</button>\n```\n\nThen use styling to change its appearance to that of a link:\n\n```css\n.link-button {\n background-color: transparent;\n border: none;\n cursor: pointer;\n text-decoration: underline;\n display: inline;\n margin: 0;\n padding: 0;\n}\n```\n\nThis button element can now also be used inline in text.\n\nOnce again we stress that this is an inferior implementation and some users will encounter difficulty to use your website, however, it will allow a larger group of people to interact with your website than the alternative of ignoring the rule's warning.\n\n## Rule options\n\nThis rule takes one optional object argument of type object:\n\n```json\n{\n \"rules\": {\n \"jsx-a11y/anchor-is-valid\": [\n \"error\",\n {\n \"components\": [\"Link\"],\n \"specialLink\": [\"hrefLeft\", \"hrefRight\"],\n \"aspects\": [\"noHref\", \"invalidHref\", \"preferButton\"]\n }\n ]\n }\n}\n```\n\nFor the `components` option, these strings determine which JSX elements (**always including** `<a>`) should be checked for the props designated in the `specialLink` options (**always including** `href`). This is a good use case when you have a wrapper component that simply renders an `<a>` element (like in React):\n\n```js\n// Link.js\nconst Link = props => <a {...props}>A link</a>;\n\n...\n\n// NavBar.js (for example)\n...\nreturn (\n <nav>\n <Link href=\"/home\" />\n </nav>\n);\n```\n\nFor the `aspects` option, these strings determine which sub-rules are run. This allows omission of certain error types in restrictive environments.\n\n- `noHref`: Checks whether an anchor contains an `href` attribute.\n- `invalidHref`: Checks if a given `href` value is valid.\n- `preferButton`: Checks if anchors have been used as buttons.\n\nThe option can be used on its own or with the `components` and `specialLink` options.\n\nIf omitted, all sub-rule aspects will be run by default. This is the recommended configuration for all cases except where the rule becomes unusable due to well founded restrictions.\n\nThe option must contain at least one `aspect`.\n\n### Succeed\n\n```jsx\n<a href=\"https://github.com\" />\n<a href=\"#section\" />\n<a href=\"foo\" />\n<a href=\"/foo/bar\" />\n<a href={someValidPath} />\n<a href=\"https://github.com\" onClick={foo} />\n<a href=\"#section\" onClick={foo} />\n<a href=\"foo\" onClick={foo} />\n<a href=\"/foo/bar\" onClick={foo} />\n<a href={someValidPath} onClick={foo} />\n```\n\n### Fail\n\nAnchors should be a button:\n\n```jsx\n<a onClick={foo} />\n<a href=\"#\" onClick={foo} />\n<a href={\"#\"} onClick={foo} />\n<a href={`#`} onClick={foo} />\n<a href=\"javascript:void(0)\" onClick={foo} />\n<a href={\"javascript:void(0)\"} onClick={foo} />\n<a href={`javascript:void(0)`} onClick={foo} />\n```\n\nMissing `href` attribute:\n\n```jsx\n<a />\n<a href={undefined} />\n<a href={null} />\n```\n\nInvalid `href` attribute:\n\n```jsx\n<a href=\"#\" />\n<a href={\"#\"} />\n<a href={`#`} />\n<a href=\"javascript:void(0)\" />\n<a href={\"javascript:void(0)\"} />\n<a href={`javascript:void(0)`} />\n```\n\n## Accessibility guidelines\n\n- [WCAG 2.1.1](https://www.w3.org/WAI/WCAG21/Understanding/keyboard)\n\n### Resources\n\n- [WebAIM - Introduction to Links and Hypertext](https://webaim.org/techniques/hypertext/)\n- [Links vs. Buttons in Modern Web Applications](https://marcysutton.com/links-vs-buttons-in-modern-web-applications/)\n- [Using ARIA - Notes on ARIA use in HTML](https://www.w3.org/TR/using-aria/#NOTES)",
|
|
1115
|
+
"jsx-a11y/jsx-a11y/aria-activedescendant-has-tabindex": "# jsx-a11y/aria-activedescendant-has-tabindex\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\n`aria-activedescendant` is used to manage focus within a [composite widget](https://www.w3.org/TR/wai-aria/#composite).\nThe element with the attribute `aria-activedescendant` retains the active document\nfocus; it indicates which of its child elements has secondary focus by assigning\nthe ID of that element to the value of `aria-activedescendant`. This pattern is\nused to build a widget like a search typeahead select list. The search input box\nretains document focus so that the user can type in the input. If the down arrow\nkey is pressed and a search suggestion is highlighted, the ID of the suggestion\nelement will be applied as the value of `aria-activedescendant` on the input\nelement.\n\nBecause an element with `aria-activedescendant` must be tabbable, it must either\nhave an inherent `tabIndex` of zero or declare a `tabIndex` attribute.\n\n## Rule details\n\nThis rule takes no arguments.\n\n### Succeed\n```jsx\n<CustomComponent />\n<CustomComponent aria-activedescendant={someID} />\n<CustomComponent aria-activedescendant={someID} tabIndex={0} />\n<CustomComponent aria-activedescendant={someID} tabIndex={-1} />\n<div />\n<input />\n<div tabIndex={0} />\n<div aria-activedescendant={someID} tabIndex={0} />\n<div aria-activedescendant={someID} tabIndex=\"0\" />\n<div aria-activedescendant={someID} tabIndex={1} />\n<div aria-activedescendant={someID} tabIndex={-1} />\n<div aria-activedescendant={someID} tabIndex=\"-1\" />\n<input aria-activedescendant={someID} />\n<input aria-activedescendant={someID} tabIndex={0} />\n<input aria-activedescendant={someID} tabIndex={-1} />\n```\n\n### Fail\n```jsx\n<div aria-activedescendant={someID} />\n```\n\n## Accessibility guidelines\nGeneral best practice (reference resources)\n\n### Resources\n- [MDN, Using the aria-activedescendant attribute](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-activedescendant_attribute)",
|
|
1116
|
+
"jsx-a11y/jsx-a11y/aria-props": "# jsx-a11y/aria-props\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nElements cannot use an invalid ARIA attribute. This will fail if it finds an `aria-*` property that is not listed in [WAI-ARIA States and Properties spec](https://www.w3.org/WAI/PF/aria-1.1/states_and_properties).\n\n## Rule details\n\nThis rule takes no arguments.\n\n### Succeed\n```jsx\n<!-- Good: Labeled using correctly spelled aria-labelledby -->\n<div id=\"address_label\">Enter your address</div>\n<input aria-labelledby=\"address_label\">\n```\n\n### Fail\n\n```jsx\n<!-- Bad: Labeled using incorrectly spelled aria-labeledby -->\n<div id=\"address_label\">Enter your address</div>\n<input aria-labeledby=\"address_label\">\n```\n\n## Accessibility guidelines\n- [WCAG 4.1.2](https://www.w3.org/WAI/WCAG21/Understanding/name-role-value)",
|
|
1117
|
+
"jsx-a11y/jsx-a11y/aria-proptypes": "# jsx-a11y/aria-proptypes\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nARIA state and property values must be valid.\n\n## Rule details\n\nThis rule takes no arguments.\n\n### Succeed\n```jsx\n<!-- Good: the aria-hidden state is of type true/false -->\n<span aria-hidden=\"true\">foo</span>\n```\n\n### Fail\n```jsx\n<!-- Bad: the aria-hidden state is of type true/false -->\n<span aria-hidden=\"yes\">foo</span>\n```\n\n## Accessibility guidelines\n- [WCAG 4.1.2](https://www.w3.org/WAI/WCAG21/Understanding/name-role-value)\n\n### Resources\n- [ARIA Spec, States and Properties](https://www.w3.org/TR/wai-aria/#states_and_properties)\n- [Chrome Audit Rules, AX_ARIA_04](https://github.com/GoogleChrome/accessibility-developer-tools/wiki/Audit-Rules#ax_aria_04)",
|
|
1118
|
+
"jsx-a11y/jsx-a11y/aria-role": "# jsx-a11y/aria-role\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nElements with ARIA roles must use a valid, non-abstract ARIA role. A reference to role definitions can be found at [WAI-ARIA](https://www.w3.org/TR/wai-aria/#role_definitions) site.\n\n## Rule options\n\nThis rule takes one optional object argument of type object:\n\n```json\n{\n \"rules\": {\n \"jsx-a11y/aria-role\": [ 2, {\n \"allowedInvalidRoles\": [\"text\"],\n \"ignoreNonDOM\": true\n }],\n }\n}\n```\n\n`allowedInvalidRules` is an optional string array of custom roles that should be allowed in addition to the ARIA spec, such as for cases when you [need to use a non-standard role](https://axesslab.com/text-splitting).\n\nFor the `ignoreNonDOM` option, this determines if developer created components are checked.\n\n### Succeed\n```jsx\n<div role=\"button\"></div> <!-- Good: \"button\" is a valid ARIA role -->\n<div role={role}></div> <!-- Good: role is a variable & cannot be determined until runtime. -->\n<div></div> <!-- Good: No ARIA role -->\n<Foo role={role}></Foo> <!-- Good: ignoreNonDOM is set to true -->\n```\n\n### Fail\n\n```jsx\n<div role=\"datepicker\"></div> <!-- Bad: \"datepicker\" is not an ARIA role -->\n<div role=\"range\"></div> <!-- Bad: \"range\" is an _abstract_ ARIA role -->\n<div role=\"\"></div> <!-- Bad: An empty ARIA role is not allowed -->\n<Foo role={role}></Foo> <!-- Bad: ignoreNonDOM is set to false or not set -->\n```\n\n## Accessibility guidelines\n- [WCAG 4.1.2](https://www.w3.org/WAI/WCAG21/Understanding/name-role-value)\n\n### Resources\n- [Chrome Audit Rules, AX_ARIA_01](https://github.com/GoogleChrome/accessibility-developer-tools/wiki/Audit-Rules#ax_aria_01)\n- [DPUB-ARIA roles](https://www.w3.org/TR/dpub-aria-1.0/)\n- [MDN: Using ARIA: Roles, states, and properties](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques)",
|
|
1119
|
+
"jsx-a11y/jsx-a11y/aria-unsupported-elements": "# jsx-a11y/aria-unsupported-elements\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nCertain reserved DOM elements do not support ARIA roles, states and properties. This is often because they are not visible, for example `meta`, `html`, `script`, `style`. This rule enforces that these DOM elements do not contain the `role` and/or `aria-*` props.\n\n## Rule details\n\nThis rule takes no arguments.\n\n### Succeed\n```jsx\n<!-- Good: the meta element should not be given any ARIA attributes -->\n<meta charset=\"UTF-8\" />\n```\n\n### Fail\n```jsx\n<!-- Bad: the meta element should not be given any ARIA attributes -->\n<meta charset=\"UTF-8\" aria-hidden=\"false\" />\n```\n\n## Accessibility guidelines\n- [WCAG 4.1.2](https://www.w3.org/WAI/WCAG21/Understanding/name-role-value)\n\n### Resources\n- [Chrome Audit Rules, AX_ARIA_12](https://github.com/GoogleChrome/accessibility-developer-tools/wiki/Audit-Rules#ax_aria_12)\n- [DPUB-ARIA roles](https://www.w3.org/TR/dpub-aria-1.0/)",
|
|
1120
|
+
"jsx-a11y/jsx-a11y/autocomplete-valid": "# jsx-a11y/autocomplete-valid\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nEnsure the autocomplete attribute is correct and suitable for the form field it is used with.\n\n## Rule options\n\nThis rule takes one optional object argument of type object:\n\n```\n{\n \"rules\": {\n \"jsx-a11y/autocomplete-valid\": [ 2, {\n \"inputComponents\": [\"Input\", \"FormField\"]\n }],\n }\n}\n```\n\n### Succeed\n```jsx\n<!-- Good: the autocomplete attribute is used according to the HTML specification -->\n<input type=\"text\" autocomplete=\"name\" />\n\n<!-- Good: MyInput is not listed in inputComponents -->\n<MyInput autocomplete=\"incorrect\" />\n```\n\n### Fail\n```jsx\n<!-- Bad: the autocomplete attribute has an invalid value -->\n<input type=\"text\" autocomplete=\"incorrect\" />\n\n<!-- Bad: the autocomplete attribute is on an inappropriate input element -->\n<input type=\"email\" autocomplete=\"url\" />\n\n<!-- Bad: MyInput is listed in inputComponents -->\n<MyInput autocomplete=\"incorrect\" />\n```\n\n## Accessibility guidelines\n- [WCAG 1.3.5](https://www.w3.org/WAI/WCAG21/Understanding/identify-input-purpose)\n\n### Resources\n- [axe-core, autocomplete-valid](https://dequeuniversity.com/rules/axe/3.2/autocomplete-valid)\n- [HTML 5.2, Autocomplete requirements](https://www.w3.org/TR/html52/sec-forms.html#autofilling-form-controls-the-autocomplete-attribute)",
|
|
1121
|
+
"jsx-a11y/jsx-a11y/click-events-have-key-events": "# jsx-a11y/click-events-have-key-events\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nEnforce `onClick` is accompanied by at least one of the following: `onKeyUp`, `onKeyDown`, `onKeyPress`. Coding for the keyboard is important for users with physical disabilities who cannot use a mouse, AT compatibility, and screen reader users. This does not apply for interactive or hidden elements.\n\n## Rule details\n\nThis rule takes no arguments.\n\n### Succeed\n```jsx\n<div onClick={() => {}} onKeyDown={this.handleKeyDown} />\n<div onClick={() => {}} onKeyUp={this.handleKeyUp} />\n<div onClick={() => {}} onKeyPress={this.handleKeyPress} />\n<button onClick={() => {}} />\n<div onClick{() => {}} aria-hidden=\"true\" />\n```\n\n### Fail\n```jsx\n<div onClick={() => {}} />\n```\n\n## Accessibility guidelines\n- [WCAG 2.1.1](https://www.w3.org/WAI/WCAG21/Understanding/keyboard)",
|
|
1122
|
+
"jsx-a11y/jsx-a11y/heading-has-content": "# jsx-a11y/heading-has-content\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nEnforce that heading elements (`h1`, `h2`, etc.) have content and that the content is accessible to screen readers. Accessible means that it is not hidden using the `aria-hidden` prop. Refer to the references to learn about why this is important.\n\n## Rule options\n\nThis rule takes one optional object argument of type object:\n\n```json\n{\n \"rules\": {\n \"jsx-a11y/heading-has-content\": [ 2, {\n \"components\": [ \"MyHeading\" ],\n }],\n }\n}\n```\n\nFor the `components` option, these strings determine which JSX elements (**always including** `<h1>` thru `<h6>`) should be checked for having content. This is a good use case when you have a wrapper component that simply renders an `h1` element (like in React):\n\n\n```js\n// Header.js\nconst Header = props => {\n return (\n <h1 {...props}>{ props.children }</h1>\n );\n}\n\n...\n\n// CreateAccount.js (for example)\n...\nreturn (\n <Header>Create Account</Header>\n);\n```\n\n#### Bad\n```jsx\nfunction Foo(props) {\n return <label {...props} />\n}\n```\n\n### Succeed\n```jsx\n<h1>Heading Content!</h1>\n<h1><TextWrapper /><h1>\n<h1 dangerouslySetInnerHTML={{ __html: 'foo' }} />\n```\n\n### Fail\n```jsx\n<h1 />\n<h1><TextWrapper aria-hidden />\n```\n\n## Accessibility guidelines\n- [WCAG 2.4.6](https://www.w3.org/TR/UNDERSTANDING-WCAG20/navigation-mechanisms-descriptive.html)\n\n### Resources\n- [axe-core, empty-heading](https://dequeuniversity.com/rules/axe/3.2/empty-heading)",
|
|
1123
|
+
"jsx-a11y/jsx-a11y/html-has-lang": "# jsx-a11y/html-has-lang\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\n<html> elements must have the lang prop. This rule is largely superseded by the [`lang` rule](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/HEAD/docs/rules/lang.md).\n\n## Rule details\n\nThis rule takes no arguments.\n\n### Succeed\n```jsx\n<html lang=\"en\">\n<html lang=\"en-US\">\n<html lang={language}>\n```\n\n### Fail\n\n```jsx\n<html>\n```\n\n## Accessibility guidelines\n- [WCAG 3.1.1](https://www.w3.org/WAI/WCAG21/Understanding/language-of-page)\n\n### Resources\n- [axe-core, html-has-lang](https://dequeuniversity.com/rules/axe/3.2/html-has-lang)\n- [axe-core, html-lang-valid](https://dequeuniversity.com/rules/axe/3.2/html-lang-valid)",
|
|
1124
|
+
"jsx-a11y/jsx-a11y/iframe-has-title": "# jsx-a11y/iframe-has-title\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\n`<iframe>` elements must have a unique title property to indicate its content to the user.\n\n## Rule details\n\nThis rule takes no arguments.\n\n### Succeed\n```jsx\n<iframe title=\"This is a unique title\" />\n<iframe title={uniqueTitle} />\n```\n\n### Fail\n```jsx\n<iframe />\n<iframe {...props} />\n<iframe title=\"\" />\n<iframe title={''} />\n<iframe title={``} />\n<iframe title={undefined} />\n<iframe title={false} />\n<iframe title={true} />\n<iframe title={42} />\n```\n\n## Accessibility guidelines\n- [WCAG 2.4.1](https://www.w3.org/WAI/WCAG21/Understanding/bypass-blocks)\n- [WCAG 4.1.2](https://www.w3.org/WAI/WCAG21/Understanding/name-role-value)\n\n### Resources\n- [axe-core, frame-title](https://dequeuniversity.com/rules/axe/3.2/frame-title)",
|
|
1125
|
+
"jsx-a11y/jsx-a11y/img-redundant-alt": "# jsx-a11y/img-redundant-alt\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nEnforce img alt attribute does not contain the word image, picture, or photo. Screen readers already announce `img` elements as an image. There is no need to use words such as *image*, *photo*, and/or *picture*.\n\n## Rule options\n\nThis rule takes one optional object argument of type object:\n\n```json\n{\n \"rules\": {\n \"jsx-a11y/img-redundant-alt\": [ 2, {\n \"components\": [ \"Image\" ],\n \"words\": [ \"Bild\", \"Foto\" ],\n }],\n }\n}\n```\n\nFor the `components` option, these strings determine which JSX elements (**always including** `<img>`) should be checked for having redundant words in the `alt` prop value . This is a good use case when you have a wrapper component that simply renders an `img` element (like in React).\n\nFor the `words` option, these strings can be used to specify custom words that should be checked for in the alt prop, including `image`, `photo`, and `picture`. Useful for specifying words in other languages.\n\nThe rule will first check if `aria-hidden` is true to determine whether to enforce the rule. If the image is hidden, then rule will always succeed.\n\n### Succeed\n```jsx\n<img src=\"foo\" alt=\"Foo eating a sandwich.\" />\n<img src=\"bar\" aria-hidden alt=\"Picture of me taking a photo of an image\" /> // Will pass because it is hidden.\n<img src=\"baz\" alt={`Baz taking a ${photo}`} /> // This is valid since photo is a variable name.\n```\n\n### Fail\n```jsx\n<img src=\"foo\" alt=\"Photo of foo being weird.\" />\n<img src=\"bar\" alt=\"Image of me at a bar!\" />\n<img src=\"baz\" alt=\"Picture of baz fixing a bug.\" />\n```\n\n## Accessibility guidelines\nGeneral best practice (reference resources)\n\n### Resources\n- [WebAIM, Alternative Text](https://webaim.org/techniques/alttext/)",
|
|
1126
|
+
"jsx-a11y/jsx-a11y/interactive-supports-focus": "# jsx-a11y/interactive-supports-focus\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nElements with an interactive role and interaction handlers (mouse or key press) must be focusable.\n\n## How do I resolve this error?\n\n### Case: I got the error \"Elements with the '${role}' interactive role must be tabbable\". How can I fix this?\n\nThis element is a stand-alone control like a button, a link or a form element. A user should be able to reach this element by pressing the tab key on their keyboard.\n\nAdd the `tabIndex` property to your component. A value of zero indicates that this element can be tabbed to.\n\n```jsx\n<div\n role=\"button\"\n tabIndex={0} />\n```\n\n-- or --\n\nReplace the component with one that renders semantic html element like `<button>`, `<a href>` or `<input>` -- whichever fits your purpose.\n\nGenerally buttons, links and form elements should be reachable via tab key presses. An element that can be tabbed to is said to be in the _tab ring_.\n\n### Case: I got the error \"Elements with the '${role}' interactive role must be focusable\". How can I fix this?\n\nThis element is part of a group of buttons, links, menu items, etc. Or this element is part of a composite widget. Composite widgets prescribe standard [keyboard interaction patterns](https://www.w3.org/TR/wai-aria-practices-1.1/#kbd_generalnav). Within a group of similar elements -- like a button bar -- or within a composite widget, elements that can be focused are given a tabindex of -1. This makes the element _focusable_ but not _tabbable_. Generally one item in a group should have a tabindex of zero so that a user can tab to the component. Once an element in the component has focus, your key management behaviors will control traversal within the component's pieces. As the UI author, you will need to implement the key handling behaviors such as listening for traversal key (up/down/left/right) presses and moving the page focus between the focusable elements in your widget.\n\n```jsx\n<div role=\"menu\">\n <div role=\"menuitem\" tabIndex=\"0\">Open</div>\n <div role=\"menuitem\" tabIndex=\"-1\">Save</div>\n <div role=\"menuitem\" tabIndex=\"-1\">Close</div>\n</div>\n```\n\nIn the example above, the first item in the group can be tabbed to. The developer provides the ability to traverse to the subsequent items via the up/down/left/right arrow keys. Traversing via arrow keys is not provided by the browser or the assistive technology. See [Fundamental Keyboard Navigation Conventions](https://www.w3.org/TR/wai-aria-practices-1.1/#kbd_generalnav) for information about established traversal behaviors for various UI widgets.\n\n### Case: This element is not a button, link, menuitem, etc. It is catching bubbled events from elements that it contains\n\nIf your element is catching bubbled click or key events from descendant elements, then the proper role for this element is `presentation`.\n\n```jsx\n<div\n onClick={onClickHandler}\n role=\"presentation\">\n <button>Save</button>\n</div>\n```\n\nMarking an element with the role `presentation` indicates to assistive technology that this element should be ignored; it exists to support the web application and is not meant for humans to interact with directly.\n\n## Rule options\n\nThis rule takes an options object with the key `tabbable`. The value is an array of interactive ARIA roles that should be considered tabbable, not just focusable. Any interactive role not included in this list will be flagged as needing to be focusable (tabindex of -1).\n\n```js\n{\n 'jsx-a11y/interactive-supports-focus': [\n 'error',\n {\n tabbable: [\n 'button',\n 'checkbox',\n 'link',\n 'searchbox',\n 'spinbutton',\n 'switch',\n 'textbox',\n ],\n },\n ]\n}\n```\n\nThe recommended options list interactive roles that act as form elements. Generally, elements with a role like `menuitem` are a part of a composite widget. Focus in a composite widget is controlled and moved programmatically to satisfy the prescribed [keyboard interaction pattern](https://www.w3.org/TR/wai-aria-practices-1.1/#kbd_generalnav) for the widget.\n\nThe list of possible values includes:\n\n```js\n[\n 'button',\n 'checkbox',\n 'columnheader',\n 'combobox',\n 'grid',\n 'gridcell',\n 'link',\n 'listbox',\n 'menu',\n 'menubar',\n 'menuitem',\n 'menuitemcheckbox',\n 'menuitemradio',\n 'option',\n 'progressbar',\n 'radio',\n 'radiogroup',\n 'row',\n 'rowheader',\n 'searchbox',\n 'slider',\n 'spinbutton',\n 'switch',\n 'tab',\n 'tablist',\n 'textbox',\n 'toolbar',\n 'tree',\n 'treegrid',\n 'treeitem',\n 'doc-backlink',\n 'doc-biblioref',\n 'doc-glossref',\n 'doc-noteref',\n]\n```\n\n### Succeed\n\n```jsx\n<!-- Good: div with onClick attribute is hidden from screen reader -->\n<div aria-hidden onClick={() => void 0} />\n<!-- Good: span with onClick attribute is in the tab order -->\n<span onClick=\"doSomething();\" tabIndex=\"0\" role=\"button\">Click me!</span>\n<!-- Good: span with onClick attribute may be focused programmatically -->\n<span onClick=\"doSomething();\" tabIndex=\"-1\" role=\"menuitem\">Click me too!</span>\n<!-- Good: anchor element with href is inherently focusable -->\n<a href=\"javascript:void(0);\" onClick=\"doSomething();\">Click ALL the things!</a>\n<!-- Good: buttons are inherently focusable -->\n<button onClick=\"doSomething();\">Click the button :)</button>\n```\n\n### Fail\n\n```jsx\n<!-- Bad: span with onClick attribute has no tabindex -->\n<span onclick=\"submitForm();\" role=\"button\">Submit</span>\n<!-- Bad: anchor element without href is not focusable -->\n<a onclick=\"showNextPage();\" role=\"button\">Next page</a>\n```\n\n## Accessibility guidelines\n\n- [WCAG 2.1.1](https://www.w3.org/WAI/WCAG21/Understanding/keyboard)\n\n### Resources\n\n- [Chrome Audit Rules, AX_FOCUS_02](https://github.com/GoogleChrome/accessibility-developer-tools/wiki/Audit-Rules#ax_focus_02)\n- [Mozilla Developer Network - ARIA Techniques](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_button_role#Keyboard_and_focus)\n- [Fundamental Keyboard Navigation Conventions](https://www.w3.org/TR/wai-aria-practices-1.1/#kbd_generalnav)\n- [WAI-ARIA Authoring Practices Guide - Design Patterns and Widgets](https://www.w3.org/TR/wai-aria-practices-1.1/#aria_ex)",
|
|
1127
|
+
"jsx-a11y/jsx-a11y/label-has-associated-control": "# jsx-a11y/label-has-associated-control\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nEnforce that a label tag has a text label and an associated control.\n\nThere are two supported ways to associate a label with a control:\n\n- Wrapping a control in a label tag.\n- Adding `htmlFor` to a label and assigning it a DOM ID string that indicates an input on the page.\n\nThis rule checks that any `label` tag (or an indicated custom component that will output a `label` tag) either (1) wraps an `input` element (or an indicated custom component that will output an `input` tag) or (2) has an `htmlFor` attribute and that the `label` tag has text content.\n\n## How do I resolve this error?\n\n### Case: I just want a text label associated with an input.\n\nThe simplest way to achieve an association between a label and an input is to wrap the input in the label.\n\n```jsx\n<label>\n Surname\n <input type=\"text\" />\n</label>\n```\n\nAll modern browsers and assistive technology will associate the label with the control.\n\n### Case: The label is a sibling of the control.\n\nIn this case, use `htmlFor` and an ID to associate the controls.\n\n```jsx\n<label htmlFor={domId}>Surname</label>\n<input type=\"text\" id={domId} />\n```\n\n### Case: My label and input components are custom components.\n\nYou can configure the rule to be aware of your custom components.\n\n```jsx\n<CustomInputLabel label=\"Surname\">\n <CustomInput type=\"text\" value={value} />\n</CustomInputLabel>\n```\n\nAnd the configuration:\n\n```json\n{\n \"rules\": {\n \"jsx-a11y/label-has-associated-control\": [ 2, {\n \"labelComponents\": [\"CustomInputLabel\"],\n \"labelAttributes\": [\"label\"],\n \"controlComponents\": [\"CustomInput\"],\n \"depth\": 3,\n }],\n }\n}\n```\n\n### Case: I have two labels for the same input\n\nIf the second `label` is in a different part of the HTML, then the second one can only contain `htmlFor` but not nesting. You will probably need eslint override comment on the second label.\n\n```jsx\n{/* eslint jsx-a11y/label-has-associated-control: [\"error\", { assert: \"either\" } ] */}\n<label htmlFor=\"a\">\n Username:\n</label>\n...\n<label htmlFor=\"a\">\n <input id=\"a\" />\n</label>\n```\n\n## How to manage IDs of `input`\n\nA common way to think of `id` with libraries like React is, `id`s should be avoided since it must be unique on the page, and components need to be reusable. Hence it is tempted to generate `id` during render-time if `id` is required. *However:*\n\nIDs shouldn't be generated in the browser, so that server and client rendering are deterministic. Render-time uuids aren't just a hack, they're actually broken and should never be used.\n\nTo restate, **every ID needs to be deterministic**, on the server and the client, and guaranteed to be unique on the page. EG: For each input, a required ID prop can be passed down from as far up the tree as possible to guarantee uniqueness.\n\n## Rule options\n\nThis rule takes one optional object argument of type object:\n\n```json\n{\n \"rules\": {\n \"jsx-a11y/label-has-associated-control\": [ 2, {\n \"labelComponents\": [\"CustomLabel\"],\n \"labelAttributes\": [\"inputLabel\"],\n \"controlComponents\": [\"CustomInput\"],\n \"assert\": \"both\",\n \"depth\": 3,\n }],\n }\n}\n```\n\n`labelComponents` is a list of custom React Component names that should be checked for an associated control.\n\n`labelAttributes` is a list of attributes to check on the label component and its children for a label. Use this if you have a custom component that uses a string passed on a prop to render an HTML `label`, for example.\n\n`controlComponents` is a list of custom React Components names that will output an input element. [Glob format](https://linuxhint.com/bash_globbing_tutorial/) is also supported for specifying names (e.g., `Label*` matches `LabelComponent` but not `CustomLabel`, `????Label` matches `LinkLabel` but not `CustomLabel`).\n\n`assert` asserts that the label has htmlFor, a nested label, both or either. Available options: `'htmlFor', 'nesting', 'both', 'either'`.\n\n`depth` (default 2, max 25) is an integer that determines how deep within a `JSXElement` label the rule should look for text content or an element with a label to determine if the `label` element will have an accessible label.\n\n### Fail\n```jsx\nfunction Foo(props) {\n return <label {...props} />\n}\n```\n\n### Succeed\n```jsx\nfunction Foo(props) {\n const {\n htmlFor,\n ...otherProps\n } = props;\n\n return <label htmlFor={htmlFor} {...otherProps} />\n}\n```\n\n### Fail\n```jsx\n<input type=\"text\" />\n<label>Surname</label>\n```\n\n### Succeed\n```jsx\n<label>\n <input type=\"text\" />\n Surname\n</label>\n```\n\n## Accessibility guidelines\n- [WCAG 1.3.1](https://www.w3.org/WAI/WCAG21/Understanding/info-and-relationships)\n- [WCAG 3.3.2](https://www.w3.org/WAI/WCAG21/Understanding/labels-or-instructions)\n- [WCAG 4.1.2](https://www.w3.org/WAI/WCAG21/Understanding/name-role-value)",
|
|
1128
|
+
"jsx-a11y/jsx-a11y/media-has-caption": "# jsx-a11y/media-has-caption\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nProviding captions for media is essential for deaf users to follow along. Captions should be a transcription or translation of the dialogue, sound effects, relevant musical cues, and other relevant audio information. Not only is this important for accessibility, but can also be useful for all users in the case that the media is unavailable (similar to `alt` text on an image when an image is unable to load).\n\nThe captions should contain all important and relevant information to understand the corresponding media. This may mean that the captions are not a 1:1 mapping of the dialogue in the media content. However, captions are *not* necessary for video components with the `muted` attribute.\n\n## Rule options\n\nThis rule takes one optional object argument of type object:\n\n```json\n{\n \"rules\": {\n \"jsx-a11y/media-has-caption\": [ 2, {\n \"audio\": [ \"Audio\" ],\n \"video\": [ \"Video\" ],\n \"track\": [ \"Track\" ],\n }],\n }\n}\n```\n\nFor the `audio`, `video`, and `track` options, these strings determine which JSX elements (**always including** their corresponding DOM element) should be used for this rule. This is a good use case when you have a wrapper component that simply renders an `audio`, `video`, or `track` element (like in React):\n\n### Succeed\n```jsx\n<audio><track kind=\"captions\" {...props} /></audio>\n<video><track kind=\"captions\" {...props} /></video>\n<video muted {...props} ></video>\n```\n\n### Fail\n```jsx\n<audio {...props} />\n<video {...props} />\n```\n\n## Accessibility guidelines\n- [WCAG 1.2.2](https://www.w3.org/WAI/WCAG21/Understanding/captions-prerecorded.html)\n- [WCAG 1.2.3](https://www.w3.org/WAI/WCAG21/Understanding/audio-description-or-media-alternative-prerecorded.html)\n\n### Resources\n- [axe-core, audio-caption](https://dequeuniversity.com/rules/axe/2.1/audio-caption)\n- [axe-core, video-caption](https://dequeuniversity.com/rules/axe/2.1/video-caption)",
|
|
1129
|
+
"jsx-a11y/jsx-a11y/mouse-events-have-key-events": "# jsx-a11y/mouse-events-have-key-events\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nEnforce onmouseover/onmouseout are accompanied by onfocus/onblur. Coding for the keyboard is important for users with physical disabilities who cannot use a mouse, AT compatibility, and screen reader users.\n\n## Rule options\n\nBy default, this rule checks that `onmouseover` is paired with `onfocus` and that `onmouseout` is paired with `onblur`. This rule takes an optional argument to specify other handlers to check for \"hover in\" and/or \"hover out\" events:\n\n```json\n{\n \"rules\": {\n \"jsx-a11y/mouse-events-have-key-events\": [\n \"error\",\n {\n \"hoverInHandlers\": [\n \"onMouseOver\",\n \"onMouseEnter\",\n \"onPointerOver\",\n \"onPointerEnter\"\n ],\n \"hoverOutHandlers\": [\n \"onMouseOut\",\n \"onMouseLeave\",\n \"onPointerOut\",\n \"onPointerLeave\"\n ]\n }\n ]\n }\n}\n```\n\nNote that while `onmouseover` and `onmouseout` are checked by default if no arguments are passed in, those are *not* included by default if you *do* provide an argument, so remember to explicitly include them if you want to check them.\n\n### Succeed\n```jsx\n<div onMouseOver={ () => void 0 } onFocus={ () => void 0 } />\n<div onMouseOut={ () => void 0 } onBlur={ () => void 0 } />\n<div onMouseOver={ () => void 0 } onFocus={ () => void 0 } {...otherProps} />\n<div onMouseOut={ () => void 0 } onBlur={ () => void 0 } {...otherProps} />\n```\n\n### Fail\nIn example 3 and 4 below, even if otherProps contains onBlur and/or onFocus, this rule will still fail. Props should be passed down explicitly for rule to pass.\n\n```jsx\n<div onMouseOver={ () => void 0 } />\n<div onMouseOut={ () => void 0 } />\n<div onMouseOver={ () => void 0 } {...otherProps} />\n<div onMouseOut={ () => void 0 } {...otherProps} />\n```\n\n## Accessibility guidelines\n- [WCAG 2.1.1](https://www.w3.org/WAI/WCAG21/Understanding/keyboard)",
|
|
1130
|
+
"jsx-a11y/jsx-a11y/no-access-key": "# jsx-a11y/no-access-key\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nEnforce no accessKey prop on element. Access keys are HTML attributes that allow web developers to assign keyboard shortcuts to elements. Inconsistencies between keyboard shortcuts and keyboard commands used by screen readers and keyboard-only users create accessibility complications so to avoid complications, access keys should not be used.\n\n### References\n1. [WebAIM](https://webaim.org/techniques/keyboard/accesskey#spec)\n\n## Rule details\n\nThis rule takes no arguments.\n\n### Succeed\n```jsx\n<div />\n```\n\n### Fail\n```jsx\n<div accessKey=\"h\" />\n```\n\n## Accessibility guidelines\nGeneral best practice (reference resources)\n\n### Resources\n- [WebAIM, Keyboard Accessibility: Accesskey](https://webaim.org/techniques/keyboard/accesskey#spec)",
|
|
1131
|
+
"jsx-a11y/jsx-a11y/no-autofocus": "# jsx-a11y/no-autofocus\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nEnforce that autoFocus prop is not used on elements. Autofocusing elements can cause usability issues for sighted and non-sighted users, alike.\n\n## Rule options\n\nThis rule takes one optional object argument of type object:\n\n```json\n{\n \"rules\": {\n \"jsx-a11y/no-autofocus\": [ 2, {\n \"ignoreNonDOM\": true\n }],\n }\n}\n```\n\nFor the `ignoreNonDOM` option, this determines if developer created components are checked.\n\n### Succeed\n```jsx\n<div />\n```\n\n### Fail\n```jsx\n<div autoFocus />\n<div autoFocus=\"true\" />\n<div autoFocus=\"false\" />\n<div autoFocus={undefined} />\n```\n\n## Accessibility guidelines\nGeneral best practice (reference resources)\n\n### Resources\n- [WHATWG HTML Standard, The autofocus attribute](https://html.spec.whatwg.org/multipage/interaction.html#attr-fe-autofocus)\n- [The accessibility of HTML 5 autofocus](https://www.brucelawson.co.uk/2009/the-accessibility-of-html-5-autofocus/)",
|
|
1132
|
+
"jsx-a11y/jsx-a11y/no-distracting-elements": "# jsx-a11y/no-distracting-elements\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nEnforces that no distracting elements are used. Elements that can be visually distracting can cause accessibility issues with visually impaired users. Such elements are most likely deprecated, and should be avoided. By default, the following elements are visually distracting: `<marquee>` and `<blink>`.\n\n## Rule options\n\nThis rule takes one optional object argument of type object:\n\n```json\n{\n \"rules\": {\n \"jsx-a11y/no-distracting-elements\": [ 2, {\n \"elements\": [ \"marquee\", \"blink\" ],\n }],\n }\n}\n```\n\nFor the `elements` option, these strings determine which JSX elements should be checked for usage. This shouldn't need to be configured unless you have a seriously compelling use case for these elements. You cannot add any additional elements than what is offered, as the schema is only valid with the provided enumerated list. If you have another element that you think may cause a11y issues due to visual impairment, please feel free to file an issue or send a PR!\n\n### Succeed\n```jsx\n<div />\n```\n\n### Fail\n```jsx\n<marquee />\n<blink />\n```\n\n## Accessibility guidelines\n- [WCAG 2.2.2](https://www.w3.org/WAI/WCAG21/Understanding/pause-stop-hide)\n\n### Resources\n- [axe-core, marquee](https://dequeuniversity.com/rules/axe/3.2/marquee)\n- [axe-core, blink](https://dequeuniversity.com/rules/axe/3.2/blink)",
|
|
1133
|
+
"jsx-a11y/jsx-a11y/no-interactive-element-to-noninteractive-role": "# jsx-a11y/no-interactive-element-to-noninteractive-role\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nInteractive HTML elements indicate _controls_ in the user interface. Interactive elements include `<a href>`, `<button>`, `<input>`, `<select>`, `<textarea>`.\n\nNon-interactive HTML elements and non-interactive ARIA roles indicate _content_ and _containers_ in the user interface. Non-interactive elements include `<main>`, `<area>`, `<h1>` (,`<h2>`, etc), `<img>`, `<li>`, `<ul>` and `<ol>`.\n\n[WAI-ARIA roles](https://www.w3.org/TR/wai-aria-1.1/#usage_intro) should not be used to convert an interactive element to a non-interactive element. Non-interactive ARIA roles include `article`, `banner`, `complementary`, `img`, `listitem`, `main`, `region` and `tooltip`.\n\n## How do I resolve this error?\n\n### Case: The element should be a container, like an article\n\nWrap your interactive element in a `<div>` with the desired role.\n\n```jsx\n<div role=\"article\">\n <button>Save</button>\n</div>\n```\n\n### Case: The element should be content, like an image\n\nPut the content inside your interactive element.\n\n```jsx\n<div\n role=\"button\"\n onClick={() => {}}\n onKeyPress={() => {}}\n tabIndex=\"0\">\n <div role=\"img\" aria-label=\"Save\" />\n</div>\n```\n\n## Rule options\n\nThe recommended options for this rule allow the `tr` element to be given a role of `presentation` (or its semantic equivalent `none`). Under normal circumstances, an element with an interactive role should not be semantically neutralized with `presentation` (or `none`).\n\nOptions are provided as an object keyed by HTML element name; the value is an array of interactive roles that are allowed on the specified element.\n\n```js\n{\n 'no-interactive-element-to-noninteractive-role': [\n 'error',\n {\n tr: ['none', 'presentation'],\n },\n ]\n}\n```\n\nUnder the recommended options, the following code is valid. It would be invalid under the strict rules.\n\n```jsx\n<tr role=\"presentation\" />\n```\n\n## Accessibility guidelines\n\n- [WCAG 4.1.2](https://www.w3.org/WAI/WCAG21/Understanding/name-role-value)\n\n### Resources\n\n- [ARIA Spec, States and Properties](https://www.w3.org/TR/wai-aria/#states_and_properties)\n- [Chrome Audit Rules, AX_ARIA_04](https://github.com/GoogleChrome/accessibility-developer-tools/wiki/Audit-Rules#ax_aria_04)\n- [WAI-ARIA roles](https://www.w3.org/TR/wai-aria-1.1/#usage_intro)\n- [WAI-ARIA Authoring Practices Guide - Design Patterns and Widgets](https://www.w3.org/TR/wai-aria-practices-1.1/#aria_ex)\n- [Fundamental Keyboard Navigation Conventions](https://www.w3.org/TR/wai-aria-practices-1.1/#kbd_generalnav)\n- [Mozilla Developer Network - ARIA Techniques](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_button_role#Keyboard_and_focus)",
|
|
1134
|
+
"jsx-a11y/jsx-a11y/no-noninteractive-element-interactions": "# jsx-a11y/no-noninteractive-element-interactions\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nNon-interactive HTML elements and non-interactive ARIA roles indicate _content_ and _containers_ in the user interface. A non-interactive element does not support event handlers (mouse and key handlers). Non-interactive elements include `<main>`, `<area>`, `<h1>` (,`<h2>`, etc), `<p>`, `<img>`, `<li>`, `<ul>` and `<ol>`. Non-interactive [WAI-ARIA roles](https://www.w3.org/TR/wai-aria-1.1/#usage_intro) include `article`, `banner`, `complementary`, `img`, `listitem`, `main`, `region` and `tooltip`.\n\n## How do I resolve this error?\n\n### Case: This element acts like a button, link, menuitem, etc\n\nMove the event handler function to an inner element that is either a semantically interactive element (`<button>`, `<a href>`) or that has an interactive role. This leaves the _content_ or _container_ semantic value of this element intact.\n\nCommon interactive roles include:\n\n 1. `button`\n 1. `link`\n 1. `checkbox`\n 1. `menuitem`\n 1. `menuitemcheckbox`\n 1. `menuitemradio`\n 1. `option`\n 1. `radio`\n 1. `searchbox`\n 1. `switch`\n 1. `textbox`\n\nNote: Adding a role to your element does **not** add behavior. When a semantic HTML element like `<button>` is used, then it will also respond to Enter key presses when it has focus. The developer is responsible for providing the expected behavior of an element that the role suggests it would have: focusability and key press support.\nsee [WAI-ARIA Authoring Practices Guide - Design Patterns and Widgets](https://www.w3.org/TR/wai-aria-practices-1.1/#aria_ex).\n\n### Case: This element is catching bubbled events from elements that it contains\n\nMove the event handler function to an inner element like `<div>` and give that element a role of `presentation`. This leaves the _content_ or _container_ semantic value of this element intact.\n\n```jsx\n<div role=\"article\">\n <div\n onClick=\"onClickHandler\"\n onKeyPress={onKeyPressHandler}\n role=\"presentation\">\n {this.props.children}\n </div>\n</div>\n```\n\nMarking an element with the role `presentation` indicates to assistive technology that this element should be ignored; it exists to support the web application and is not meant for humans to interact with directly.\n\n### Case: This is a heading that expands/collapses content on the package\n\nHeaders often double as expand/collapse controls for the content they headline. An accordion component is a common example of this pattern. Rather than assign the interaction handling code to the heading itself, put a button inside the heading instead. This pattern retains the role of the heading and the role of the button.\n\n```jsx\n<h3>\n <button onClick={this._expandSection}>News</button>\n</h3>\n<ul id=\"articles-list\">\n <li>...</li>\n</ul>\n```\n\n### Case: This element is a table cell\n\nTable cells (and tables in general) are meant to contain data. ARIA provides us with a construct called a [Grid](https://w3c.github.io/aria-practices/#grid) that is essentially a 2 dimensional logical container for content and interactive elements.\n\nYou have two options in this case.\n\n#### Option 1, move the interactive content inside the table cells\n\nFor instance, move the button inside the cell:\n\n```jsx\n<table>\n <tr>\n <td><button>Sort</button></td>\n </tr>\n</table>\n```\n\nThis preserves the table cell semantics and the button semantics; the two are not conflated on the cell.\n\n#### Option 2, convert the table into an ARIA grid\n\nIf your user interface has a table-like layout, but is filled with interactive components in the cells, consider converting the table into a grid.\n\n```jsx\n<table role=\"grid\">\n <tr>\n <td role=\"gridcell\" onClick={this.sort}>Sort</td>\n </tr>\n</table>\n```\n\nYou can also put the interactive content inside the grid cell. This maintains the semantic distinction between the cell and the interaction content, although a grid cell can be interactive.\n\n## Rule options\n\nYou may configure which handler props should be taken into account when applying this rule. The recommended configuration includes the following 6 handlers.\n\n```javascript\n'jsx-a11y/no-noninteractive-element-interactions': [\n 'error',\n {\n handlers: [\n 'onClick',\n 'onMouseDown',\n 'onMouseUp',\n 'onKeyPress',\n 'onKeyDown',\n 'onKeyUp',\n ],\n },\n],\n```\n\nAdjust the list of handler prop names in the handlers array to increase or decrease the coverage surface of this rule in your codebase.\n\n### Succeed\n\n```jsx\n<div onClick={() => void 0} role=\"button\" />\n<div onClick={() => void 0} role=\"presentation\" />\n<input type=\"text\" onClick={() => void 0} /> // Interactive element does not require role.\n<button onClick={() => void 0} className=\"foo\" /> // button is interactive.\n<div onClick={() => void 0} role=\"button\" aria-hidden /> // This is hidden from screen reader.\n<Input onClick={() => void 0} type=\"hidden\" /> // This is a higher-level DOM component\n```\n\n### Fail\n\n```jsx\n<li onClick={() => void 0} />\n<div onClick={() => void 0} role=\"listitem\" />\n```\n\n## Accessibility guidelines\n\n- [WCAG 4.1.2](https://www.w3.org/WAI/WCAG21/Understanding/name-role-value)\n\n### Resources\n\n- [WAI-ARIA roles](https://www.w3.org/TR/wai-aria-1.1/#usage_intro)\n- [WAI-ARIA Authoring Practices Guide - Design Patterns and Widgets](https://www.w3.org/TR/wai-aria-practices-1.1/#aria_ex)\n- [Fundamental Keyboard Navigation Conventions](https://www.w3.org/TR/wai-aria-practices-1.1/#kbd_generalnav)\n- [Mozilla Developer Network - ARIA Techniques](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_button_role#Keyboard_and_focus)",
|
|
1135
|
+
"jsx-a11y/jsx-a11y/no-noninteractive-element-to-interactive-role": "# jsx-a11y/no-noninteractive-element-to-interactive-role\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nNon-interactive HTML elements indicate _content_ and _containers_ in the user interface. Non-interactive elements include `<main>`, `<area>`, `<h1>` (,`<h2>`, etc), `<img>`, `<li>`, `<ul>` and `<ol>`.\n\nInteractive HTML elements indicate _controls_ in the user interface. Interactive elements include `<a href>`, `<button>`, `<input>`, `<select>`, `<textarea>`.\n\n[WAI-ARIA roles](https://www.w3.org/TR/wai-aria-1.1/#usage_intro) should not be used to convert a non-interactive element to an interactive element. Interactive ARIA roles include `button`, `link`, `checkbox`, `menuitem`, `menuitemcheckbox`, `menuitemradio`, `option`, `radio`, `searchbox`, `switch` and `textbox`.\n\n## How do I resolve this error?\n\n### Case: This element should be a control, like a button\n\nPut the control inside the non-interactive container element.\n\n```jsx\n<li>\n <div\n role=\"button\"\n onClick={() => {}}\n onKeyPress={() => {}}>\n Save\n </div>\n</li>\n```\n\nOr wrap the content inside your interactive element.\n\n```jsx\n<div\n role=\"button\"\n onClick={() => {}}\n onKeyPress={() => {}}\n tabIndex=\"0\">\n <img src=\"some/file.png\" alt=\"Save\" />\n</div>\n```\n\n## Rule options\n\nThe recommended options for this rule allow several common interactive roles to be applied to a non-interactive element. The options are provided as an object keyed by HTML element name; the value is an array of interactive roles that are allowed on the specified element.\n\n```js\n{\n 'no-noninteractive-element-to-interactive-role': [\n 'error',\n {\n ul: ['listbox', 'menu', 'menubar', 'radiogroup', 'tablist', 'tree', 'treegrid'],\n ol: ['listbox', 'menu', 'menubar', 'radiogroup', 'tablist', 'tree', 'treegrid'],\n li: ['menuitem', 'option', 'row', 'tab', 'treeitem'],\n table: ['grid'],\n td: ['gridcell'],\n },\n ]\n}\n```\n\nUnder the recommended options, the following code is valid. It would be invalid under the strict rules.\n\n```jsx\n<ul role=\"menu\" />\n```\n\n## Accessibility guidelines\n\n- [WCAG 4.1.2](https://www.w3.org/WAI/WCAG21/Understanding/name-role-value)\n\n### Resources\n\n- [WAI-ARIA roles](https://www.w3.org/TR/wai-aria-1.1/#usage_intro)\n- [WAI-ARIA Authoring Practices Guide - Design Patterns and Widgets](https://www.w3.org/TR/wai-aria-practices-1.1/#aria_ex)\n- [Fundamental Keyboard Navigation Conventions](https://www.w3.org/TR/wai-aria-practices-1.1/#kbd_generalnav)\n- [Mozilla Developer Network - ARIA Techniques](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_button_role#Keyboard_and_focus)",
|
|
1136
|
+
"jsx-a11y/jsx-a11y/no-noninteractive-tabindex": "# jsx-a11y/no-noninteractive-tabindex\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nTab key navigation should be limited to elements on the page that can be interacted with. Thus it is not necessary to add a tabindex to items in an unordered list, for example, to make them navigable through assistive technology. These applications already afford page traversal mechanisms based on the HTML of the page. Generally, we should try to reduce the size of the page's tab ring rather than increasing it.\n\n## How do I resolve this error?\n\n### Case: I am using an `<a>` tag. Isn't that interactive?\n\nThe `<a>` tag is tricky. Consider the following:\n\n```jsx\n<a>Edit</a>\n<a href=\"#\">Edit</a>\n<a role=\"button\">Edit</a>\n```\n\nThe bare `<a>` tag is an _anchor_. It has no semantic AX API mapping in either ARIA or the AXObject model. It's as meaningful as `<div>`, which is to say it has no meaning. An `<a>` tag with an `href` attribute has an inherent role of `link`. An `<a>` tag with an explicit role obtains the designated role. In the example above, this role is `button`.\n\n### Case: I am using \"semantic\" HTML. Isn't that interactive?\n\nIf we take a step back into the field of linguistics for a moment, let's consider what it means for something to be \"semantic\". Nothing, in and of itself, has meaning. Meaning is constructed through dialogue. A speaker intends a meaning and a listener/observer interprets a meaning. Each participant constructs their own meaning through dialogue. There is no intrinsic or isolated meaning outside of interaction. Thus, we must ask, given that we have a \"speaker\" who communicates via \"semantic\" HTML, who is listening/observing?\n\nIn our case, the observer is the Accessibility (AX) API. Browsers interpret HTML (inflected at times by ARIA) to construct a meaning (AX Tree) of the page. Whatever the semantic HTML intends has only the force of suggestion to the AX API. Therefore, we have inconsistencies. For example, there is not yet an ARIA role for `text` or `label` and thus no way to change a `<label>` into plain text or a `<span>` into a label via ARIA. `<div>` has an AXObject correpondant `DivRole`, but no such object maps to `<span>`.\n\nWhat this lint rule endeavors to do is apply the AX API understanding of the semantics of an HTML document back onto your code. The concept of interactivity boils down to whether a user can do something with the indicated or focused component.\n\nCommon interactive roles include:\n\n 1. `button`\n 1. `link`\n 1. `checkbox`\n 1. `menuitem`\n 1. `menuitemcheckbox`\n 1. `menuitemradio`\n 1. `option`\n 1. `radio`\n 1. `searchbox`\n 1. `switch`\n 1. `textbox`\n\nEndeavor to limit tabbable elements to those that a user can act upon.\n\n### Case: Shouldn't I add a tabindex so that users can navigate to this item?\n\nIt is not necessary to put a tabindex on an `<article>`, for instance or on `<li>` items; assistive technologies provide affordances to users to find and traverse these containers. Most elements that require a tabindex -- `<a href>`, `<button>`, `<input>`, `<textarea>` -- have it already.\n\nYour application might require an exception to this rule in the case of an element that captures incoming tab traversal for a composite widget. In that case, turn off this rule on a per instance basis. This is an uncommon case.\n\nIf you know that a particular element will be scrollable, you might want to add `tabindex=\"0\"` if your website supports browsers that don't make these containers keyboard-focusable. The current status for this platform feature can be tracked in [Chrome Platform Status \"Feature: Keyboard-focusable scroll containers\"](https://www.chromestatus.com/feature/5231964663578624).\n\n```jsx\n// eslint-disable-next-line no-noninteractive-tabindex\n<pre tabIndex=\"0\">\n <code>{someLongCode}</code>\n</pre>\n```\n\n## Rule options\n\nThe recommended options for this rule allow `tabIndex` on elements with the noninteractive `tabpanel` role. Adding `tabIndex` to a tabpanel is a recommended practice in some instances.\n\n```javascript\n'jsx-a11y/no-noninteractive-tabindex': [\n 'error',\n {\n tags: [],\n roles: ['tabpanel'],\n allowExpressionValues: true,\n },\n]\n```\n\nThe `allowExpressionValues` option determines whether the `role` attribute is allowed to be assigned using an expression. For example, the following would pass in recommended mode if `allowExpressionValues` is set to be `true`:\n\n```jsx\n<div role={ROLE_BUTTON} onClick={() => {}} tabIndex=\"0\" />;\n// In case of a conditional expression, there should be literals on both sides of ternary operator\n<div role={isButton ? \"button\" : \"link\"} onClick={() => {}} tabIndex=\"0\" />;\n```\n\n### Succeed\n\n```jsx\n<div />\n<MyButton tabIndex={0} />\n<button />\n<button tabIndex=\"0\" />\n<button tabIndex={0} />\n<div />\n<div tabIndex=\"-1\" />\n<div role=\"button\" tabIndex=\"0\" />\n<div role=\"article\" tabIndex=\"-1\" />\n<article tabIndex=\"-1\" />\n```\n\n### Fail\n\n```jsx\n<div tabIndex=\"0\" />\n<div role=\"article\" tabIndex=\"0\" />\n<article tabIndex=\"0\" />\n<article tabIndex={0} />\n```\n\n## Accessibility guidelines\n\n- [WCAG 2.1.1](https://www.w3.org/WAI/WCAG21/Understanding/keyboard)\n\n### Resources\n\n- [Fundamental Keyboard Navigation Conventions](https://www.w3.org/TR/wai-aria-practices-1.1/#kbd_generalnav)",
|
|
1137
|
+
"jsx-a11y/jsx-a11y/no-redundant-roles": "# jsx-a11y/no-redundant-roles\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nSome HTML elements have native semantics that are implemented by the browser. This includes default/implicit ARIA roles. Setting an ARIA role that matches its default/implicit role is redundant since it is already set by the browser.\n\n## Rule options\n\nThe default options for this rule allow an implicit role of `navigation` to be applied to a `nav` element as is [advised by w3](https://www.w3.org/WAI/GL/wiki/Using_HTML5_nav_element#Example:The_.3Cnav.3E_element). The options are provided as an object keyed by HTML element name; the value is an array of implicit ARIA roles that are allowed on the specified element.\n\n```js\n{\n 'jsx-a11y/no-redundant-roles': [\n 'error',\n {\n nav: ['navigation'],\n },\n ],\n}\n```\n\n### Succeed\n\n```jsx\n<div />\n<button role=\"presentation\" />\n<MyComponent role=\"main\" />\n```\n\n### Fail\n\n```jsx\n<button role=\"button\" />\n<img role=\"img\" src=\"foo.jpg\" />\n```\n\n## Accessibility guidelines\n\nGeneral best practice (reference resources)\n\n### Resources\n\n- [ARIA Spec, ARIA Adds Nothing to Default Semantics of Most HTML Elements](https://www.w3.org/TR/using-aria/#aria-does-nothing)\n- [Identifying SVG as an image](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#identifying_svg_as_an_image)",
|
|
1138
|
+
"jsx-a11y/jsx-a11y/no-static-element-interactions": "# jsx-a11y/no-static-element-interactions\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nStatic HTML elements do not have semantic meaning. This is clear in the case of `<div>` and `<span>`. It is less so clear in the case of elements that _seem_ semantic, but that do not have a semantic mapping in the accessibility layer. For example `<a>`, `<big>`, `<blockquote>`, `<footer>`, `<picture>`, `<strike>` and `<time>` -- to name a few -- have no semantic layer mapping. They are as void of meaning as `<div>`.\n\nThe [WAI-ARIA `role` attribute](https://www.w3.org/TR/wai-aria-1.1/#usage_intro) confers a semantic mapping to an element. The semantic value can then be expressed to a user via assistive technology.\n\nIn order to add interactivity such as a mouse or key event listener to a static element, that element must be given a role value as well.\n\n## How do I resolve this error?\n\n### Case: This element acts like a button, link, menuitem, etc\n\nIndicate the element's role with the `role` attribute:\n\n```jsx\n<div\n onClick={onClickHandler}\n onKeyPress={onKeyPressHandler}\n role=\"button\"\n tabindex=\"0\">\n Save\n</div>\n```\n\nCommon interactive roles include:\n\n 1. `button`\n 1. `link`\n 1. `checkbox`\n 1. `menuitem`\n 1. `menuitemcheckbox`\n 1. `menuitemradio`\n 1. `option`\n 1. `radio`\n 1. `searchbox`\n 1. `switch`\n 1. `textbox`\n\nNote: Adding a role to your element does **not** add behavior. When a semantic HTML element like `<button>` is used, then it will also respond to Enter key presses when it has focus. The developer is responsible for providing the expected behavior of an element that the role suggests it would have: focusability and key press support.\n\n### Case: The event handler is only being used to capture bubbled events\n\nIf your element is catching bubbled click or key events from descendant elements, there are no appropriate roles for your element: you will have to deactivate the rule. Consider explaining the reason for disabling the rule as well.\n\n```jsx\n{/* The <div> element has a child <button> element that allows keyboard interaction */}\n{/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}\n<div onClick={this.handleButtonClick}>\n <button>Save</button>\n <button>Cancel</button>\n</div>\n```\n\nDo not use the role `presentation` on the element: it removes the element's semantics, and may also remove its children's semantics, creating big issues with assistive technology.\n\n## Rule options\n\nYou may configure which handler props should be taken into account when applying this rule. The recommended configuration includes the following 6 handlers and the `allowExpressionValues` option.\n\n```javascript\n'jsx-a11y/no-static-element-interactions': [\n 'error',\n {\n handlers: [\n 'onClick',\n 'onMouseDown',\n 'onMouseUp',\n 'onKeyPress',\n 'onKeyDown',\n 'onKeyUp',\n ],\n allowExpressionValues: true,\n },\n],\n```\n\nAdjust the list of handler prop names in the handlers array to increase or decrease the coverage surface of this rule in your codebase.\n\nThe `allowExpressionValues` option determines whether the `role` attribute is allowed to be assigned using an expression. For example, the following would pass in recommended mode if `allowExpressionValues` is set to be `true`:\n\n```jsx\n<div role={ROLE_BUTTON} onClick={() => {}} />;\n// In case of a conditional expression, there should be literals on both sides of ternary operator\n<div role={isButton ? \"button\" : \"link\"} onClick={() => {}} />;\n```\n\n### Succeed\n\n```jsx\n<button onClick={() => {}} className=\"foo\" />\n<div className=\"foo\" onClick={() => {}} role=\"button\" />\n<input type=\"text\" onClick={() => {}} />\n```\n\n### Fail\n\n```jsx\n<div onClick={() => {}} />\n```\n\n## Accessibility guidelines\n\n- [WCAG 4.1.2](https://www.w3.org/WAI/WCAG21/Understanding/name-role-value)\n\n### Resources\n\n- [WAI-ARIA `role` attribute](https://www.w3.org/TR/wai-aria-1.1/#usage_intro)\n- [WAI-ARIA Authoring Practices Guide - Design Patterns and Widgets](https://www.w3.org/TR/wai-aria-practices-1.1/#aria_ex)\n- [Fundamental Keyboard Navigation Conventions](https://www.w3.org/TR/wai-aria-practices-1.1/#kbd_generalnav)\n- [Mozilla Developer Network - ARIA Techniques](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_button_role#Keyboard_and_focus)",
|
|
1139
|
+
"jsx-a11y/jsx-a11y/role-has-required-aria-props": "# jsx-a11y/role-has-required-aria-props\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nElements with ARIA roles must have all required attributes for that role.\n\n## Rule details\n\nThis rule takes no arguments.\n\n### Succeed\n```jsx\n<!-- Good: the checkbox role requires the aria-checked state -->\n<span role=\"checkbox\" aria-checked=\"false\" aria-labelledby=\"foo\" tabindex=\"0\"></span>\n```\n\n### Fail\n\n```jsx\n<!-- Bad: the checkbox role requires the aria-checked state -->\n<span role=\"checkbox\" aria-labelledby=\"foo\" tabindex=\"0\"></span>\n```\n\n## Accessibility guidelines\n- [WCAG 4.1.2](https://www.w3.org/WAI/WCAG21/Understanding/name-role-value)\n\n### Resources\n- [ARIA Spec, Roles](https://www.w3.org/TR/wai-aria/#roles)\n- [Chrome Audit Rules, AX_ARIA_03](https://github.com/GoogleChrome/accessibility-developer-tools/wiki/Audit-Rules#ax_aria_03)",
|
|
1140
|
+
"jsx-a11y/jsx-a11y/role-supports-aria-props": "# jsx-a11y/role-supports-aria-props\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nEnforce that elements with explicit or implicit roles defined contain only `aria-*` properties supported by that `role`. Many ARIA attributes (states and properties) can only be used on elements with particular roles. Some elements have implicit roles, such as `<a href=\"#\" />`, which will resolve to `role=\"link\"`.\n\n## Rule details\n\nThis rule takes no arguments.\n\n### Succeed\n```jsx\n<!-- Good: the radiogroup role does support the aria-required property -->\n<ul role=\"radiogroup\" aria-required aria-labelledby=\"foo\">\n <li tabIndex=\"-1\" role=\"radio\" aria-checked=\"false\">Rainbow Trout</li>\n <li tabIndex=\"-1\" role=\"radio\" aria-checked=\"false\">Brook Trout</li>\n <li tabIndex=\"0\" role=\"radio\" aria-checked=\"true\">Lake Trout</li>\n</ul>\n```\n\n### Fail\n\n```jsx\n<!-- Bad: the radio role does not support the aria-required property -->\n<ul role=\"radiogroup\" aria-labelledby=\"foo\">\n <li aria-required tabIndex=\"-1\" role=\"radio\" aria-checked=\"false\">Rainbow Trout</li>\n <li aria-required tabIndex=\"-1\" role=\"radio\" aria-checked=\"false\">Brook Trout</li>\n <li aria-required tabIndex=\"0\" role=\"radio\" aria-checked=\"true\">Lake Trout</li>\n</ul>\n```\n\n## Accessibility guidelines\n- [WCAG 4.1.2](https://www.w3.org/WAI/WCAG21/Understanding/name-role-value)\n\n### Resources\n- [ARIA Spec, States and Properties](https://www.w3.org/TR/wai-aria/#states_and_properties)\n- [Chrome Audit Rules, AX_ARIA_10](https://github.com/GoogleChrome/accessibility-developer-tools/wiki/Audit-Rules#ax_aria_10)",
|
|
1141
|
+
"jsx-a11y/jsx-a11y/scope": "# jsx-a11y/scope\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nThe `scope` prop should be used only on `<th>` elements.\n\n## Rule details\n\nThis rule takes no arguments.\n\n### Succeed\n```jsx\n<th scope=\"col\" />\n<th scope={scope} />\n```\n\n### Fail\n\n```jsx\n<div scope />\n```\n\n## Accessibility guidelines\n- [WCAG 1.3.1](https://www.w3.org/WAI/WCAG21/Understanding/info-and-relationships)\n- [WCAG 4.1.1](https://www.w3.org/WAI/WCAG21/Understanding/parsing)\n\n### Resources\n- [axe-core, scope-attr-valid](https://dequeuniversity.com/rules/axe/3.5/scope-attr-valid)",
|
|
1142
|
+
"jsx-a11y/jsx-a11y/tabindex-no-positive": "# jsx-a11y/tabindex-no-positive\n\n\ud83d\udcbc This rule is enabled in the following configs: \u2611\ufe0f `recommended`, \ud83d\udd12 `strict`.\n\n<!-- end auto-generated rule header -->\n\nAvoid positive `tabIndex` property values to synchronize the flow of the page with keyboard tab order.\n\n## Rule details\n\nThis rule takes no arguments.\n\n### Succeed\n```jsx\n<span tabIndex=\"0\">foo</span>\n<span tabIndex=\"-1\">bar</span>\n<span tabIndex={0}>baz</span>\n```\n\n### Fail\n```jsx\n<span tabIndex=\"5\">foo</span>\n<span tabIndex=\"3\">bar</span>\n<span tabIndex=\"1\">baz</span>\n<span tabIndex=\"2\">never really sure what goes after baz</span>\n```\n\n## Accessibility guidelines\n- [WCAG 2.4.3](https://www.w3.org/WAI/WCAG21/Understanding/focus-order)\n\n### Resources\n- [Chrome Audit Rules, AX_FOCUS_03](https://github.com/GoogleChrome/accessibility-developer-tools/wiki/Audit-Rules#ax_focus_03)"
|
|
1143
|
+
}
|