Path: blob/main/extensions/copilot/src/extension/prompts/node/inline/pythonCookbookData.ts
13404 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45// this file is automatically generated. Do not edit it.6type PromptMap = Record<string, string>;78export const pythonRuffCookbooks: PromptMap = {9'AIR001': 'The variable name should match the `task_id` for clarity and consistency. [Before] ```python from airflow.operators import PythonOperator incorrect_name = PythonOperator(task_id="my_task") ``` [After] ```python from airflow.operators import PythonOperator my_task = PythonOperator(task_id="my_task") ```',10'AIR301': 'Add an explicit `schedule` parameter to the `DAG` instantiation to ensure compatibility with future Airflow versions. [Before] ```python from airflow import DAG # Using the implicit default schedule. dag = DAG(dag_id="my_dag") ``` [After] ```python from datetime import timedelta from airflow import DAG dag = DAG(dag_id="my_dag", schedule=timedelta(days=1)) ```',11'AIR302': 'Replace the deprecated `days_ago` function with a calculation using `timedelta`. [Before] ```python from airflow.utils.dates import days_ago yesterday = days_ago(today, 1) ``` [After] ```python from datetime import timedelta yesterday = today - timedelta(days=1) ```',12'AIR303': 'Update the import statement to reflect the new location of the `FabAuthManager` in the Airflow provider package. [Before] ```python from airflow.auth.managers.fab.fab_auth_manage import FabAuthManager ``` [After] ```python from airflow.providers.fab.auth_manager.fab_auth_manage import FabAuthManager ```',13'ERA001': 'Remove commented-out code to avoid dead code issues. [Before] ```python # print("Hello, world!") ``` [After] ```python # This line has been removed to eliminate dead code. ```',14'FAST001': 'Remove the redundant `response_model` parameter from the FastAPI route. [Before] ```python from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str @app.post("/items/", response_model=Item) async def create_item(item: Item) -> Item: return item ``` [After] ```python from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str @app.post("/items/") async def create_item(item: Item) -> Item: return item ```',15'FAST002': 'Replace the use of `Depends` as a default value with `Annotated` for better clarity and consistency in FastAPI route definitions. [Before] ```python from fastapi import Depends, FastAPI app = FastAPI() async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100): return {"q": q, "skip": skip, "limit": limit} @app.get("/items/") async def read_items(commons: dict = Depends(common_parameters)): return commons ``` [After] ```python from typing import Annotated from fastapi import Depends, FastAPI app = FastAPI() async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100): return {"q": q, "skip": skip, "limit": limit} @app.get("/items/") async def read_items(commons: Annotated[dict, Depends(common_parameters)]): return commons ```',16'FAST003': 'Add the missing path parameter to the function signature to ensure it is accessible in the function body. [Before] ```python from fastapi import FastAPI app = FastAPI() @app.get("/things/{thing_id}") async def read_thing(query: str): ... ``` [After] ```python from fastapi import FastAPI app = FastAPI() @app.get("/things/{thing_id}") async def read_thing(thing_id: int, query: str): ... ```',17'YTT101': 'Use `sys.version_info` instead of `sys.version[:3]` to avoid truncation of version numbers. [Before] ```python import sys sys.version[:3] # Evaluates to "3.1" on Python 3.10. ``` [After] ```python import sys sys.version_info[:2] # Evaluates to (3, 10) on Python 3.10. ```',18'YTT102': 'Use `sys.version_info.minor` instead of `sys.version[2]` to correctly access the minor version number. [Before] ```python import sys sys.version[2] # Evaluates to "1" on Python 3.10. ``` [After] ```python import sys f"{sys.version_info.minor}" # Evaluates to "10" on Python 3.10. ```',19'YTT103': 'Replace string comparison of `sys.version` with tuple comparison using `sys.version_info`. [Before] ```python import sys sys.version > "3.9" # `False` on Python 3.10. ``` [After] ```python import sys sys.version_info > (3, 9) # `True` on Python 3.10. ```',20'YTT201': 'Use a comparison operator to check for Python version compatibility. [Before] ```python import sys if sys.version_info[0] == 3: ... else: print("Python 2") # This will be printed on Python 4. ``` [After] ```python import sys if sys.version_info >= (3,): ... else: print("Python 2") # This will not be printed on Python 4. ```',21'YTT202': 'Replace `six.PY3` with `not six.PY2` to ensure compatibility with future Python versions. [Before] ```python import six six.PY3 # `False` on Python 4. ``` [After] ```python import six not six.PY2 # `True` on Python 4. ```',22'YTT203': 'Use a tuple comparison for `sys.version_info` to ensure compatibility with future Python versions. [Before] ```python import sys if sys.version_info[1] < 7: print("Python 3.6 or earlier.") # This will be printed on Python 4.0. ``` [After] ```python import sys if sys.version_info < (3, 7): print("Python 3.6 or earlier.") ```',23'YTT204': 'Use a tuple comparison for `sys.version_info` to ensure compatibility with future Python versions. [Before] ```python import sys if sys.version_info.minor < 7: print("Python 3.6 or earlier.") # This will be printed on Python 4.0. ``` [After] ```python import sys if sys.version_info < (3, 7): print("Python 3.6 or earlier.") ```',24'YTT301': 'Replace `sys.version[0]` with `sys.version_info.major` to correctly access the major version number. [Before] ```python import sys sys.version[0] # If using Python 10, this evaluates to "1". ``` [After] ```python import sys sys.version_info.major # If using Python 10, this evaluates to "10". ```',25'YTT302': 'Replace string comparison of `sys.version` with tuple comparison using `sys.version_info` for accurate version checks. [Before] ```python import sys sys.version >= "3" # `False` on Python 10. ``` [After] ```python import sys sys.version_info >= (3,) # `True` on Python 10. ```',26'YTT303': 'Use `sys.version_info.major` instead of `sys.version[:1]` to correctly retrieve the major version number. [Before] ```python import sys sys.version[:1] # If using Python 10, this evaluates to "1". ``` [After] ```python import sys sys.version_info.major # If using Python 10, this evaluates to "10". ```',27'ANN001': 'Add type annotations to function arguments for better documentation and type checking. [Before] ```python def foo(x): ... ``` [After] ```python def foo(x: int): ... ```',28'ANN002': 'Add type annotations to `*args` to improve type safety and documentation. [Before] ```python def foo(*args): ... ``` [After] ```python def foo(*args: int): ... ```',29'ANN003': 'Add type annotations to `**kwargs` to improve type safety and documentation. [Before] ```python def foo(**kwargs): ... ``` [After] ```python def foo(**kwargs: int): ... ```',30'ANN101': 'Add a type annotation for the `self` parameter in the method to improve clarity and maintainability. [Before] ```python class Foo: def bar(self): ... ``` [After] ```python class Foo: def bar(self: "Foo"): ... ```',31'ANN102': 'Add a type annotation for the `cls` argument to improve clarity and maintainability. [Before] ```python class Foo: @classmethod def bar(cls): ... ``` [After] ```python from typing import Type class Foo: @classmethod def bar(cls: Type["Foo"]): ... ```',32'ANN201': 'Add return type annotations to the function to improve type safety and documentation. [Before] ```python def add(a, b): return a + b ``` [After] ```python def add(a: int, b: int) -> int: return a + b ```',33'ANN202': 'Add return type annotations to private functions for better documentation and type checking. [Before] ```python def _add(a, b): return a + b ``` [After] ```python def _add(a: int, b: int) -> int: return a + b ```',34'ANN204': 'Add a return type annotation to the `__init__` method to improve type safety and documentation. [Before] ```python class Foo: def __init__(self, x: int): self.x = x ``` [After] ```python class Foo: def __init__(self, x: int) -> None: self.x = x ```',35'ANN205': 'Add a return type annotation to the static method for better type documentation and error checking. [Before] ```python class Foo: @staticmethod def bar(): return 1 ``` [After] ```python class Foo: @staticmethod def bar() -> int: return 1 ```',36'ANN206': 'Add a return type annotation to the class method for better type documentation and error checking. [Before] ```python class Foo: @classmethod def bar(cls): return 1 ``` [After] ```python class Foo: @classmethod def bar(cls) -> int: return 1 ```',37'ANN401': 'Replace the use of `Any` with a more specific type to improve type safety. [Before] ```python from typing import Any MyAny = Any def foo(x: MyAny): ... ``` [After] ```python def foo(x: int): ... ```',38'ASYNC100': 'Add an `await` statement within the context manager to ensure the timeout has an effect. [Before] ```python async def func(): async with asyncio.timeout(2): do_something() ``` [After] ```python async def func(): async with asyncio.timeout(2): do_something() await awaitable() ```',39'ASYNC105': 'Add `await` to the `trio.sleep` call to ensure it is properly awaited. [Before] ```python async def double_sleep(x): trio.sleep(2 * x) ``` [After] ```python async def double_sleep(x): await trio.sleep(2 * x) ```',40'ASYNC109': 'Remove the `timeout` parameter from the async function and use a context manager for timeout handling. [Before] ```python async def long_running_task(timeout): ... async def main(): await long_running_task(timeout=2) ``` [After] ```python async def long_running_task(): ... async def main(): async with asyncio.timeout(2): await long_running_task() ```',41'ASYNC110': 'Replace the use of `asyncio.sleep` in a `while` loop with an `asyncio.Event` to improve efficiency and responsiveness. [Before] ```python DONE = False async def func(): while not DONE: await asyncio.sleep(1) ``` [After] ```python DONE = asyncio.Event() async def func(): await DONE.wait() ```',42'ASYNC115': 'Replace `trio.sleep(0)` with `trio.lowlevel.checkpoint()` for better code clarity. [Before] ```python import trio async def func(): await trio.sleep(0) ``` [After] ```python import trio async def func(): await trio.lowlevel.checkpoint() ```',43'ASYNC116': 'Replace `trio.sleep()` with `trio.sleep_forever()` for delays greater than 24 hours to better convey the intent of indefinite sleeping. [Before] ```python import trio async def func(): await trio.sleep(86401) ``` [After] ```python import trio async def func(): await trio.sleep_forever() ```',44'ASYNC210': 'Replace the blocking HTTP call with an asynchronous HTTP client to prevent blocking the event loop. [Before] ```python async def fetch(): urllib.request.urlopen("https://example.com/foo/bar").read() ``` [After] ```python import aiohttp async def fetch(): async with aiohttp.ClientSession() as session: async with session.get("https://example.com/foo/bar") as resp: ... ```',45'ASYNC220': 'Replace the blocking `os.popen()` call with the non-blocking `asyncio.create_subprocess_shell()` to maintain the benefits of asynchronous programming. [Before] ```python async def foo(): os.popen(cmd) ``` [After] ```python async def foo(): await asyncio.create_subprocess_shell(cmd) ```',46'ASYNC221': 'Replace the blocking `subprocess.run()` with the non-blocking `asyncio.create_subprocess_shell()` to maintain the benefits of asynchronous programming. [Before] ```python async def foo(): subprocess.run(cmd) ``` [After] ```python async def foo(): process = await asyncio.create_subprocess_shell(cmd) ```',47'ASYNC222': 'Replace the blocking call in the async function with an asynchronous equivalent using `asyncio.run_in_executor`. [Before] ```python async def foo(): os.waitpid(0) ``` [After] ```python import asyncio import os def wait_for_process(): os.waitpid(0) async def foo(): await asyncio.get_running_loop().run_in_executor(None, wait_for_process) ```',48'ASYNC230': 'Replace the blocking file open and read methods with their asynchronous counterparts to prevent blocking the event loop. [Before] ```python async def foo(): with open("bar.txt") as f: contents = f.read() ``` [After] ```python import anyio async def foo(): async with await anyio.open_file("bar.txt") as f: contents = await f.read() ```',49'ASYNC251': 'Replace `time.sleep` with `await asyncio.sleep` to prevent blocking the event loop in async functions. [Before] ```python async def fetch(): time.sleep(1) ``` [After] ```python async def fetch(): await asyncio.sleep(1) ```',50'S101': 'Replace the `assert` statement with a conditional check that raises a meaningful exception for better error handling in production. [Before] ```python assert x > 0, "Expected positive value." ``` [After] ```python if x <= 0: raise ValueError("Expected positive value.") ```',51'S102': 'Replace the use of `exec()` with a safer alternative, such as defining a function or using `eval()` for specific cases. [Before] ```python exec("print(\'Hello World\')") ``` [After] ```python def safe_print(): print(\'Hello World\') safe_print() ```',52'S103': 'Change file permissions from overly permissive to more secure. [Before] ```python import os os.chmod("/etc/secrets.txt", 0o666) # rw-rw-rw- ``` [After] ```python import os os.chmod("/etc/secrets.txt", 0o600) # rw------- ``` This change restricts access to the file, allowing only the owner to read and write, thus enhancing security.',53'S104': 'Change the hardcoded binding to a specific interface for improved security. [Before] [python] ```python ALLOWED_HOSTS = ["0.0.0.0"] ``` [After] [python] ```python ALLOWED_HOSTS = ["127.0.0.1", "localhost"] ```',54'S105': 'Replace hardcoded passwords with environment variable retrieval for better security. [Before] ```python SECRET_KEY = "hunter2" ``` [After] ```python import os SECRET_KEY = os.environ["SECRET_KEY"] ```',55'S106': 'Replace hardcoded passwords with environment variables to enhance security. [Before] ```python connect_to_server(password="hunter2") ``` [After] ```python import os connect_to_server(password=os.environ["PASSWORD"]) ```',56'S107': 'Replace hardcoded passwords in function arguments with environment variable retrieval to enhance security. [Before] ```python def connect_to_server(password="hunter2"): ... ``` [After] ```python import os def connect_to_server(password=os.environ["PASSWORD"]): ... ```',57'S108': 'Replace hardcoded temporary file paths with the `tempfile` module to enhance security and avoid conflicts. [Before] ```python with open("/tmp/foo.txt", "w") as file: ... ``` [After] ```python import tempfile with tempfile.NamedTemporaryFile() as file: ... ```',58'S110': 'Replace the `try`-`except`-`pass` pattern with logging to capture exceptions. [Before] ```python try: ... except Exception: pass ``` [After] ```python import logging try: ... except Exception as exc: logging.exception("Exception occurred") ```',59'S112': 'Replace the `try`-`except`-`continue` pattern with logging the exception to avoid suppressing errors. [Before] ```python import logging while predicate: try: ... except Exception: continue ``` [After] ```python import logging while predicate: try: ... except Exception as exc: logging.exception("Error occurred") ```',60'S113': 'Add a `timeout` parameter to the `requests.get` call to prevent indefinite hanging. [Before] ```python import requests requests.get("https://www.example.com/") ``` [After] ```python import requests requests.get("https://www.example.com/", timeout=10) ```',61'S201': 'Change the `debug=True` setting to use an environment variable for better security. [Before] ```python import flask app = Flask() app.run(debug=True) ``` [After] ```python import os import flask app = Flask() app.run(debug=os.environ.get("ENV") == "dev") ```',62'S202': 'Use the `filter` argument in `extractall` for Python 3.12 and later to enhance security. [Before] ```python import tarfile import tempfile tar = tarfile.open(filename) tar.extractall(path=tempfile.mkdtemp()) tar.close() ``` [After] ```python import tarfile import tempfile tar = tarfile.open(filename) tar.extractall(path=tempfile.mkdtemp(), filter=\'data\') tar.close() ```',63'S301': 'Replace `pickle` with a safer serialization format like `json` to avoid security risks associated with deserializing untrusted data. [Before] ```python import pickle with open("foo.pickle", "rb") as file: foo = pickle.load(file) ``` [After] ```python import json with open("foo.json", "r") as file: foo = json.load(file) ```',64'S302': 'Replace the use of `marshal` with a safer serialization format like `json`. [Before] ```python import marshal with open("foo.marshal", "rb") as file: foo = marshal.load(file) ``` [After] ```python import json with open("foo.json", "r") as file: foo = json.load(file) ```',65'S303': 'Replace the use of the weak MD5 hash function with the secure SHA-256 hash function. [Before] ```python from cryptography.hazmat.primitives import hashes digest = hashes.Hash(hashes.MD5()) digest.update(b"Hello, world!") digest.finalize() ``` [After] ```python from cryptography.hazmat.primitives import hashes digest = hashes.Hash(hashes.SHA256()) digest.update(b"Hello, world!") digest.finalize() ```',66'S304': 'Replace the use of the weak ARC4 cipher with a strong, modern cipher like Fernet. [Before] ```python from cryptography.hazmat.primitives.ciphers import Cipher, algorithms algorithm = algorithms.ARC4(key) cipher = Cipher(algorithm, mode=None) encryptor = cipher.encryptor() ``` [After] ```python from cryptography.fernet import Fernet fernet = Fernet(key) ```',67'S305': 'Replace the use of the weak ARC4 algorithm and ECB mode with a stronger algorithm and mode. [Before] ```python from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes algorithm = algorithms.ARC4(key) cipher = Cipher(algorithm, mode=modes.ECB(iv)) encryptor = cipher.encryptor() ``` [After] ```python from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes algorithm = algorithms.AES(key) # Use AES instead of ARC4 cipher = Cipher(algorithm, mode=modes.CFB(iv)) # Use CFB mode instead of ECB encryptor = cipher.encryptor() ```',68'S306': 'Replace the use of `tempfile.mktemp` with `tempfile.TemporaryFile` for better security and automatic file management. [Before] ```python import tempfile tmp_file = tempfile.mktemp() with open(tmp_file, "w") as file: file.write("Hello, world!") ``` [After] ```python import tempfile with tempfile.TemporaryFile() as file: file.write("Hello, world!") ```',69'S307': 'Replace the insecure `eval()` function with `ast.literal_eval()` for safer evaluation of user input. [Before] ```python x = eval(input("Enter a number: ")) ``` [After] ```python from ast import literal_eval x = literal_eval(input("Enter a number: ")) ```',70'S308': 'Remove the use of `mark_safe` to prevent XSS vulnerabilities. [Before] ```python from django.utils.safestring import mark_safe content = mark_safe("<script>alert(\'Hello, world!\')</script>") # XSS. ``` [After] ```python content = "<script>alert(\'Hello, world!\')</script>" # Safe if rendered. ```',71'S310': 'Ensure that only permitted URL schemes are used to prevent security vulnerabilities. [Before] ```python from urllib.request import urlopen url = input("Enter a URL: ") with urlopen(url) as response: ... ``` [After] ```python from urllib.request import urlopen url = input("Enter a URL: ") if not url.startswith(("http:", "https:")): raise ValueError("URL must start with \'http:\' or \'https:\'") with urlopen(url) as response: ... ```',72'S311': 'Replace the use of the `random` module with the `secrets` module for secure random number generation. [Before] ```python import random random.randrange(10) ``` [After] ```python import secrets secrets.randbelow(10) ```',73'S312': `Replace Telnet-related functions with SSH for secure communication. [Before] [python] import telnetlib # Example of using Telnet tn = telnetlib.Telnet('hostname') tn.write(b'command\\n') tn.close() [After] [python] import paramiko # Example of using SSH ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('hostname', username='user', password='pass') stdin, stdout, stderr = ssh.exec_command('command') ssh.close()`,74'S313': 'Replace the insecure XML parser with a secure alternative from the `defusedxml` package. [Before] ```python from xml.etree.cElementTree import parse tree = parse("untrusted.xml") # Vulnerable to XML attacks. ``` [After] ```python from defusedxml.cElementTree import parse tree = parse("untrusted.xml") ```',75'S314': 'Replace the insecure XML parser with a secure alternative from the `defusedxml` package. [Before] ```python from xml.etree.ElementTree import parse tree = parse("untrusted.xml") # Vulnerable to XML attacks. ``` [After] ```python from defusedxml.ElementTree import parse tree = parse("untrusted.xml") ```',76'S315': 'Replace the insecure XML parser with a secure alternative from the `defusedxml` package. [Before] ```python from xml.sax.expatreader import create_parser parser = create_parser() ``` [After] ```python from defusedxml.sax import create_parser parser = create_parser() ```',77'S316': 'Replace the insecure XML parser with a secure alternative from the `defusedxml` package. [Before] ```python from xml.dom.expatbuilder import parse parse("untrusted.xml") ``` [After] ```python from defusedxml.expatbuilder import parse tree = parse("untrusted.xml") ```',78'S317': 'Replace the insecure XML parser with a secure alternative from the `defusedxml` package. [Before] ```python from xml.sax import make_parser make_parser() ``` [After] ```python from defusedxml.sax import make_parser make_parser() ```',79'S318': 'Replace the insecure XML parser with a secure alternative from the `defusedxml` package. [Before] ```python from xml.dom.minidom import parse content = parse("untrusted.xml") ``` [After] ```python from defusedxml.minidom import parse content = parse("untrusted.xml") ```',80'S319': 'Replace the insecure XML parser with a secure alternative from the `defusedxml` package. [Before] ```python from xml.dom.pulldom import parse content = parse("untrusted.xml") ``` [After] ```python from defusedxml.pulldom import parse content = parse("untrusted.xml") ```',81'S320': 'Use a secure XML parser configuration to mitigate risks associated with untrusted XML content. [Before] ```python from lxml import etree content = etree.parse("untrusted.xml") ``` [After] ```python from lxml import etree parser = etree.XMLParser(load_dtd=False, no_network=True, resolve_entities=False) content = etree.parse("untrusted.xml", parser=parser) ``` This fix configures the XML parser to disable DTD loading, network access, and entity resolution, reducing the risk of XML attacks.',82'S321': 'Replace FTP-related functions with SFTP or FTPS for secure data transfer. [Before] ```python from ftplib import FTP ftp = FTP(\'ftp.example.com\') ftp.login(\'user\', \'password\') ``` [After] ```python import paramiko transport = paramiko.Transport((\'sftp.example.com\', 22)) transport.connect(username=\'user\', password=\'password\') sftp = paramiko.SFTPClient.from_transport(transport) ```',83'S323': 'Replace the use of `ssl._create_unverified_context` with `ssl.create_default_context` for secure SSL context creation. [Before] ```python import ssl context = ssl._create_unverified_context() ``` [After] ```python import ssl context = ssl.create_default_context() ```',84'S324': 'Replace the use of the weak MD5 hash function with a secure SHA256 hash function. [Before] ```python import hashlib def certificate_is_valid(certificate: bytes, known_hash: str) -> bool: hash = hashlib.md5(certificate).hexdigest() return hash == known_hash ``` [After] ```python import hashlib def certificate_is_valid(certificate: bytes, known_hash: str) -> bool: hash = hashlib.sha256(certificate).hexdigest() return hash == known_hash ```',85'S401': 'Replace the use of `telnetlib` with a more secure alternative, such as `paramiko` for SSH connections. [Before] ```python import telnetlib ``` [After] ```python import paramiko ```',86'S402': 'Replace the `ftplib` import with a more secure alternative like `paramiko` for SFTP. [Before] ```python import ftplib ``` [After] ```python import paramiko ```',87'S403': 'Replace the use of `pickle` with safer serialization alternatives like `json` or `yaml` to avoid security risks associated with unpickling. [Before] ```python import pickle ``` [After] ```python import json # Use json for safer serialization ```',88'S404': 'Replace the use of `subprocess` with safer alternatives like `os` or `shlex` for command execution. [Before] ```python import subprocess ``` [After] ```python import os ``` This change avoids the potential security risks associated with using `subprocess` for executing shell commands.',89'S405': 'Replace the import of `xml.etree.cElementTree` with `defusedxml.ElementTree` to mitigate XML vulnerabilities. [Before] ```python import xml.etree.cElementTree ``` [After] ```python from defusedxml.ElementTree import ElementTree ```',90'S406': 'Replace the import of `xml.sax` with `defusedxml.ElementTree` to mitigate XML vulnerabilities. [Before] ```python import xml.sax ``` [After] ```python from defusedxml.ElementTree import parse ```',91'S407': 'Replace the import of `xml.dom.expatbuilder` with `defusedxml.ElementTree` to mitigate XML vulnerabilities. [Before] ```python import xml.dom.expatbuilder ``` [After] ```python from defusedxml.ElementTree import parse ```',92'S408': 'Replace the import of `xml.dom.minidom` with `defusedxml.minidom` to mitigate XML vulnerabilities. [Before] ```python import xml.dom.minidom ``` [After] ```python from defusedxml.minidom import parse ```',93'S409': 'Replace the import of `xml.dom.pulldom` with `defusedxml.ElementTree` to mitigate XML vulnerabilities. [Before] ```python import xml.dom.pulldom ``` [After] ```python from defusedxml.ElementTree import parse ```',94'S410': 'Replace the import of `lxml` with `defusedxml` to ensure safe XML parsing. [Before] ```python import lxml ``` [After] ```python from defusedxml.ElementTree import parse ``` This change ensures that you are using a secure method for parsing XML, mitigating the risk of XML attacks.',95'S411': 'Replace the direct import of the `xmlrpc` module with a monkey patch from `defused.xmlrpc`. [Before] ```python import xmlrpc ``` [After] ```python from defused.xmlrpc import monkey_patch monkey_patch() ```',96'S412': 'Remove the import of `wsgiref.handlers.CGIHandler` to avoid potential vulnerabilities associated with CGI. [Before] ```python import wsgiref.handlers.CGIHandler ``` [After] ```python # import wsgiref.handlers.CGIHandler # Removed to prevent vulnerabilities ```',97'S413': 'Replace the import of the deprecated `pycrypto` library with the recommended `cryptography` library. [Before] ```python import Crypto.Random ``` [After] ```python from cryptography.hazmat.primitives import hashes ```',98'S415': 'Replace the import of the `pyghmi` module with a more secure alternative for IPMI communication. [Before] ```python import pyghmi ``` [After] ```python import ipaddress # Example of a more secure alternative ``` This change suggests using a different module that supports secure protocols, as `pyghmi` is associated with insecure IPMI practices.',99'S501': 'Remove the `verify=False` parameter to ensure SSL certificate verification is enabled. [Before] ```python import requests requests.get("https://www.example.com", verify=False) ``` [After] ```python import requests requests.get("https://www.example.com") # By default, `verify=True`. ```',100'S502': 'Replace the insecure SSL/TLS version with a more secure version. [Before] ```python import ssl ssl.wrap_socket(ssl_version=ssl.PROTOCOL_TLSv1) ``` [After] ```python import ssl ssl.wrap_socket(ssl_version=ssl.PROTOCOL_TLSv1_2) ``` This change ensures that the code uses a more secure version of TLS, avoiding known vulnerabilities associated with older versions.',101'S503': 'Change the default SSL/TLS protocol version from an insecure version to a secure one. [Before] ```python import ssl def func(version=ssl.PROTOCOL_TLSv1): ... ``` [After] ```python import ssl def func(version=ssl.PROTOCOL_TLSv1_2): ... ```',102'S504': 'Specify the `ssl_version` parameter in `ssl.wrap_socket()` to ensure secure protocol usage. [Before] ```python import ssl ssl.wrap_socket() ``` [After] ```python import ssl ssl.wrap_socket(ssl_version=ssl.PROTOCOL_TLSv1_2) ```',103'S505': 'Update cryptographic key sizes to meet security standards. [Before] ```python from cryptography.hazmat.primitives.asymmetric import dsa, ec dsa.generate_private_key(key_size=512) ec.generate_private_key(curve=ec.SECT163K1()) ``` [After] ```python from cryptography.hazmat.primitives.asymmetric import dsa, ec dsa.generate_private_key(key_size=2048) # Updated to a secure key size ec.generate_private_key(curve=ec.SECP256R1()) # Updated to a secure curve ```',104'S506': 'Replace `yaml.load` with `yaml.safe_load` to prevent security vulnerabilities when loading untrusted YAML files. [Before] ```python import yaml yaml.load(untrusted_yaml) ``` [After] ```python import yaml yaml.safe_load(untrusted_yaml) ```',105'S507': 'Change the SSH client\'s missing host key policy from `AutoAddPolicy` to `RejectPolicy` to ensure secure verification of the remote host. [Before] ```python from paramiko import client ssh_client = client.SSHClient() ssh_client.set_missing_host_key_policy(client.AutoAddPolicy) ``` [After] ```python from paramiko import client ssh_client = client.SSHClient() ssh_client.set_missing_host_key_policy(client.RejectPolicy) ```',106'S508': 'Change the SNMP model from v1 (mpModel=0) or v2 (mpModel=1) to v3 (mpModel=2) for improved security. [Before] ```python from pysnmp.hlapi import CommunityData CommunityData("public", mpModel=0) ``` [After] ```python from pysnmp.hlapi import CommunityData CommunityData("public", mpModel=2) ```',107'S509': 'Add authentication and privacy keys to the UsmUserData instantiation for SNMPv3 encryption. [Before] ```python from pysnmp.hlapi import UsmUserData UsmUserData("user") ``` [After] ```python from pysnmp.hlapi import UsmUserData UsmUserData("user", "authkey", "privkey") ```',108'S601': 'Sanitize inputs to prevent shell injection vulnerabilities when using `paramiko`. [Before] ```python import paramiko client = paramiko.SSHClient() client.exec_command("echo $HOME") ``` [After] ```python import paramiko import shlex client = paramiko.SSHClient() command = "echo $HOME" safe_command = shlex.quote(command) # Sanitize the command client.exec_command(safe_command) ```',109'S602': 'Replace the use of `shell=True` in subprocess calls to prevent shell injection vulnerabilities. [Before] ```python import subprocess subprocess.run("ls -l", shell=True) ``` [After] ```python import subprocess subprocess.run(["ls", "-l"]) ```',110'S603': 'Validate the input command to ensure it is safe before passing it to `subprocess.run`. [Before] ```python import subprocess cmd = input("Enter a command: ").split() subprocess.run(cmd) ``` [After] ```python import subprocess cmd = input("Enter a command: ").split() if all(arg.isalnum() for arg in cmd): # Basic validation subprocess.run(cmd) else: print("Invalid command.") ```',111'S604': 'Replace `shell=True` with a list of arguments to avoid shell injection vulnerabilities. [Before] ```python import subprocess user_input = input("Enter a command: ") subprocess.run(user_input, shell=True) ``` [After] ```python import subprocess user_input = input("Enter a command: ").split() # Split input into a list subprocess.run(user_input) # Pass the list directly ```',112'S605': 'Replace `os.system` with `subprocess.run` for better security and functionality. [Before] ```python import os # Safe usage (literal string) command = "ls -l" os.system(command) # Potentially unsafe usage (expression) cmd = get_user_input() os.system(cmd) ``` [After] ```python import subprocess # Safe usage (literal string) command = "ls -l" subprocess.run(command, shell=True) # Potentially unsafe usage (expression) cmd = get_user_input() subprocess.run(cmd, shell=True) # Still potentially unsafe; consider validating input. ```',113'S606': 'Use `subprocess.run` instead of `os.spawnlp` for better security and flexibility. [Before] ```python import os def insecure_function(arbitrary_user_input: str): os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", arbitrary_user_input) ``` [After] ```python import subprocess def secure_function(arbitrary_user_input: str): subprocess.run(["/bin/mycmd", arbitrary_user_input], check=True) ```',114'S607': 'Use the full path to the executable to prevent security vulnerabilities. [Before] ```python import subprocess subprocess.Popen(["ruff", "check", "file.py"]) ``` [After] ```python import subprocess subprocess.Popen(["/usr/bin/ruff", "check", "file.py"]) ```',115'S608': 'Use parameterized queries to prevent SQL injection. [Before] ```python query = "DELETE FROM foo WHERE id = \'%s\'" % identifier ``` [After] ```python query = "DELETE FROM foo WHERE id = %s" cursor.execute(query, (identifier,)) ``` This change uses a parameterized query, which separates the SQL command from the data, mitigating the risk of SQL injection.',116'S609': 'Replace wildcard usage in `subprocess.Popen()` with a specific file name to prevent wildcard injection vulnerabilities. [Before] ```python import subprocess subprocess.Popen(["chmod", "777", "*.py"]) ``` [After] ```python import subprocess subprocess.Popen(["chmod", "777", "main.py"]) ```',117'S610': 'Replace non-literal expressions in the `extra` function with literal strings to prevent SQL injection vulnerabilities. [Before] ```python from django.contrib.auth.models import User # String interpolation creates a security loophole that could be used # for SQL injection: User.objects.all().extra(select={"test": "%secure" % "nos"}) ``` [After] ```python from django.contrib.auth.models import User # SQL injection is impossible if all arguments are literal expressions: User.objects.all().extra(select={"test": "secure"}) ```',118'S611': 'Replace the use of `RawSQL` with Django\'s ORM methods to prevent SQL injection vulnerabilities. [Before] ```python from django.db.models.expressions import RawSQL from django.contrib.auth.models import User User.objects.annotate(val=("%secure" % "nos", [])) ``` [After] ```python from django.contrib.auth.models import User User.objects.annotate(val=F(\'some_field\')) # Replace \'some_field\' with the actual field you want to annotate ```',119'S612': 'Remove the insecure `logging.config.listen` call to prevent potential security vulnerabilities. [Before] ```python import logging logging.config.listen(9999) ``` [After] ```python import logging # Removed insecure logging.config.listen call ```',120'S701': 'Set `autoescape=True` in the Jinja2 environment to prevent XSS vulnerabilities. [Before] ```python import jinja2 jinja2.Environment(loader=jinja2.FileSystemLoader(".")) ``` [After] ```python import jinja2 jinja2.Environment(loader=jinja2.FileSystemLoader("."), autoescape=True) ```',121'S702': 'Ensure that Mako templates properly escape variables to prevent XSS vulnerabilities. [Before] ```python from mako.template import Template Template("hello") ``` [After] ```python from mako.template import Template Template("${ \'hello\' | h }") ``` This fix uses the `| h` filter to HTML escape the string "hello", mitigating the risk of XSS attacks.',122'BLE001': 'Replace broad `except` clauses with specific exceptions to avoid catching unintended exceptions. [Before] ```python try: foo() except BaseException: ... ``` [After] ```python try: foo() except FileNotFoundError: ... ```',123'FBT001': 'Refactor the function to avoid using a boolean positional argument for clarity. [Before] ```python from math import ceil, floor def round_number(number: float, up: bool) -> int: return ceil(number) if up else floor(number) round_number(1.5, True) # What does `True` mean? round_number(1.5, False) # What does `False` mean? ``` [After] ```python from math import ceil, floor def round_up(number: float) -> int: return ceil(number) def round_down(number: float) -> int: return floor(number) round_up(1.5) round_down(1.5) ```',124'FBT002': 'Refactor the function to avoid using a boolean positional argument for clarity. [Before] ```python from math import ceil, floor def round_number(number, up=True): return ceil(number) if up else floor(number) round_number(1.5, True) # What does `True` mean? round_number(1.5, False) # What does `False` mean? ``` [After] ```python from math import ceil, floor def round_up(number): return ceil(number) def round_down(number): return floor(number) round_up(1.5) round_down(1.5) ```',125'FBT003': 'Use keyword arguments instead of positional boolean arguments for clarity. [Before] ```python def func(flag: bool) -> None: ... func(True) ``` [After] ```python def func(flag: bool) -> None: ... func(flag=True) ```',126'B002': 'Replace unary prefix increment and decrement operators with augmented assignment statements. [Before] ```python ++x --y ``` [After] ```python x += 1 y -= 1 ```',127'B003': 'Reassigning `os.environ` directly is incorrect; instead, clear it and set individual keys. [Before] ```python import os os.environ = {"foo": "bar"} ``` [After] ```python import os os.environ.clear() os.environ["foo"] = "bar" ```',128'B004': 'Replace `hasattr(obj, "__call__")` with `callable(obj)` for a more reliable check of object callability. [Before] ```python hasattr(obj, "__call__") ``` [After] ```python callable(obj) ```',129'B005': 'Replace the use of `.strip()`, `.lstrip()`, or `.rstrip()` with `str.removeprefix()` or `str.removesuffix()` for clarity and correctness. [Before] ```python "text.txt".strip(".txt") # "e" ``` [After] ```python "text.txt".removesuffix(".txt") # "text" ```',130'B006': 'Change mutable default argument to `None` and initialize inside the function. [Before] ```python def add_to_list(item, some_list=[]): some_list.append(item) return some_list ``` [After] ```python def add_to_list(item, some_list=None): if some_list is None: some_list = [] some_list.append(item) return some_list ```',131'B007': 'Remove unused variable or prefix it with an underscore to indicate intent. [Before] ```python for i, j in foo: bar(i) ``` [After] ```python for i, _j in foo: bar(i) ```',132'B008': 'Replace mutable default arguments with `None` and initialize inside the function to avoid unexpected behavior. [Before] ```python def mutable_default(arg: list[int] = create_list()) -> list[int]: arg.append(4) return arg ``` [After] ```python def better(arg: list[int] | None = None) -> list[int]: if arg is None: arg = create_list() arg.append(4) return arg ```',133'B009': 'Replace `getattr` calls with direct attribute access for constant attribute values. [Before] ```python getattr(obj, "foo") ``` [After] ```python obj.foo ```',134'B010': 'Replace `setattr` with direct attribute assignment for constant values. [Before] ```python setattr(obj, "foo", 42) ``` [After] ```python obj.foo = 42 ```',135'B011': 'Replace `assert False` with `raise AssertionError` to ensure consistent behavior regardless of optimization mode. [Before] ```python assert False ``` [After] ```python raise AssertionError ```',136'B012': 'Remove the `return` statement from the `finally` block to ensure exceptions are not silenced. [Before] ```python def speed(distance, time): try: return distance / time except ZeroDivisionError: raise ValueError("Time cannot be zero") finally: return 299792458 # `ValueError` is silenced ``` [After] ```python def speed(distance, time): try: return distance / time except ZeroDivisionError: raise ValueError("Time cannot be zero") ```',137'B013': 'Replace single-element tuples in exception handlers with the exception type directly for clarity and conciseness. [Before] ```python try: ... except (ValueError,): ... ``` [After] ```python try: ... except ValueError: ... ```',138'B014': 'Remove redundant exception handling to avoid unreachable code. [Before] ```python try: ... except (Exception, ValueError): # `Exception` includes `ValueError`. ... ``` [After] ```python try: ... except Exception: ... ```',139'B015': 'Replace useless comparison with an assert statement to enforce invariants. [Before] ```python foo == bar ``` [After] ```python assert foo == bar, "`foo` and `bar` should be equal." ```',140'B016': 'Replace the literal value in the `raise` statement with an instance of an exception class. [Before] ```python raise "foo" ``` [After] ```python raise Exception("foo") ```',141'B017': 'Replace the use of `Exception` in `assertRaises` with a more specific exception type to avoid catching unintended exceptions. [Before] ```python self.assertRaises(Exception, foo) ``` [After] ```python self.assertRaises(SomeSpecificException, foo) ```',142'B018': 'Assign the result of an expression to an anonymous variable to indicate intentional disregard for its value. [Before] ```python with errors.ExceptionRaisedContext(): obj.attribute ``` [After] ```python with errors.ExceptionRaisedContext(): _ = obj.attribute ```',143'B019': 'Remove the `@lru_cache` decorator from the instance method to prevent memory leaks. [Before] ```python from functools import lru_cache class Number: value: int @lru_cache def squared(self): return square(self.value) ``` [After] ```python from functools import lru_cache class Number: value: int def squared(self): return square(self.value) ```',144'B020': 'Rename the loop control variable to avoid overriding the iterable. [Before] ```python items = [1, 2, 3] for items in items: print(items) ``` [After] ```python items = [1, 2, 3] for item in items: print(item) ```',145'B021': 'Replace f-string with a regular string for proper docstring usage. [Before] ```python def foo(): f"""Not a docstring.""" ``` [After] ```python def foo(): """A docstring.""" ```',146'B022': 'Add an exception type to `contextlib.suppress` to avoid redundancy. [Before] ```python import contextlib with contextlib.suppress(): foo() ``` [After] ```python import contextlib with contextlib.suppress(Exception): foo() ```',147'B023': 'Use default arguments in lambda functions to bind the loop variable correctly. [Before] ```python adders = [lambda x: x + i for i in range(3)] values = [adder(1) for adder in adders] # [3, 3, 3] ``` [After] ```python adders = [lambda x, i=i: x + i for i in range(3)] values = [adder(1) for adder in adders] # [1, 2, 3] ```',148'B024': 'Add an `@abstractmethod` decorator to the `method` to ensure the class is properly defined as abstract. [Before] ```python from abc import ABC from typing import ClassVar class Foo(ABC): class_var: ClassVar[str] = "assigned" def method(self): bar() ``` [After] ```python from abc import ABC, abstractmethod from typing import ClassVar class Foo(ABC): class_var: ClassVar[str] # unassigned @abstractmethod def method(self): bar() ```',149'B025': 'Remove duplicate exception handlers to avoid redundancy. [Before] ```python try: ... except ValueError: ... except ValueError: ... ``` [After] ```python try: ... except ValueError: ... ```',150'B026': 'Avoid using star-argument unpacking after keyword arguments to prevent confusion and potential errors. [Before] ```python def foo(x, y, z): return x, y, z foo(z=3, *[1, 2]) # (1, 2, 3) # No error, but confusing! ``` [After] ```python def foo(x, y, z): return x, y, z foo(*[1, 2], 3) # (1, 2, 3) ```',151'B027': 'Add the `@abstractmethod` decorator to the empty method in the abstract base class. [Before] ```python from abc import ABC class Foo(ABC): def method(self): ... ``` [After] ```python from abc import ABC, abstractmethod class Foo(ABC): @abstractmethod def method(self): ... ```',152'B028': 'Add an explicit `stacklevel` argument to `warnings.warn` calls to provide better context for warnings. [Before] ```python warnings.warn("This is a warning") ``` [After] ```python warnings.warn("This is a warning", stacklevel=2) ```',153'B029': 'Replace the empty tuple in the `except` clause with a specific exception type to ensure proper error handling. [Before] ```python try: 1 / 0 except (): ... ``` [After] ```python try: 1 / 0 except ZeroDivisionError: ... ```',154'B030': 'Change the exception type in the `except` clause to a valid exception class. [Before] ```python try: 1 / 0 except 1: ... ``` [After] ```python try: 1 / 0 except ZeroDivisionError: ... ``` This fix ensures that the `except` clause catches a valid exception type, preventing a `TypeError`.',155'B031': 'Store the generator output from `itertools.groupby()` in a list to ensure it can be reused. [Before] ```python import itertools for name, group in itertools.groupby(data): for _ in range(5): do_something_with_the_group(group) ``` [After] ```python import itertools for name, group in itertools.groupby(data): values = list(group) for _ in range(5): do_something_with_the_group(values) ```',156'B032': 'Replace the colon with an assignment operator to correct the syntax. [Before] ```python a["b"]: 1 ``` [After] ```python a["b"] = 1 ```',157'B033': 'Remove duplicate items from set literals to ensure clarity and avoid redundancy. [Before] ```python {1, 2, 3, 1} ``` [After] ```python {1, 2, 3} ```',158'B034': 'Change positional arguments to keyword arguments for `re.split` to avoid confusion. [Before] ```python import re re.split("pattern", "replacement", 1) ``` [After] ```python import re re.split("pattern", "replacement", maxsplit=1) ```',159'B035': 'Replace the static key in the dictionary comprehension with a dynamic key derived from the iteration variable. [Before] ```python data = ["some", "Data"] {"key": value.upper() for value in data} ``` [After] ```python data = ["some", "Data"] {value: value.upper() for value in data} ```',160'B039': 'Change the default value of `ContextVar` from a mutable object to `None` and initialize a new mutable object inside the logic. [Before] ```python from contextvars import ContextVar cv: ContextVar[list] = ContextVar("cv", default=[]) ``` [After] ```python from contextvars import ContextVar cv: ContextVar[list | None] = ContextVar("cv", default=None) if cv.get() is None: cv.set([]) ```',161'B901': 'Replace the `return` statement with `yield from` to ensure the generator yields values instead of raising `StopIteration`. [Before] ```python from collections.abc import Iterable from pathlib import Path def get_file_paths(file_types: Iterable[str] | None = None) -> Iterable[Path]: dir_path = Path(".") if file_types is None: return dir_path.glob("*") for file_type in file_types: yield from dir_path.glob(f"*.{file_type}") ``` [After] ```python from collections.abc import Iterable from pathlib import Path def get_file_paths(file_types: Iterable[str] | None = None) -> Iterable[Path]: dir_path = Path(".") if file_types is None: yield from dir_path.glob("*") else: for file_type in file_types: yield from dir_path.glob(f"*.{file_type}") ```',162'B903': 'Replace the class with a dataclass to reduce boilerplate code. [Before] ```python class Point: def __init__(self, x: float, y: float): self.x = x self.y = y ``` [After] ```python from dataclasses import dataclass @dataclass class Point: x: float y: float ```',163'B904': 'Add a `from` clause to the `raise` statements for better exception chaining. [Before] ```python try: ... except FileNotFoundError: if ...: raise RuntimeError("...") else: raise UserWarning("...") ``` [After] ```python try: ... except FileNotFoundError as exc: if ...: raise RuntimeError("...") from None else: raise UserWarning("...") from exc ```',164'B905': 'Add the `strict` parameter to `zip` calls to avoid silent truncation of iterables. [Before] ```python zip(a, b) ``` [After] ```python zip(a, b, strict=True) ```',165'B909': 'To avoid modifying the iterable during iteration, create a copy of the list to iterate over instead. [Before] ```python items = [1, 2, 3] for item in items: print(item) items.append(item) ``` [After] ```python items = [1, 2, 3] for item in items[:]: # Iterate over a copy of the list print(item) items.append(item) ```',166'B911': 'Add the `strict` parameter to `itertools.batched` calls to ensure explicit control over batch length. [Before] ```python import itertools batches = itertools.batched(iterable, n) ``` [After] ```python import itertools batches = itertools.batched(iterable, n, strict=True) # or strict=False ```',167'A001': 'Rename the variable `max` to avoid shadowing the built-in `max()` function. [Before] ```python def find_max(list_of_lists): max = 0 for flat_list in list_of_lists: for value in flat_list: max = max(max, value) # TypeError: \'int\' object is not callable return max ``` [After] ```python def find_max(list_of_lists): result = 0 for flat_list in list_of_lists: for value in flat_list: result = max(result, value) return result ```',168'A002': 'Rename function arguments to avoid shadowing built-in names. [Before] ```python def remove_duplicates(list, list2): result = set() for value in list: result.add(value) for value in list2: result.add(value) return list(result) # TypeError: \'list\' object is not callable ``` [After] ```python def remove_duplicates(list1, list2): result = set() for value in list1: result.add(value) for value in list2: result.add(value) return list(result) ```',169'A003': 'Rename the `list` method to avoid shadowing the built-in `list` type. [Before] ```python class Class: @staticmethod def list() -> None: pass @staticmethod def repeat(value: int, times: int) -> list[int]: return [value] * times ``` [After] ```python class Class: @staticmethod def custom_list() -> None: pass @staticmethod def repeat(value: int, times: int) -> list[int]: return [value] * times ``` This change prevents confusion and potential errors by ensuring that the method name does not conflict with the built-in `list`.',170'A004': 'Rename the imported function to avoid conflict with the built-in name. [Before] ```python from rich import print print("Some message") ``` [After] ```python from rich import print as rich_print rich_print("Some message") ``` This change prevents confusion between the imported function and the built-in `print` function, enhancing code readability and maintainability.',171'A005': 'Rename the custom module to avoid name clashes with the standard library. [Before] ```python # random.py import random def get_random_choice(): return random.choice([1, 2, 3]) ``` [After] ```python # my_random.py import random def get_random_choice(): return random.choice([1, 2, 3]) ``` Renaming `random.py` to `my_random.py` prevents conflicts with the built-in `random` module, ensuring that imports work as intended.',172'A006': 'The code does not seem to contain any specific errors, but it could benefit from a more explicit example of how to implement the `builtins-ignorelist` configuration option. [Before] [python] # Example of a lambda using a builtin name my_lambda = lambda list: list.append(1) [After] [python] # Example of a lambda using a builtin name with ignorelist # Configuration in .flake8 [flake8] lint.flake8-builtins.builtins-ignorelist = list my_lambda = lambda my_list: my_list.append(1)',173'COM812': 'Add a trailing comma to the last item in the dictionary for better version control. [Before] ```python foo = { "bar": 1, "baz": 2 } ``` [After] ```python foo = { "bar": 1, "baz": 2, } ```',174'COM818': 'Remove the trailing comma to avoid creating an unintended tuple. [Before] ```python import json foo = json.dumps({"bar": 1}), ``` [After] ```python import json foo = json.dumps({"bar": 1}) ```',175'COM819': 'Remove unnecessary trailing commas to adhere to best practices. [Before] ```python foo = (1, 2, 3,) ``` [After] ```python foo = (1, 2, 3) ```',176'C400': 'Replace unnecessary generator expressions with list comprehensions or direct list calls for clarity and idiomatic code. [Before] ```python list(f(x) for x in foo) list(x for x in foo) list((x for x in foo)) ``` [After] ```python [f(x) for x in foo] list(foo) list(foo) ```',177'C401': 'Replace unnecessary generator expressions with set comprehensions or direct set calls for clarity and idiomatic usage. [Before] ```python set(f(x) for x in foo) set(x for x in foo) set((x for x in foo)) ``` [After] ```python {f(x) for x in foo} set(foo) set(foo) ```',178'C402': 'Replace the use of `dict()` with a dictionary comprehension for clarity and idiomatic code. [Before] ```python dict((x, f(x)) for x in foo) ``` [After] ```python {x: f(x) for x in foo} ```',179'C403': 'Replace the list comprehension inside `set()` with a set comprehension for better performance and readability. [Before] ```python set([f(x) for x in foo]) ``` [After] ```python {f(x) for x in foo} ```',180'C404': 'Replace the unnecessary list comprehension with a dictionary comprehension for better readability and performance. [Before] ```python dict([(x, f(x)) for x in foo]) ``` [After] ```python {x: f(x) for x in foo} ```',181'C405': 'Replace unnecessary list or tuple literals in `set()` calls with set literals for improved readability and performance. [Before] ```python set([1, 2]) set((1, 2)) set([]) ``` [After] ```python {1, 2} {1, 2} set() ```',182'C406': 'Replace unnecessary list or tuple literals in `dict()` calls with dictionary literals for improved readability and performance. [Before] ```python dict([(1, 2), (3, 4)]) dict(((1, 2), (3, 4))) dict([]) ``` [After] ```python {1: 2, 3: 4} {1: 2, 3: 4} {} ```',183'C408': 'Replace unnecessary calls to `dict()`, `list()`, and `tuple()` with their respective empty literals for better performance and readability. [Before] ```python dict() dict(a=1, b=2) list() tuple() ``` [After] ```python {} {"a": 1, "b": 2} [] () ```',184'C409': 'Remove unnecessary list or tuple literals in `tuple()` calls and replace list comprehensions with generator expressions. [Before] ```python tuple([1, 2]) tuple((1, 2)) tuple([x for x in range(10)]) ``` [After] ```python (1, 2) (1, 2) tuple(x for x in range(10)) ```',185'C410': 'Remove unnecessary `list()` calls that wrap list or tuple literals. [Before] ```python list([1, 2]) list((1, 2)) ``` [After] ```python [1, 2] [1, 2] ```',186'C411': 'Remove unnecessary `list()` calls around list comprehensions for cleaner code. [Before] ```python list([f(x) for x in foo]) ``` [After] ```python [f(x) for x in foo] ```',187'C413': 'Remove unnecessary `list()` or `reversed()` calls around `sorted()` for clarity and efficiency. [Before] ```python reversed(sorted(iterable)) ``` [After] ```python sorted(iterable, reverse=True) ```',188'C414': 'Remove unnecessary double-casting of iterables to improve code clarity and efficiency. [Before] ```python list(tuple(iterable)) ``` [After] ```python list(iterable) ```',189'C415': 'Remove unnecessary subscript reversal of the iterable before passing it to functions that already handle order. [Before] ```python sorted(iterable[::-1]) set(iterable[::-1]) reversed(iterable[::-1]) ``` [After] ```python sorted(iterable) set(iterable) reversed(iterable) ```',190'C416': 'Replace unnecessary dict, list, or set comprehensions with their respective constructors for improved readability and performance, but be cautious with dictionary comprehensions that iterate over mappings. [Before] ```python {a: b for a, b in iterable} [x for x in iterable] {x for x in iterable} ``` [After] ```python dict(iterable) list(iterable) set(iterable) ```',191'C417': 'Replace `map()` with a generator expression for improved performance and readability. [Before] ```python map(lambda x: x + 1, iterable) ``` [After] ```python (x + 1 for x in iterable) ```',192'C418': 'Remove unnecessary `dict()` calls that wrap dictionary literals or comprehensions. [Before] ```python dict({}) dict({"a": 1}) ``` [After] ```python {} {"a": 1} ``` This fix simplifies the code by directly using dictionary literals instead of wrapping them in `dict()`, which is redundant.',193'C419': 'Replace unnecessary list comprehensions with generator expressions for built-in functions to improve performance and memory usage. [Before] ```python any([x.id for x in bar]) all([x.id for x in bar]) sum([x.val for x in bar]) min([x.val for x in bar]) max([x.val for x in bar]) ``` [After] ```python any(x.id for x in bar) all(x.id for x in bar) sum(x.val for x in bar) min(x.val for x in bar) max(x.val for x in bar) ```',194'C420': 'Replace unnecessary dict comprehensions with `dict.fromkeys` for better readability and efficiency. [Before] ```python {a: None for a in iterable} {a: 1 for a in iterable} ``` [After] ```python dict.fromkeys(iterable) dict.fromkeys(iterable, 1) ```',195'CPY001': `The code needs to ensure it checks for the presence of a copyright notice correctly within the specified byte limit. [Before] [python] def check_copyright(file_path): with open(file_path, 'rb') as f: content = f.read(4096) return b'Copyright' not in content [After] [python] def check_copyright(file_path): with open(file_path, 'rb') as f: content = f.read(4096) return b'Copyright' not in content # Ensure 'Copyright' is checked in a case-insensitive manner.`,196'DTZ001': 'Add timezone information to `datetime` instantiations to avoid naive datetime objects. [Before] ```python import datetime datetime.datetime(2000, 1, 1, 0, 0, 0) ``` [After] ```python import datetime datetime.datetime(2000, 1, 1, 0, 0, 0, tzinfo=datetime.timezone.utc) ```',197'DTZ002': 'Replace `datetime.datetime.today()` with `datetime.datetime.now(tz=...)` to ensure the `datetime` object is timezone-aware. [Before] ```python import datetime datetime.datetime.today() ``` [After] ```python import datetime datetime.datetime.now(tz=datetime.timezone.utc) ``` Or, for Python 3.11 and later: ```python import datetime datetime.datetime.now(tz=datetime.UTC) ```',198'DTZ003': 'Replace `datetime.datetime.utcnow()` with `datetime.datetime.now(tz=datetime.timezone.utc)` to ensure the datetime object is timezone-aware. [Before] ```python import datetime datetime.datetime.utcnow() ``` [After] ```python import datetime datetime.datetime.now(tz=datetime.timezone.utc) ```',199'DTZ004': 'Replace `utcfromtimestamp()` with `fromtimestamp()` to ensure the datetime object is timezone-aware. [Before] ```python import datetime datetime.datetime.utcfromtimestamp(946684800) ``` [After] ```python import datetime datetime.datetime.fromtimestamp(946684800, tz=datetime.timezone.utc) ```',200'DTZ005': 'Use timezone-aware datetime objects instead of naive ones by specifying a timezone when calling `datetime.datetime.now()`. [Before] ```python import datetime datetime.datetime.now() ``` [After] ```python import datetime datetime.datetime.now(tz=datetime.timezone.utc) ```',201'DTZ006': 'Always specify a timezone when using `datetime.datetime.fromtimestamp()` to avoid creating naive datetime objects. [Before] ```python import datetime datetime.datetime.fromtimestamp(946684800) ``` [After] ```python import datetime datetime.datetime.fromtimestamp(946684800, tz=datetime.timezone.utc) ```',202'DTZ007': 'Ensure datetime objects are timezone-aware by using `.replace(tzinfo=<timezone>)` or `.astimezone()` after `strptime()`. [Before] ```python import datetime datetime.datetime.strptime("2022/01/31", "%Y/%m/%d") ``` [After] ```python import datetime datetime.datetime.strptime("2022/01/31", "%Y/%m/%d").replace( tzinfo=datetime.timezone.utc ) ```',203'DTZ011': 'Replace `datetime.date.today()` with a timezone-aware alternative to avoid naive datetime objects. [Before] ```python import datetime datetime.date.today() ``` [After] ```python import datetime datetime.datetime.now(tz=datetime.timezone.utc).date() ```',204'DTZ012': 'Replace `datetime.date.fromtimestamp()` with `datetime.datetime.fromtimestamp()` to ensure the datetime object is timezone-aware. [Before] ```python import datetime datetime.date.fromtimestamp(946684800) ``` [After] ```python import datetime datetime.datetime.fromtimestamp(946684800, tz=datetime.timezone.utc) ```',205'DTZ901': 'Replace `datetime.max` and `datetime.min` with timezone-aware versions to avoid unexpected behavior. [Before] ```python import datetime # Example usage max_time = datetime.datetime.max min_time = datetime.datetime.min ``` [After] ```python import datetime # Example usage max_time = datetime.datetime.max.replace(tzinfo=datetime.UTC) min_time = datetime.datetime.min.replace(tzinfo=datetime.UTC) ```',206'T100': 'Remove the `breakpoint()` call to prevent unintended behavior in production code. [Before] ```python def foo(): breakpoint() ``` [After] ```python import logging def foo(): logging.debug("Function foo called") ```',207'DJ001': 'Change nullable string fields to use an empty string as the default value instead of allowing `None`. [Before] ```python from django.db import models class MyModel(models.Model): field = models.CharField(max_length=255, null=True) ``` [After] ```python from django.db import models class MyModel(models.Model): field = models.CharField(max_length=255, default="") ```',208'DJ003': 'Replace the use of `locals()` with an explicit context dictionary to avoid exposing unintended variables. [Before] ```python from django.shortcuts import render def index(request): posts = Post.objects.all() return render(request, "app/index.html", locals()) ``` [After] ```python from django.shortcuts import render def index(request): posts = Post.objects.all() context = {"posts": posts} return render(request, "app/index.html", context) ```',209'DJ006': 'Replace the `exclude` attribute with a specific `fields` list to prevent unintended exposure of new model fields. [Before] ```python from django.forms import ModelForm class PostForm(ModelForm): class Meta: model = Post exclude = ["author"] ``` [After] ```python from django.forms import ModelForm class PostForm(ModelForm): class Meta: model = Post fields = ["title", "content"] ```',210'DJ007': 'Replace `fields = "__all__"` with an explicit list of fields to avoid exposing unintended fields in the `ModelForm`. [Before] ```python from django.forms import ModelForm class PostForm(ModelForm): class Meta: model = Post fields = "__all__" ``` [After] ```python from django.forms import ModelForm class PostForm(ModelForm): class Meta: model = Post fields = ["title", "content"] ```',211'DJ008': 'Add a `__str__` method to the Django model to provide a meaningful string representation. [Before] ```python from django.db import models class MyModel(models.Model): field = models.CharField(max_length=255) ``` [After] ```python from django.db import models class MyModel(models.Model): field = models.CharField(max_length=255) def __str__(self): return f"{self.field}" ```',212'DJ012': 'Reorder the class attributes and methods in accordance with the Django Style Guide. [Before] ```python from django.db import models class StrBeforeFieldModel(models.Model): class Meta: verbose_name = "test" verbose_name_plural = "tests" def __str__(self): return "foobar" first_name = models.CharField(max_length=32) last_name = models.CharField(max_length=40) ``` [After] ```python from django.db import models class StrBeforeFieldModel(models.Model): first_name = models.CharField(max_length=32) last_name = models.CharField(max_length=40) class Meta: verbose_name = "test" verbose_name_plural = "tests" def __str__(self): return "foobar" ```',213'DJ013': 'The `@receiver` decorator should be placed before any other decorators to ensure the function is properly connected to the signal. [Before] ```python from django.dispatch import receiver from django.db.models.signals import post_save @transaction.atomic @receiver(post_save, sender=MyModel) def my_handler(sender, instance, created, **kwargs): pass ``` [After] ```python from django.dispatch import receiver from django.db.models.signals import post_save @receiver(post_save, sender=MyModel) @transaction.atomic def my_handler(sender, instance, created, **kwargs): pass ```',214'EM101': 'Use a variable for the error message instead of a string literal in the exception constructor to avoid duplication in the traceback. [Before] ```python raise RuntimeError("\'Some value\' is incorrect") ``` [After] ```python msg = "\'Some value\' is incorrect" raise RuntimeError(msg) ```',215'EM102': 'Use a variable to store the error message instead of using an f-string directly in the exception constructor. [Before] ```python sub = "Some value" raise RuntimeError(f"{sub!r} is incorrect") ``` [After] ```python sub = "Some value" msg = f"{sub!r} is incorrect" raise RuntimeError(msg) ```',216'EM103': 'Use a variable to store the error message instead of formatting it directly in the `raise` statement to avoid duplication in the traceback. [Before] ```python sub = "Some value" raise RuntimeError("\'{}\' is incorrect".format(sub)) ``` [After] ```python sub = "Some value" msg = "\'{}\' is incorrect".format(sub) raise RuntimeError(msg) ```',217'EXE001': 'Ensure that files with a shebang are executable or remove the shebang if not needed. [Before] ```python #!/usr/bin/env python # This script does something ``` [After] ```bash chmod +x script.py # Make the script executable # or # Remove the shebang if the script is not intended to be executable # (remove the line: #!/usr/bin/env python) ```',218'EXE002': 'Add a shebang to executable `.py` files or remove the executable bit if not needed. [Before] ```bash # Check for executable .py files without a shebang find . -name "*.py" -executable ! -exec grep -q \'^#!\' {} \\; -print ``` [After] ```bash # Check for executable .py files without a shebang and suggest fixes find . -name "*.py" -executable ! -exec grep -q \'^#!\' {} \\; -exec echo "Add shebang to: {}" \\; -print ``` This modification suggests adding a shebang to the identified files, improving clarity on the necessary action.',219'EXE003': 'Change the shebang line to specify the Python interpreter. [Before] ```python #!/usr/bin/env bash ``` [After] ```python #!/usr/bin/env python3 ``` This change ensures that the script is executed with the Python interpreter, preventing potential execution errors.',220'EXE004': 'Remove the leading whitespace before the shebang directive to ensure it is recognized correctly. [Before] ```python #!/usr/bin/env python3 ``` [After] ```python #!/usr/bin/env python3 ```',221'EXE005': 'Move the shebang line to the very top of the file to ensure it is recognized by the interpreter. [Before] ```python foo = 1 #!/usr/bin/env python3 ``` [After] ```python #!/usr/bin/env python3 foo = 1 ```',222'FIX001': 'Replace the "FIXME" comment with proper error handling to avoid potential runtime errors. [Before] ```python def speed(distance, time): return distance / time # FIXME: Raises ZeroDivisionError for time = 0. ``` [After] ```python def speed(distance, time): if time == 0: raise ValueError("Time cannot be zero.") return distance / time ```',223'FIX002': 'Remove the "TODO" comment and implement the feature if necessary. [Before] ```python def greet(name): return f"Hello, {name}!" # TODO: Add support for custom greetings. ``` [After] ```python def greet(name, custom_greeting=None): if custom_greeting: return f"{custom_greeting}, {name}!" return f"Hello, {name}!" ```',224'FIX003': 'Replace the "XXX" comment with a more descriptive "TODO" comment and handle the potential ZeroDivisionError. [Before] ```python def speed(distance, time): return distance / time # XXX: Raises ZeroDivisionError for time = 0. ``` [After] ```python def speed(distance, time): if time == 0: raise ValueError("Time cannot be zero.") # TODO: Handle division by zero. return distance / time ```',225'FIX004': 'Remove the "HACK" comment and address the underlying issue by using the `platform` module to check the operating system. [Before] ```python import os def running_windows(): # HACK: Use platform module instead. try: os.mkdir("C:\\\\Windows\\\\System32\\\\\") except FileExistsError: return True else: os.rmdir("C:\\\\Windows\\\\System32\\\\\") return False ``` [After] ```python import os import platform def running_windows(): if platform.system() == "Windows": try: os.mkdir("C:\\\\Windows\\\\System32\\\\\") except FileExistsError: return True else: os.rmdir("C:\\\\Windows\\\\System32\\\\\") return False return False ```',226'FA100': 'Add `from __future__ import annotations` to enable modern type annotations in older Python versions. [Before] ```python from typing import List, Dict, Optional def func(obj: Dict[str, Optional[int]]) -> None: ... ``` [After] ```python from __future__ import annotations from typing import List, Dict, Optional def func(obj: Dict[str, Optional[int]]) -> None: ... ```',227'FA102': 'Add `from __future__ import annotations` to ensure compatibility with older Python versions when using PEP 585 and PEP 604-style type annotations. [Before] ```python def func(obj: dict[str, int | None]) -> None: ... ``` [After] ```python from __future__ import annotations def func(obj: dict[str, int | None]) -> None: ... ```',228'INT001': 'Replace f-string usage in `gettext` calls with string formatting to ensure correct translation lookup. [Before] ```python from gettext import gettext as _ name = "Maria" _(f"Hello, {name}!") # Looks for "Hello, Maria!". ``` [After] ```python from gettext import gettext as _ name = "Maria" _("Hello, %s!") % name # Looks for "Hello, %s!". ```',229'INT002': 'Use the `gettext` function correctly by formatting the string after the translation lookup. [Before] ```python from gettext import gettext as _ name = "Maria" _("Hello, %s!" % name) # Looks for "Hello, Maria!". ``` [After] ```python from gettext import gettext as _ name = "Maria" _("Hello, %s!") % name # Looks for "Hello, %s!". ```',230'INT003': 'Use the correct formatting method for `gettext` to avoid unexpected behavior. [Before] ```python from gettext import gettext as _ name = "Maria" _("Hello, {}!".format(name)) # Looks for "Hello, Maria!". ``` [After] ```python from gettext import gettext as _ name = "Maria" _("Hello, %s!") % name # Looks for "Hello, %s!". ```',231'ISC001': 'Replace implicitly concatenated strings with a single string for improved readability. [Before] ```python z = "The quick " "brown fox." ``` [After] ```python z = "The quick brown fox." ```',232'ISC002': 'Replace backslash for line continuation with parentheses for better readability. [Before] ```python z = "The quick brown fox jumps over the lazy "\\ "dog." ``` [After] ```python z = ( "The quick brown fox jumps over the lazy " "dog." ) ```',233'ISC003': 'Replace explicit string concatenation with implicit concatenation for better readability. [Before] ```python z = ( "The quick brown fox jumps over the lazy " + "dog" ) ``` [After] ```python z = ( "The quick brown fox jumps over the lazy " "dog" ) ```',234'ICN001': 'Change the import statement to use the common alias for pandas. [Before] ```python import pandas ``` [After] ```python import pandas as pd ``` This change ensures that the pandas library is imported using the widely accepted alias `pd`, improving code readability and consistency.',235'ICN002': 'Replace non-standard import alias with a more consistent naming convention. [Before] ```python import tensorflow.keras.backend as K ``` [After] ```python import tensorflow as tf tf.keras.backend ```',236'ICN003': 'Change direct member imports to module imports for consistency and readability. [Before] ```python from pandas import Series ``` [After] ```python import pandas as pd pd.Series ```',237'LOG001': 'Replace direct instantiation of `logging.Logger` with `logging.getLogger()` to ensure proper logger configuration and hierarchy. [Before] ```python import logging logger = logging.Logger(__name__) ``` [After] ```python import logging logger = logging.getLogger(__name__) ```',238'LOG002': 'Replace the usage of `__file__` with `__name__` when calling `logging.getLogger()` to follow best practices. [Before] ```python import logging logger = logging.getLogger(__file__) ``` [After] ```python import logging logger = logging.getLogger(__name__) ```',239'LOG004': 'Replace `logging.exception()` with `logging.error()` to avoid logging without an active exception context. [Before] ```python import logging logging.exception("Foobar") ``` [After] ```python import logging logging.error("Foobar") ```',240'LOG007': 'Replace `logging.exception()` with `logging.error()` to improve clarity and intent when not capturing exception information. [Before] ```python logging.exception("An error occurred", exc_info=False) ``` [After] ```python logging.error("An error occurred") ```',241'LOG009': 'Replace `logging.WARN` with `logging.WARNING` for clarity and to adhere to best practices. [Before] ```python import logging logging.basicConfig(level=logging.WARN) ``` [After] ```python import logging logging.basicConfig(level=logging.WARNING) ```',242'LOG014': 'Remove `exc_info=True` from logging calls outside of exception handlers to prevent attaching `None` as exception information. [Before] ```python import logging logging.warning("Foobar", exc_info=True) ``` [After] ```python import logging logging.warning("Foobar") ```',243'LOG015': 'Replace the use of the root logger with a named logger to include source information in log messages. [Before] ```python import logging logging.info("Foobar") ``` [After] ```python import logging logger = logging.getLogger(__name__) logger.info("Foobar") ```',244'G001': 'Replace `str.format` with the `extra` keyword argument or positional arguments for logging messages. [Before] ```python import logging logging.basicConfig(format="%(message)s", level=logging.INFO) user = "Maria" logging.info("{} - Something happened".format(user)) ``` [After] ```python import logging logging.basicConfig(format="%(user_id)s - %(message)s", level=logging.INFO) user = "Maria" logging.info("Something happened", extra={"user_id": user}) ``` Or: ```python import logging logging.basicConfig(format="%(message)s", level=logging.INFO) user = "Maria" logging.info("%s - Something happened", user) ```',245'G002': 'Replace `printf`-style formatting in logging with the `extra` keyword argument or positional arguments to defer string formatting. [Before] ```python import logging logging.basicConfig(format="%(message)s", level=logging.INFO) user = "Maria" logging.info("%s - Something happened" % user) ``` [After] ```python import logging logging.basicConfig(format="%(user_id)s - %(message)s", level=logging.INFO) user = "Maria" logging.info("Something happened", extra=dict(user_id=user)) ```',246'G003': 'Replace string concatenation in logging with the `extra` keyword argument or formatted string arguments to defer message formatting. [Before] ```python import logging logging.basicConfig(format="%(message)s", level=logging.INFO) user = "Maria" logging.info(user + " - Something happened") ``` [After] ```python import logging logging.basicConfig(format="%(user_id)s - %(message)s", level=logging.INFO) user = "Maria" logging.info("Something happened", extra=dict(user_id=user)) ``` Or: ```python import logging logging.basicConfig(format="%(message)s", level=logging.INFO) user = "Maria" logging.info("%s - Something happened", user) ```',247'G004': 'Replace f-string logging with the `extra` keyword argument or positional arguments to defer string formatting. [Before] ```python import logging logging.basicConfig(format="%(message)s", level=logging.INFO) user = "Maria" logging.info(f"{user} - Something happened") ``` [After] ```python import logging logging.basicConfig(format="%(user_id)s - %(message)s", level=logging.INFO) user = "Maria" logging.info("Something happened", extra=dict(user_id=user)) ```',248'G010': 'Replace deprecated `logging.warn` with `logging.warning` for better compatibility and adherence to best practices. [Before] ```python import logging logging.warn("Something happened") ``` [After] ```python import logging logging.warning("Something happened") ```',249'G101': 'Change the `extra` dictionary keys to match the defined LogRecord attributes to avoid `KeyError`. [Before] ```python import logging logging.basicConfig(format="%(name) - %(message)s", level=logging.INFO) username = "Maria" logging.info("Something happened", extra=dict(name=username)) ``` [After] ```python import logging logging.basicConfig(format="%(user_id)s - %(message)s", level=logging.INFO) username = "Maria" logging.info("Something happened", extra=dict(user_id=username)) ```',250'G201': 'Replace `logging.error` with `logging.exception` when logging exceptions to improve readability and intent clarity. [Before] ```python import logging try: ... except ValueError: logging.error("Exception occurred", exc_info=True) ``` [After] ```python import logging try: ... except ValueError: logging.exception("Exception occurred") ```',251'G202': 'Remove redundant `exc_info=True` from `logging.exception` calls. [Before] ```python import logging try: ... except ValueError: logging.exception("Exception occurred", exc_info=True) ``` [After] ```python import logging try: ... except ValueError: logging.exception("Exception occurred") ```',252'INP001': 'Add an `__init__.py` file to directories intended to be regular Python packages. [Before] [python] # Directory structure without __init__.py my_package/ sub_package/ module.py [After] [python] # Directory structure with __init__.py my_package/ sub_package/ __init__.py module.py Adding the `__init__.py` file ensures that the directory is recognized as a regular Python package, allowing for proper imports.',253'PIE790': 'Remove unnecessary `pass` or ellipsis (`...`) statements from functions that contain other statements. [Before] ```python def func(): """Placeholder docstring.""" pass ``` [After] ```python def func(): """Placeholder docstring.""" ```',254'PIE794': 'Remove the duplicate field definition to avoid redundancy. [Before] ```python class Person: name = Tom ... name = Ben ``` [After] ```python class Person: name = Tom ... ```',255'PIE796': 'Change the duplicate enum value to ensure all values are unique. [Before] ```python from enum import Enum class Foo(Enum): A = 1 B = 2 C = 1 ``` [After] ```python from enum import Enum class Foo(Enum): A = 1 B = 2 C = 3 ```',256'PIE800': 'Remove unnecessary dictionary unpacking for improved readability. [Before] ```python foo = {"A": 1, "B": 2} bar = {**foo, **{"C": 3}} ``` [After] ```python foo = {"A": 1, "B": 2} bar = {**foo, "C": 3} ```',257'PIE804': 'Avoid using `dict` unpacking for keyword arguments when valid identifiers are available. [Before] ```python def foo(bar): return bar + 1 print(foo(**{"bar": 2})) # prints 3 ``` [After] ```python def foo(bar): return bar + 1 print(foo(bar=2)) # prints 3 ```',258'PIE807': 'Replace the lambda function with the built-in `list` for the default factory in the dataclass. [Before] ```python from dataclasses import dataclass, field @dataclass class Foo: bar: list[int] = field(default_factory=lambda: []) ``` [After] ```python from dataclasses import dataclass, field @dataclass class Foo: bar: list[int] = field(default_factory=list) ```',259'PIE808': 'Remove unnecessary `start` argument in `range` calls. [Before] ```python range(0, 3) ``` [After] ```python range(3) ```',260'PIE810': 'Combine multiple `startswith` calls into a single call with a tuple for better efficiency and readability. [Before] ```python msg = "Hello, world!" if msg.startswith("Hello") or msg.startswith("Hi"): print("Greetings!") ``` [After] ```python msg = "Hello, world!" if msg.startswith(("Hello", "Hi")): print("Greetings!") ```',261'T201': 'Remove `print` statements from production code to prevent potential information leaks and use logging instead. [Before] ```python def add_numbers(a, b): print(f"The sum of {a} and {b} is {a + b}") return a + b ``` [After] ```python import logging def add_numbers(a, b): logging.debug(f"The sum of {a} and {b} is {a + b}") return a + b ```',262'T203': 'Remove `pprint` statements to avoid potential exposure of sensitive information in production code. [Before] ```python import pprint def merge_dicts(dict_a, dict_b): dict_c = {**dict_a, **dict_b} pprint.pprint(dict_c) return dict_c ``` [After] ```python def merge_dicts(dict_a, dict_b): dict_c = {**dict_a, **dict_b} return dict_c ```',263'PYI001': 'Type variables should be prefixed with an underscore to avoid accidental exposure. [Before] [python] ```pyi from typing import TypeVar T = TypeVar("T") ``` [After] [python] ```pyi from typing import TypeVar _T = TypeVar("_T") ```',264'PYI002': 'Replace complex conditional checks with simple ones for better type checker compatibility. [Before] ```pyi import sys if (3, 10) <= sys.version_info < (3, 12): ... ``` [After] ```pyi import sys if sys.version_info >= (3, 10) and sys.version_info < (3, 12): ... ```',265'PYI003': 'Change the comparison of `sys.version_info` from a string to an integer to avoid unexpected behavior. [Before] ```pyi import sys if sys.version_info[0] == "2": ... ``` [After] ```pyi import sys if sys.version_info[0] == 2: ... ```',266'PYI004': 'Replace patch version checks with major and minor version checks for compatibility with type checkers. [Before] ```pyi import sys if sys.version_info >= (3, 4, 3): ... ``` [After] ```pyi import sys if sys.version_info >= (3, 4): ... ```',267'PYI005': 'Correct the tuple length in the version comparison to ensure accurate checks against `sys.version_info`. [Before] ```pyi import sys if sys.version_info[:2] == (3,): ... ``` [After] ```pyi import sys if sys.version_info[0] == 3: ... ```',268'PYI006': 'Replace the use of `>` with `>=` for proper version comparison. [Before] ```python import sys if sys.version_info > (3, 8): ... ``` [After] ```python import sys if sys.version_info >= (3, 9): ... ``` This change ensures that the comparison correctly includes version 3.8 and avoids unexpected behavior.',269'PYI007': 'Replace complex `sys.platform` checks with simple string comparisons for better type checker compatibility. [Before] [python] ```pyi if sys.platform.startswith("linux"): # Linux specific definitions ... else: # Posix specific definitions ... ``` [After] [python] ```pyi if sys.platform == "linux": # Linux specific definitions ... else: # Posix specific definitions ... ```',270'PYI008': 'Correct the typo in the platform name comparison. [Before] [python] ```pyi if sys.platform == "linus": ... ``` [After] [python] ```pyi if sys.platform == "linux": ... ```',271'PYI009': 'Replace `pass` statements in stub bodies with `...` for stylistic consistency. [Before] ```pyi def foo(bar: int) -> list[int]: pass ``` [After] ```pyi def foo(bar: int) -> list[int]: ... ```',272'PYI010': 'Replace the function body with an ellipsis (`...`) to indicate a stub. [Before] [python] ```pyi def double(x: int) -> int: return x * 2 ``` [After] [python] ```pyi def double(x: int) -> int: ... ```',273'PYI011': 'Replace complex default values in stub files with `...` to comply with best practices. [Before] [python] ```pyi def foo(arg: list[int] = list(range(10_000))) -> None: ... ``` [After] [python] ```pyi def foo(arg: list[int] = ...) -> None: ... ```',274'PYI012': 'Remove the unnecessary `pass` statement from non-empty class bodies in `.pyi` files. [Before] [python] ```pyi class MyClass: x: int pass ``` [After] [python] ```pyi class MyClass: x: int ```',275'PYI013': 'Remove the ellipsis from non-empty class bodies. [Before] [python] class Foo: ... value: int ``` [After] [python] class Foo: value: int ```',276'PYI014': 'Replace complex default values in stub files with `...` to comply with type hinting best practices. [Before] [python] ```pyi def foo(arg=[]) -> None: ... ``` [After] [python] ```pyi def foo(arg=...) -> None: ... ```',277'PYI015': 'Replace complex default values in stub files with `...` to indicate non-simple assignments. [Before] ```pyi foo: str = "..." ``` [After] ```pyi foo: str = ... ```',278'PYI016': 'Remove duplicate types from union declarations. [Before] ```python foo: str | str ``` [After] ```python foo: str ```',279'PYI017': 'Replace multi-assignment and non-name target assignments in stub files with individual assignments to maintain clarity and adherence to best practices. [Before] [python] ```pyi from typing import TypeAlias a = b = int class Klass: ... Klass.X: TypeAlias = int ``` [After] [python] ```pyi from typing import TypeAlias a: TypeAlias = int b: TypeAlias = int class Klass: X: TypeAlias = int ```',280'PYI018': 'Remove unused private `TypeVar`, `ParamSpec`, or `TypeVarTuple` declarations to avoid confusion. [Before] ```pyi import typing import typing_extensions _T = typing.TypeVar("_T") _Ts = typing_extensions.TypeVarTuple("_Ts") ``` [After] ```pyi # Removed unused private TypeVar and TypeVarTuple ``` This fix eliminates the unused declarations, ensuring cleaner and more maintainable code.',281'PYI019': 'Replace custom `TypeVar` with `Self` for better readability and compliance with PEP 673. [Before] [python] from typing import TypeVar _S = TypeVar("_S", bound="Foo") class Foo: def __new__(cls: type[_S], *args: str, **kwargs: int) -> _S: ... def foo(self: _S, arg: bytes) -> _S: ... @classmethod def bar(cls: type[_S], arg: int) -> _S: ... [/python] [After] [python] from typing import Self class Foo: def __new__(cls, *args: str, **kwargs: int) -> Self: ... def foo(self, arg: bytes) -> Self: ... @classmethod def bar(cls, arg: int) -> Self: ... [/python]',282'PYI020': 'Remove quotes from type annotations in stub files. [Before] [python] ```pyi def function() -> "int": ... ``` [After] [python] ```pyi def function() -> int: ... ```',283'PYI021': 'Remove the docstring from the stub file to adhere to best practices. [Before] ```pyi def func(param: int) -> str: """This is a docstring.""" ... ``` [After] ```pyi def func(param: int) -> str: ... ```',284'PYI024': 'Replace `collections.namedtuple` with `typing.NamedTuple` for better type annotations. [Before] [python] ```pyi from collections import namedtuple person = namedtuple("Person", ["name", "age"]) ``` [After] [python] ```pyi from typing import NamedTuple class Person(NamedTuple): name: str age: int ```',285'PYI025': 'Alias `Set` to `AbstractSet` when importing from `collections.abc` to avoid confusion with the built-in `set`. [Before] [python] ```pyi from collections.abc import Set ``` [After] [python] ```pyi from collections.abc import Set as AbstractSet ```',286'PYI026': 'Add `TypeAlias` annotation to clarify that the variable is a type alias. [Before] [python] ```pyi Vector = list[float] ``` [After] [python] ```pyi from typing import TypeAlias Vector: TypeAlias = list[float] ```',287'PYI029': 'Remove the redundant `__repr__` method definition in the stub class. [Before] ```pyi class Foo: def __repr__(self) -> str: ... ``` [After] ```pyi class Foo: pass ``` This change eliminates the unnecessary definition of `__repr__`, as the default implementation from `object` suffices.',288'PYI030': 'Combine multiple `Literal` types into a single `Literal` for clarity and conciseness. [Before] ```pyi from typing import Literal field: Literal[1] | Literal[2] | str ``` [After] ```pyi from typing import Literal field: Literal[1, 2] | str ```',289'PYI032': 'Change the type annotation of the second parameter in `__eq__` from `typing.Any` to `object` for better type safety. [Before] [python] ```pyi class Foo: def __eq__(self, obj: typing.Any) -> bool: ... ``` [After] [python] ```pyi class Foo: def __eq__(self, obj: object) -> bool: ... ```',290'PYI033': 'Replace type comments with type annotations in stub files. [Before] [python] ```pyi x = 1 # type: int ``` [After] [python] ```pyi x: int = 1 ```',291'PYI034': 'Change fixed return types to `Self` for better type inference in subclasses. [Before] [python] class Foo: def __new__(cls, *args: Any, **kwargs: Any) -> Foo: ... def __enter__(self) -> Foo: ... async def __aenter__(self) -> Foo: ... def __iadd__(self, other: Foo) -> Foo: ... [After] [python] from typing_extensions import Self class Foo: def __new__(cls, *args: Any, **kwargs: Any) -> Self: ... def __enter__(self) -> Self: ... async def __aenter__(self) -> Self: ... def __iadd__(self, other: Foo) -> Self: ...',292'PYI035': 'Assign values to special variables like `__all__`, `__match_args__`, and `__slots__` in stub files to maintain consistency with their runtime counterparts. [Before] [python] ```pyi __all__: list[str] ``` [After] [python] ```pyi __all__: list[str] = ["foo", "bar"] ```',293'PYI036': 'The `__exit__` method should accept `None` as a valid type for its parameters to align with the expected signature. [Before] [python] ```pyi from types import TracebackType class Foo: def __exit__( self, typ: BaseException, exc: BaseException, tb: TracebackType ) -> None: ... ``` [After] [python] ```pyi from types import TracebackType class Foo: def __exit__( self, typ: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None, ) -> None: ... ```',294'PYI041': 'Remove redundant unions of numeric types in parameter annotations. [Before] ```pyi def foo(x: float | int | str) -> None: ... ``` [After] ```pyi def foo(x: float | str) -> None: ... ```',295'PYI042': 'Change the type alias name to follow the CamelCase naming convention. [Before] [python] ```pyi type_alias_name: TypeAlias = int ``` [After] [python] ```pyi TypeAliasName: TypeAlias = int ```',296'PYI043': 'Remove the \'T\' suffix from the type alias to avoid confusion with type variables. [Before] [python] ```pyi from typing import TypeAlias _MyTypeT: TypeAlias = int ``` [After] [python] ```pyi from typing import TypeAlias _MyType: TypeAlias = int ```',297'PYI044': 'Remove the unnecessary `from __future__ import annotations` statement from stub files. [Before] ```python from __future__ import annotations class Example: def method(self, param: \'Example\') -> None: pass ``` [After] ```python class Example: def method(self, param: \'Example\') -> None: pass ``` This fix eliminates the import statement, as it is not needed in stub files where forward references are natively supported.',298'PYI045': 'Change the return type of the `__iter__` method from `Iterable` to `Iterator` to comply with best practices. [Before] ```python import collections.abc class Klass: def __iter__(self) -> collections.abc.Iterable[str]: ... ``` [After] ```python import collections.abc class Klass: def __iter__(self) -> collections.abc.Iterator[str]: ... ```',299'PYI046': 'The private `typing.Protocol` should be utilized in a function to avoid being flagged as unused. [Before] [python] ```pyi import typing class _PrivateProtocol(typing.Protocol): foo: int ``` [After] [python] ```pyi import typing class _PrivateProtocol(typing.Protocol): foo: int def func(arg: _PrivateProtocol) -> None: ... ```',300'PYI047': 'Remove the unused private type alias to prevent confusion. [Before] [python] ```pyi import typing _UnusedTypeAlias: typing.TypeAlias = int ``` [After] [python] ```pyi import typing # Removed unused type alias ```',301'PYI048': 'Replace the function body with a single ellipsis (`...`) to comply with stub file conventions. [Before] [python] ```pyi def function(): x = 1 y = 2 return x + y ``` [After] [python] ```pyi def function(): ... ```',302'PYI049': 'Remove the unused private `TypedDict` definition to avoid confusion. [Before] [python] ```pyi import typing class _UnusedPrivateTypedDict(typing.TypedDict): foo: list[int] ``` [After] [python] ```pyi import typing # Removed unused private TypedDict ```',303'PYI050': 'Replace `NoReturn` with `Never` for parameter annotations to improve clarity. [Before] [python] ```pyi from typing import NoReturn def foo(x: NoReturn): ... ``` [After] [python] ```pyi from typing import Never def foo(x: Never): ... ```',304'PYI051': 'Remove the redundant `Literal` type that is a subtype of the union\'s supertype. [Before] ```pyi from typing import Literal x: Literal["A", b"B"] | str ``` [After] ```pyi from typing import Literal x: Literal[b"B"] | str ```',305'PYI052': 'Ensure all assignments in stub files are annotated with a type. [Before] ```python # example.pyi x = 5 y = "hello" ``` [After] ```python # example.pyi x: int = 5 y: str = "hello" ```',306'PYI053': 'Replace long string literals in stub files with ellipses (`...`) to adhere to best practices. [Before] [python] ```pyi def foo(arg: str = "51 character stringgggggggggggggggggggggggggggggggg") -> None: ... ``` [After] [python] ```pyi def foo(arg: str = ...) -> None: ... ```',307'PYI054': 'Replace the long numeric literal default value with ellipses (`...`) to adhere to best practices for function stubs. [Before] [python] ```pyi def foo(arg: int = 693568516352839939918568862861217771399698285293568) -> None: ... ``` [After] [python] ```pyi def foo(arg: int = ...) -> None: ... ```',308'PYI055': 'Replace multiple `type`s in a union with a single `type` wrapping a combined union for clarity and conciseness. [Before] [python] field: type[int] | type[float] | str ``` [After] [python] field: type[int | float] | str ```',309'PYI056': 'Replace `append` and `remove` calls on `__all__` with the `+=` operator for better compatibility with type checkers. [Before] [python] ```pyi import sys __all__ = ["A", "B"] if sys.version_info >= (3, 10): __all__.append("C") if sys.version_info >= (3, 11): __all__.remove("B") ``` [After] [python] ```pyi import sys __all__ = ["A"] if sys.version_info < (3, 11): __all__ += ["B"] if sys.version_info >= (3, 10): __all__ += ["C"] ```',310'PYI057': 'Replace deprecated `typing.ByteString` with `collections.abc.Buffer` for compatibility with future Python versions. [Before] ```python from typing import ByteString ``` [After] ```python from collections.abc import Buffer ```',311'PYI058': 'Change the return type of `__iter__` methods from `Generator` to `Iterator` for better abstraction. [Before] ```python from collections.abc import AsyncGenerator, Generator from typing import Any class CustomIterator: def __iter__(self) -> Generator: yield from range(42) class CustomIterator2: def __iter__(self) -> Generator[str, Any, None]: yield from "abcdefg" ``` [After] ```python from collections.abc import Iterator class CustomIterator: def __iter__(self) -> Iterator: yield from range(42) class CustomIterator2: def __iter__(self) -> Iterator[str]: yield from "abcdefg" ```',312'PYI059': 'Reorder base classes to ensure `Generic[]` is the last class in the bases tuple. [Before] ```python class LinkedList(Generic[T], Sized): def push(self, item: T) -> None: self._items.append(item) class MyMapping( Generic[K, V], Iterable[Tuple[K, V]], Container[Tuple[K, V]], ): ... ``` [After] ```python class LinkedList(Sized, Generic[T]): def push(self, item: T) -> None: self._items.append(item) class MyMapping( Iterable[Tuple[K, V]], Container[Tuple[K, V]], Generic[K, V], ): ... ```',313'PYI061': 'Replace `Literal[None]` with `None` for improved readability. [Before] ```python from typing import Literal Literal[None] Literal[1, 2, 3, "foo", 5, None] ``` [After] ```python from typing import Literal None Literal[1, 2, 3, "foo", 5] | None ```',314'PYI062': 'Remove duplicate members from `typing.Literal[]` to ensure type clarity and conciseness. [Before] ```python foo: Literal["a", "b", "a"] ``` [After] ```python foo: Literal["a", "b"] ```',315'PYI063': 'Replace the old-style positional-only parameter syntax with the new PEP 570 syntax for better readability and compliance with modern Python standards. [Before] [python] ```python def foo(__x: int) -> None: ... ``` [After] [python] ```python def foo(x: int, /) -> None: ... ```',316'PYI064': 'Replace `Final[Literal[...]]` annotations with just `Final` for better readability and conciseness. [Before] [python] ```pyi from typing import Final, Literal x: Final[Literal[42]] y: Final[Literal[42]] = 42 ``` [After] [python] ```pyi from typing import Final x: Final = 42 y: Final = 42 ```',317'PYI066': 'Reorder version checks to prioritize newer Python versions for clarity and maintainability. [Before] [python] ```pyi import sys if sys.version_info < (3, 10): def read_data(x, *, preserve_order=True): ... else: def read_data(x): ... ``` [After] [python] ```pyi import sys if sys.version_info >= (3, 10): def read_data(x): ... else: def read_data(x, *, preserve_order=True): ... ```',318'PT001': 'Remove unnecessary parentheses from the `@pytest.fixture` decorator for consistency. [Before] ```python import pytest @pytest.fixture() def my_fixture(): ... ``` [After] ```python import pytest @pytest.fixture def my_fixture(): ... ```',319'PT002': 'Change the positional argument in the `@pytest.fixture` decorator to a keyword argument for better clarity and consistency. [Before] ```python import pytest @pytest.fixture("module") def my_fixture(): ... ``` [After] ```python import pytest @pytest.fixture(scope="module") def my_fixture(): ... ```',320'PT003': 'Remove the unnecessary `scope="function"` argument from the `@pytest.fixture` decorator since it is the default. [Before] ```python import pytest @pytest.fixture(scope="function") def my_fixture(): ... ``` [After] ```python import pytest @pytest.fixture() def my_fixture(): ... ```',321'PT004': 'Rename fixtures that do not return a value to start with an underscore. [Before] ```python import pytest @pytest.fixture() def patch_something(mocker): mocker.patch("module.object") @pytest.fixture() def use_context(): with create_context(): yield ``` [After] ```python import pytest @pytest.fixture() def _patch_something(mocker): mocker.patch("module.object") @pytest.fixture() def _use_context(): with create_context(): yield ```',322'PT005': 'Remove leading underscores from fixture names to align with pytest conventions. [Before] ```python import pytest @pytest.fixture() def _some_object(): return SomeClass() @pytest.fixture() def _some_object_with_cleanup(): obj = SomeClass() yield obj obj.cleanup() ``` [After] ```python import pytest @pytest.fixture() def some_object(): return SomeClass() @pytest.fixture() def some_object_with_cleanup(): obj = SomeClass() yield obj obj.cleanup() ```',323'PT006': 'Use a string for a single parameter and a tuple for multiple parameters in `pytest.mark.parametrize`. [Before] ```python import pytest # single parameter, always expecting string @pytest.mark.parametrize(("param",), [1, 2, 3]) def test_foo(param): ... # multiple parameters, expecting tuple @pytest.mark.parametrize(["param1", "param2"], [(1, 2), (3, 4)]) def test_bar(param1, param2): ... # multiple parameters, expecting tuple @pytest.mark.parametrize("param1,param2", [(1, 2), (3, 4)]) def test_baz(param1, param2): ... ``` [After] ```python import pytest @pytest.mark.parametrize("param", [1, 2, 3]) def test_foo(param): ... @pytest.mark.parametrize(("param1", "param2"), [(1, 2), (3, 4)]) def test_bar(param1, param2): ... ```',324'PT007': 'Change tuples to lists for parameter values in `pytest.mark.parametrize` to adhere to style guidelines. [Before] ```python import pytest # expected list, got tuple @pytest.mark.parametrize("param", (1, 2)) def test_foo(param): ... # expected top-level list, got tuple @pytest.mark.parametrize( ("param1", "param2"), ( (1, 2), (3, 4), ), ) def test_bar(param1, param2): ... # expected individual rows to be tuples, got lists @pytest.mark.parametrize( ("param1", "param2"), [ [1, 2], [3, 4], ], ) def test_baz(param1, param2): ... ``` [After] ```python import pytest @pytest.mark.parametrize("param", [1, 2]) def test_foo(param): ... @pytest.mark.parametrize(("param1", "param2"), [(1, 2), (3, 4)]) def test_bar(param1, param2): ... @pytest.mark.parametrize( ("param1", "param2"), [(1, 2), (3, 4)], ) def test_baz(param1, param2): ... ```',325'PT008': 'Replace the `lambda` function with `return_value` for clarity and robustness. [Before] ```python def test_foo(mocker): mocker.patch("module.target", lambda x, y: 7) ``` [After] ```python def test_foo(mocker): mocker.patch("module.target", return_value=7) ```',326'PT009': 'Replace `unittest` assertion methods with regular `assert` statements for better compatibility with `pytest`. [Before] ```python import unittest class TestFoo(unittest.TestCase): def test_foo(self): self.assertEqual(a, b) ``` [After] ```python class TestFoo: def test_foo(self): assert a == b ```',327'PT010': 'Add the expected exception type as the first argument to `pytest.raises`. [Before] ```python import pytest def test_foo(): with pytest.raises(): do_something() ``` [After] ```python import pytest def test_foo(): with pytest.raises(SomeException): do_something() ```',328'PT011': 'Add a `match` parameter to `pytest.raises` to ensure that only the expected exception message is caught. [Before] ```python import pytest def test_foo(): with pytest.raises(ValueError): ... # empty string is also an error with pytest.raises(ValueError, match=""): ... ``` [After] ```python import pytest def test_foo(): with pytest.raises(ValueError, match="expected message"): ... ```',329'PT012': 'The `pytest.raises` context manager should only contain a single statement that raises the expected exception to ensure proper test behavior. [Before] ```python import pytest def test_foo(): with pytest.raises(MyError): setup() func_to_test() # not executed if `setup()` raises `MyError` assert foo() # not executed ``` [After] ```python import pytest def test_foo(): setup() with pytest.raises(MyError): func_to_test() assert foo() ```',330'PT013': 'Change the import statement to ensure consistency by importing `pytest` directly. [Before] ```python import pytest as pt from pytest import fixture ``` [After] ```python import pytest ```',331'PT014': 'Remove duplicate test cases in `pytest.mark.parametrize` to avoid redundancy. [Before] ```python import pytest @pytest.mark.parametrize( ("param1", "param2"), [ (1, 2), (1, 2), ], ) def test_foo(param1, param2): ... ``` [After] ```python import pytest @pytest.mark.parametrize( ("param1", "param2"), [ (1, 2), ], ) def test_foo(param1, param2): ... ```',332'PT015': 'Replace `assert` statements with `pytest.fail` for clearer intent. [Before] ```python def test_foo(): if some_condition: assert False, "some_condition was True" ``` [After] ```python import pytest def test_foo(): if some_condition: pytest.fail("some_condition was True") ```',333'PT016': 'Add meaningful messages to `pytest.fail` calls to improve test failure clarity. [Before] ```python import pytest def test_foo(): pytest.fail() def test_bar(): pytest.fail("") def test_baz(): pytest.fail(reason="") ``` [After] ```python import pytest def test_foo(): pytest.fail("Test foo failed due to an unexpected condition.") def test_bar(): pytest.fail(reason="Test bar failed because of an empty response.") ```',334'PT017': 'Replace `assert` statements in `except` clauses with `pytest.raises()` for better exception handling. [Before] ```python def test_foo(): try: 1 / 0 except ZeroDivisionError as e: assert e.args ``` [After] ```python import pytest def test_foo(): with pytest.raises(ZeroDivisionError) as exc_info: 1 / 0 assert exc_info.value.args ```',335'PT018': 'Replace composite assertions with individual assertions for better clarity in failure messages. [Before] ```python def test_foo(): assert something and something_else def test_bar(): assert not (something or something_else) ``` [After] ```python def test_foo(): assert something assert something_else def test_bar(): assert not something assert not something_else ```',336'PT019': 'Replace the fixture parameter in the test function with the `@pytest.mark.usefixtures` decorator to clarify fixture dependencies. [Before] ```python import pytest @pytest.fixture def _patch_something(): ... def test_foo(_patch_something): ... ``` [After] ```python import pytest @pytest.fixture def _patch_something(): ... @pytest.mark.usefixtures("_patch_something") def test_foo(): ... ```',337'PT020': 'Replace `pytest.yield_fixture` with `pytest.fixture` as `yield_fixture` is deprecated. [Before] ```python import pytest @pytest.yield_fixture() def my_fixture(): obj = SomeClass() yield obj obj.cleanup() ``` [After] ```python import pytest @pytest.fixture() def my_fixture(): obj = SomeClass() yield obj obj.cleanup() ```',338'PT021': 'Replace `request.addfinalizer` with a `yield` statement for better readability in the fixture. [Before] ```python import pytest @pytest.fixture() def my_fixture(request): resource = acquire_resource() request.addfinalizer(resource.release) return resource ``` [After] ```python import pytest @pytest.fixture() def my_fixture(): resource = acquire_resource() yield resource resource.release() ```',339'PT022': 'Remove unnecessary `yield` in fixtures that do not require teardown. [Before] ```python import pytest @pytest.fixture() def my_fixture(): resource = acquire_resource() yield resource ``` [After] ```python import pytest @pytest.fixture() def my_fixture_without_teardown(): resource = acquire_resource() return resource ```',340'PT023': 'To ensure consistency in the use of `@pytest.mark.<marker>()`, you should either always use parentheses or remove them when no arguments are present. [Before] ```python import pytest @pytest.mark.foo def test_something(): ... ``` [After] ```python import pytest @pytest.mark.foo() def test_something(): ... ```',341'PT024': 'Remove the unnecessary `@pytest.mark.asyncio` decorator from the fixture. [Before] ```python import pytest @pytest.mark.asyncio() @pytest.fixture() async def my_fixture(): return 0 ``` [After] ```python import pytest @pytest.fixture() async def my_fixture(): return 0 ```',342'PT025': 'Remove the `pytest.mark.usefixtures` decorator from the fixture definition, as it has no effect on pytest fixtures. [Before] ```python import pytest @pytest.fixture() def a(): pass @pytest.mark.usefixtures("a") @pytest.fixture() def b(a): pass ``` [After] ```python import pytest @pytest.fixture() def a(): pass @pytest.fixture() def b(a): pass ```',343'PT026': 'Remove the empty `@pytest.mark.usefixtures()` decorator to clean up the code. [Before] ```python import pytest @pytest.mark.usefixtures() def test_something(): ... ``` [After] ```python def test_something(): ... ```',344'PT027': 'Replace `unittest`\'s `assertRaises` with `pytest`\'s `raises` for better assertion style. [Before] ```python import unittest class TestFoo(unittest.TestCase): def test_foo(self): with self.assertRaises(ValueError): raise ValueError("foo") ``` [After] ```python import pytest class TestFoo: def test_foo(self): with pytest.raises(ValueError): raise ValueError("foo") ```',345'PT028': 'Remove default arguments from test function parameters to ensure they can be overridden by fixtures. [Before] ```python def test_foo(a=1): ... ``` [After] ```python def test_foo(a): ... ```',346'PT029': 'Add an expected warning type as the first argument to `pytest.warns`. [Before] ```python import pytest def test_foo(): with pytest.warns(): do_something() ``` [After] ```python import pytest def test_foo(): with pytest.warns(SomeWarning): do_something() ```',347'PT030': 'Add a `match` parameter to `pytest.warns` calls to ensure that only specific warnings are caught. [Before] ```python import pytest def test_foo(): with pytest.warns(RuntimeWarning): ... # empty string is also an error with pytest.warns(RuntimeWarning, match=""): ... ``` [After] ```python import pytest def test_foo(): with pytest.warns(RuntimeWarning, match="expected message"): ... with pytest.warns(RuntimeWarning, match="expected message"): ... ```',348'PT031': 'Refactor the `pytest.warns` context manager to only contain a single statement that triggers the expected warning. [Before] ```python import pytest def test_foo_warns(): with pytest.warns(Warning): setup() # False negative if setup triggers a warning but foo does not. foo() ``` [After] ```python import pytest def test_foo_warns(): setup() with pytest.warns(Warning): foo() ```',349'Q000': 'Ensure consistent use of double quotes for inline strings based on the `lint.flake8-quotes.inline-quotes` setting. [Before] ```python foo = \'bar\' ``` [After] ```python foo = "bar" ```',350'Q001': 'Ensure consistency in multiline string quotes based on the `lint.flake8-quotes.multiline-quotes` setting. [Before] ```python foo = \'\'\' bar \'\'\' ``` [After] ```python foo = """ bar """ ```',351'Q002': 'Change single quotes to double quotes for consistency in docstrings based on the `lint.flake8-quotes.docstring-quotes` setting. [Before] ```python \'\'\' bar \'\'\' ``` [After] ```python """ bar """ ```',352'Q003': 'Change the outer quotes from single to double to avoid escaping inner quotes. [Before] ```python foo = \'bar\\\'s\' ``` [After] ```python foo = "bar\'s" ```',353'Q004': 'Remove unnecessary escape character from the string. [Before] ```python foo = "bar\\\'s" ``` [After] ```python foo = "bar\'s" ```',354'RSE102': 'Remove unnecessary parentheses from raised exceptions to improve code conciseness. [Before] ```python raise TypeError() ``` [After] ```python raise TypeError ```',355'RET501': 'Remove the explicit `return None` statement to avoid redundancy since Python returns `None` by default. [Before] ```python def foo(bar): if not bar: return return None ``` [After] ```python def foo(bar): if not bar: return return ```',356'RET502': 'Add an explicit `return None` statement to clarify intent when returning from a function that also has other return statements. [Before] ```python def foo(bar): if not bar: return return 1 ``` [After] ```python def foo(bar): if not bar: return None return 1 ```',357'RET503': 'Add an explicit `return None` statement at the end of the function to clarify intent. [Before] ```python def foo(bar): if not bar: return 1 ``` [After] ```python def foo(bar): if not bar: return 1 return None ```',358'RET504': 'Remove unnecessary variable assignment before return. [Before] ```python def foo(): bar = 1 return bar ``` [After] ```python def foo(): return 1 ```',359'RET505': 'Remove unnecessary `else` statement after a `return` to improve readability. [Before] ```python def foo(bar, baz): if bar: return 1 else: return baz ``` [After] ```python def foo(bar, baz): if bar: return 1 return baz ```',360'RET506': 'Remove unnecessary `else` statement after a `raise` to improve readability. [Before] ```python def foo(bar, baz): if bar == "Specific Error": raise Exception(bar) else: raise Exception(baz) ``` [After] ```python def foo(bar, baz): if bar == "Specific Error": raise Exception(bar) raise Exception(baz) ```',361'RET507': 'Remove unnecessary `else` statement after a `continue` in the loop. [Before] ```python def foo(bar, baz): for i in bar: if i < baz: continue else: x = 0 ``` [After] ```python def foo(bar, baz): for i in bar: if i < baz: continue x = 0 ```',362'RET508': 'Remove unnecessary `else` statement after a `break` to improve code readability. [Before] ```python def foo(bar, baz): for i in bar: if i > baz: break else: x = 0 ``` [After] ```python def foo(bar, baz): for i in bar: if i > baz: break x = 0 ```',363'SLF001': 'Change the access of the private member to a public member to adhere to Python\'s conventions. [Before] ```python class Class: def __init__(self): self._private_member = "..." var = Class() print(var._private_member) ``` [After] ```python class Class: def __init__(self): self.public_member = "..." var = Class() print(var.public_member) ```',364'SIM101': 'Replace multiple `isinstance` calls with a single call using a tuple for better readability and conciseness. [Before] ```python if isinstance(obj, int) or isinstance(obj, float): pass ``` [After] ```python if isinstance(obj, (int, float)): pass ```',365'SIM102': 'Combine nested `if` statements into a single `if` statement using the `and` operator for better readability. [Before] ```python if foo: if bar: ... ``` [After] ```python if foo and bar: ... ```',366'SIM103': 'Replace unnecessary `if` statements that return boolean values with direct boolean expressions. [Before] ```python if x > 0: return True else: return False ``` [After] ```python return x > 0 ```',367'SIM105': 'Replace `try`-`except`-`pass` with `contextlib.suppress` for conciseness and clarity. [Before] ```python try: 1 / 0 except ZeroDivisionError: pass ``` [After] ```python import contextlib with contextlib.suppress(ZeroDivisionError): 1 / 0 ```',368'SIM107': 'Replace the `return` statement in the `finally` block to avoid overriding the return value from the `try` or `except` blocks. [Before] ```python def squared(n): try: sqr = n**2 return sqr except Exception: return "An exception occurred" finally: return -1 # Always returns -1. ``` [After] ```python def squared(n): try: return_value = n**2 except Exception: return_value = "An exception occurred" finally: return_value = -1 return return_value ```',369'SIM108': 'Replace `if`-`else` blocks with ternary operators for conciseness. [Before] ```python if foo: bar = x else: bar = y ``` [After] ```python bar = x if foo else y ``` Simplify ternary expressions to binary expressions when applicable. [Before] ```python if cond: z = cond else: z = other_cond ``` [After] ```python z = cond or other_cond ```',370'SIM109': 'Replace multiple equality comparisons with the `in` operator for conciseness. [Before] ```python if foo == x or foo == y: ... ``` [After] ```python if foo in (x, y): ... ```',371'SIM110': 'Replace the `for` loop with the `any` builtin function for improved conciseness and readability. [Before] ```python for item in iterable: if predicate(item): return True return False ``` [After] ```python return any(predicate(item) for item in iterable) ```',372'SIM112': 'Change the environment variable access to use uppercase to follow best practices. [Before] ```python import os os.environ["foo"] ``` [After] ```python import os os.environ["FOO"] ```',373'SIM113': 'Replace the manual index increment with `enumerate()` for better readability and conciseness. [Before] ```python fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(f"{i + 1}. {fruit}") i += 1 ``` [After] ```python fruits = ["apple", "banana", "cherry"] for i, fruit in enumerate(fruits): print(f"{i + 1}. {fruit}") ```',374'SIM114': 'Combine identical `if` branches using `or` for clarity. [Before] ```python if x == 1: print("Hello") elif x == 2: print("Hello") ``` [After] ```python if x == 1 or x == 2: print("Hello") ```',375'SIM115': 'Use a context manager when opening files to ensure they are properly closed. [Before] ```python file = open("foo.txt") ... file.close() ``` [After] ```python with open("foo.txt") as file: ... ```',376'SIM116': 'Replace multiple consecutive if-statements with a dictionary lookup for cleaner code. [Before] ```python if x == 1: return "Hello" elif x == 2: return "Goodbye" else: return "Goodnight" ``` [After] ```python return {1: "Hello", 2: "Goodbye"}.get(x, "Goodnight") ```',377'SIM117': 'Combine nested context managers into a single `with` statement for improved readability. [Before] ```python with A() as a: with B() as b: pass ``` [After] ```python with A() as a, B() as b: pass ```',378'SIM118': 'Replace `key in dict.keys()` with `key in dict` for improved readability and efficiency. [Before] ```python key in foo.keys() ``` [After] ```python key in foo ```',379'SIM201': 'Replace negated `==` with `!=` for better readability. [Before] ```python not a == b ``` [After] ```python a != b ```',380'SIM202': 'Replace negated `!=` operators with `==` for improved readability, while being cautious of potential behavior changes. [Before] ```python not a != b ``` [After] ```python a == b ```',381'SIM208': 'Remove redundant double negation for improved readability. [Before] ```python not (not a) ``` [After] ```python a ```',382'SIM210': 'Replace unnecessary `if` expressions with `bool()` calls for improved conciseness and readability. [Before] ```python if a: result = True else: result = False ``` [After] ```python result = bool(a) ```',383'SIM211': 'Replace the `if` expression with a `not` operator for improved readability. [Before] ```python False if a else True ``` [After] ```python not a ```',384'SIM212': 'Replace the negated condition in the `if` expression for better readability. [Before] ```python b if not a else a ``` [After] ```python a if a else b ```',385'SIM220': 'Remove the negation from the `and` expression to avoid always evaluating to `False`. [Before] ```python x and not x ``` [After] ```python # Simply use x or not x for a valid expression x or not x ```',386'SIM221': 'Remove the redundant expression to avoid always evaluating to `True`. [Before] ```python x or not x ``` [After] ```python # Simply use x x ```',387'SIM222': 'Replace redundant `or` expressions with `True` or the first truthy value for clarity and conciseness. [Before] ```python if x or [1] or y: pass a = x or [1] or y ``` [After] ```python if True: pass a = x or [1] ```',388'SIM223': 'Replace `and` expressions containing falsey values with `False` or the first falsey value for clarity and conciseness. [Before] ```python if x and [] and y: pass a = x and [] and y ``` [After] ```python if False: pass a = x and [] ```',389'SIM300': 'Replace Yoda conditions with standard comparison format for improved readability. [Before] ```python if "Foo" == foo: ... ``` [After] ```python if foo == "Foo": ... ```',390'SIM401': 'Replace `if` statements that check for key existence in a dictionary with `dict.get()` for conciseness. [Before] ```python if "bar" in foo: value = foo["bar"] else: value = 0 ``` [After] ```python value = foo.get("bar", 0) ```',391'SIM905': 'Replace `str.split` calls with list literals for improved readability and performance. [Before] ```python "a,b,c,d".split(",") ``` [After] ```python ["a", "b", "c", "d"] ```',392'SIM910': 'Remove the explicit `None` default value in `dict.get()` calls. [Before] ```python ages = {"Tom": 23, "Maria": 23, "Dog": 11} age = ages.get("Cat", None) ``` [After] ```python ages = {"Tom": 23, "Maria": 23, "Dog": 11} age = ages.get("Cat") ```',393'SIM911': 'Replace the use of `zip()` with the `items()` method for better readability and performance. [Before] ```python flag_stars = {"USA": 50, "Slovenia": 3, "Panama": 2, "Australia": 6} for country, stars in zip(flag_stars.keys(), flag_stars.values()): print(f"{country}\'s flag has {stars} stars.") ``` [After] ```python flag_stars = {"USA": 50, "Slovenia": 3, "Panama": 2, "Australia": 6} for country, stars in flag_stars.items(): print(f"{country}\'s flag has {stars} stars.") ```',394'SLOT000': 'Add `__slots__` to subclasses of `str` to optimize memory usage. [Before] ```python class Foo(str): pass ``` [After] ```python class Foo(str): __slots__ = () ```',395'SLOT001': 'Add `__slots__` to subclasses of `tuple` to optimize memory usage. [Before] ```python class Foo(tuple): pass ``` [After] ```python class Foo(tuple): __slots__ = () ```',396'SLOT002': 'Add `__slots__` to the subclass of `namedtuple` to optimize memory usage. [Before] ```python from collections import namedtuple class Foo(namedtuple("foo", ["str", "int"])): pass ``` [After] ```python from collections import namedtuple class Foo(namedtuple("foo", ["str", "int"])): __slots__ = () ```',397'TID251': `The code snippet is missing the implementation details for checking banned imports. [Before] [python] # Example of a function that checks for banned imports def check_imports(imports): banned_imports = ['os', 'sys'] for imp in imports: if imp in banned_imports: print(f"Banned import detected: {imp}") # Sample usage check_imports(['os', 'json', 'sys']) [After] [python] # Improved function to check for banned imports with better structure def check_imports(imports): banned_imports = {'os', 'sys'} # Use a set for faster lookups detected_bans = [imp for imp in imports if imp in banned_imports] for imp in detected_bans: print(f"Banned import detected: {imp}") # Sample usage check_imports(['os', 'json', 'sys'])`,398'TID252': 'Replace relative import with an absolute import for better readability and adherence to PEP 8 guidelines. [Before] ```python from .. import foo ``` [After] ```python from mypkg import foo ```',399'TID253': 'Move the import statement for `tensorflow` inside the function to avoid module-level imports and improve startup time. [Before] ```python import tensorflow as tf def show_version(): print(tf.__version__) ``` [After] ```python def show_version(): import tensorflow as tf print(tf.__version__) ```',400'TD001': 'Change the comment tag from "FIXME" to "TODO" to ensure clarity and consistency in code comments. [Before] ```python # FIXME(ruff): this should get fixed! ``` [After] ```python # TODO(ruff): this is now fixed! ```',401'TD002': 'Ensure that TODO comments include an author for better context. [Before] ```python # TODO: should assign an author here ``` [After] ```python # TODO(charlie): now an author is assigned ```',402'TD003': 'Ensure that TODO comments include a relevant issue link or code for better context. [Before] ```python # TODO: this link has no issue ``` [After] ```python # TODO(charlie): this comment has an issue link # https://github.com/astral-sh/ruff/issues/3870 ```',403'TD004': 'Ensure that "TODO" tags are followed by a colon for consistency. [Before] ```python # TODO(charlie) fix this colon ``` [After] ```python # TODO(charlie): fix this colon ``` This change adds a colon after the author\'s name to adhere to the expected format for "TODO" comments.',404'TD005': 'Ensure that TODO comments include a description for clarity. [Before] ```python # TODO(charlie) ``` [After] ```python # TODO(charlie): fix some issue ```',405'TD006': 'Ensure "TODO" is capitalized in comments for better readability. [Before] ```python # todo(charlie): capitalize this ``` [After] ```python # TODO(charlie): capitalize this ```',406'TD007': 'Add a space after the colon in the TODO comment. [Before] ```python # TODO(charlie):fix this ``` [After] ```python # TODO(charlie): fix this ```',407'TC001': 'Move the import of `local_module` into a conditional `if TYPE_CHECKING:` block to avoid runtime overhead. [Before] ```python from __future__ import annotations import local_module def func(sized: local_module.Container) -> int: return len(sized) ``` [After] ```python from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: import local_module def func(sized: local_module.Container) -> int: return len(sized) ```',408'TC002': 'Move the import of `pandas` into a conditional `if TYPE_CHECKING:` block to avoid runtime overhead. [Before] ```python from __future__ import annotations import pandas as pd def func(df: pd.DataFrame) -> int: return len(df) ``` [After] ```python from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: import pandas as pd def func(df: pd.DataFrame) -> int: return len(df) ```',409'TC003': 'Move the import of `Path` into a conditional `if TYPE_CHECKING:` block to avoid unnecessary runtime overhead. [Before] ```python from __future__ import annotations from pathlib import Path def func(path: Path) -> str: return str(path) ``` [After] ```python from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from pathlib import Path def func(path: Path) -> str: return str(path) ```',410'TC004': 'Move the import statement outside the type-checking block to ensure the symbol is available at runtime. [Before] ```python from typing import TYPE_CHECKING if TYPE_CHECKING: import foo def bar() -> None: foo.bar() # raises NameError: name \'foo\' is not defined ``` [After] ```python import foo def bar() -> None: foo.bar() ```',411'TC005': 'Remove the empty type-checking block to avoid confusion. [Before] ```python from typing import TYPE_CHECKING if TYPE_CHECKING: pass print("Hello, world!") ``` [After] ```python print("Hello, world!") ```',412'TC006': 'Ensure type expressions in `typing.cast()` are quoted for consistency. [Before] ```python from typing import cast x = cast(dict[str, int], foo) ``` [After] ```python from typing import cast x = cast("dict[str, int]", foo) ```',413'TC007': 'Change the type alias definition to use a string to avoid runtime `NameError`. [Before] ```python from typing import TYPE_CHECKING, TypeAlias if TYPE_CHECKING: from foo import Foo OptFoo: TypeAlias = Foo | None ``` [After] ```python from typing import TYPE_CHECKING, TypeAlias if TYPE_CHECKING: from foo import Foo OptFoo: TypeAlias = "Foo | None" ```',414'TC008': 'Remove unnecessary quotes from type aliases to improve runtime efficiency. [Before] ```python OptInt: TypeAlias = "int | None" ``` [After] ```python OptInt: TypeAlias = int | None ``` [Before] ```python type OptInt = "int | None" ``` [After] ```python type OptInt = int | None ```',415'TC010': 'Remove quotes from the union type to avoid runtime errors. [Before] ```python var: str | "int" ``` [After] ```python var: str | int ```',416'ARG001': 'Remove unused argument `baz` from the function definition to avoid confusion. [Before] ```python def foo(bar, baz): return bar * 2 ``` [After] ```python def foo(bar): return bar * 2 ```',417'ARG002': 'Remove unused arguments from the method definition to improve code clarity. [Before] ```python class Class: def foo(self, arg1, arg2): print(arg1) ``` [After] ```python class Class: def foo(self, arg1): print(arg1) ```',418'ARG003': 'Remove unused argument `arg2` from the method definition to avoid confusion. [Before] ```python class Class: @classmethod def foo(cls, arg1, arg2): print(arg1) ``` [After] ```python class Class: @classmethod def foo(cls, arg1): print(arg1) ```',419'ARG004': 'Remove the unused argument `arg2` from the static method definition to avoid confusion. [Before] ```python class Class: @staticmethod def foo(arg1, arg2): print(arg1) ``` [After] ```python class Class: @staticmethod def foo(arg1): print(arg1) ```',420'ARG005': 'Remove unused arguments from the lambda expression to prevent confusion. [Before] ```python my_list = [1, 2, 3, 4, 5] squares = map(lambda x, y: x**2, my_list) ``` [After] ```python my_list = [1, 2, 3, 4, 5] squares = map(lambda x: x**2, my_list) ```',421'PTH100': 'Replace `os.path.abspath` with `pathlib.Path.resolve()` for improved readability and type safety. [Before] ```python import os file_path = os.path.abspath("../path/to/file") ``` [After] ```python from pathlib import Path file_path = Path("../path/to/file").resolve() ```',422'PTH101': 'Replace `os.chmod` with `Path.chmod` for improved readability. [Before] ```python import os os.chmod("file.py", 0o444) ``` [After] ```python from pathlib import Path Path("file.py").chmod(0o444) ```',423'PTH102': 'Replace `os.mkdir` with `Path.mkdir` for improved readability and type safety. [Before] ```python import os os.mkdir("./directory/") ``` [After] ```python from pathlib import Path Path("./directory/").mkdir() ```',424'PTH103': 'Replace `os.makedirs` with `Path.mkdir` for improved readability and type safety. [Before] ```python import os os.makedirs("./nested/directory/") ``` [After] ```python from pathlib import Path Path("./nested/directory/").mkdir(parents=True) ```',425'PTH104': 'Replace `os.rename` with `Path.rename` for improved readability and type safety. [Before] ```python import os os.rename("old.py", "new.py") ``` [After] ```python from pathlib import Path Path("old.py").rename("new.py") ```',426'PTH105': 'Replace `os.replace` with `Path.replace` for improved readability. [Before] ```python import os os.replace("old.py", "new.py") ``` [After] ```python from pathlib import Path Path("old.py").replace("new.py") ```',427'PTH106': 'Replace `os.rmdir` with `Path.rmdir()` for improved readability and type safety. [Before] ```python import os os.rmdir("folder/") ``` [After] ```python from pathlib import Path Path("folder/").rmdir() ```',428'PTH107': 'Replace `os.remove` with `Path.unlink` for improved readability and type safety. [Before] ```python import os os.remove("file.py") ``` [After] ```python from pathlib import Path Path("file.py").unlink() ```',429'PTH108': 'Replace `os.unlink` with `Path.unlink` for improved readability. [Before] ```python import os os.unlink("file.py") ``` [After] ```python from pathlib import Path Path("file.py").unlink() ```',430'PTH109': 'Replace `os.getcwd()` with `Path.cwd()` for improved readability and type safety. [Before] ```python import os cwd = os.getcwd() ``` [After] ```python from pathlib import Path cwd = Path.cwd() ```',431'PTH110': 'Replace `os.path.exists` with `Path.exists` for improved readability. [Before] ```python import os os.path.exists("file.py") ``` [After] ```python from pathlib import Path Path("file.py").exists() ```',432'PTH111': 'Replace `os.path.expanduser` with `Path.expanduser` for improved readability. [Before] ```python import os os.path.expanduser("~/films/Monty Python") ``` [After] ```python from pathlib import Path Path("~/films/Monty Python").expanduser() ```',433'PTH112': 'Replace `os.path.isdir` with `Path.is_dir` for improved readability and modern practices. [Before] ```python import os os.path.isdir("docs") ``` [After] ```python from pathlib import Path Path("docs").is_dir() ```',434'PTH113': 'Replace `os.path.isfile` with `Path.is_file` for improved readability and type safety. [Before] ```python import os os.path.isfile("docs") ``` [After] ```python from pathlib import Path Path("docs").is_file() ```',435'PTH114': 'Replace `os.path.islink` with `Path.is_symlink` for improved readability. [Before] ```python import os os.path.islink("docs") ``` [After] ```python from pathlib import Path Path("docs").is_symlink() ```',436'PTH115': 'Replace `os.readlink` with `Path.readlink` for improved readability. [Before] ```python import os os.readlink(file_name) ``` [After] ```python from pathlib import Path Path(file_name).readlink() ```',437'PTH116': 'Replace `os.stat` with `pathlib.Path.stat()` for improved readability and maintainability. [Before] ```python import os from pwd import getpwuid from grp import getgrgid stat = os.stat(file_name) owner_name = getpwuid(stat.st_uid).pw_name group_name = getgrgid(stat.st_gid).gr_name ``` [After] ```python from pathlib import Path file_path = Path(file_name) stat = file_path.stat() owner_name = file_path.owner() group_name = file_path.group() ```',438'PTH117': 'Replace `os.path.isabs` with `Path.is_absolute()` for improved readability. [Before] ```python import os if os.path.isabs(file_name): print("Absolute path!") ``` [After] ```python from pathlib import Path if Path(file_name).is_absolute(): print("Absolute path!") ```',439'PTH118': 'Replace `os.path.join` with `pathlib.Path` for improved readability and type safety. [Before] ```python import os os.path.join(os.path.join(ROOT_PATH, "folder"), "file.py") ``` [After] ```python from pathlib import Path Path(ROOT_PATH) / "folder" / "file.py" ```',440'PTH119': 'Replace `os.path.basename` with `Path.name` for improved readability. [Before] ```python import os os.path.basename(__file__) ``` [After] ```python from pathlib import Path Path(__file__).name ```',441'PTH120': 'Replace `os.path.dirname` with `Path.parent` for improved readability. [Before] ```python import os os.path.dirname(__file__) ``` [After] ```python from pathlib import Path Path(__file__).parent ```',442'PTH121': 'Replace `os.path.samefile` with `Path.samefile` for improved readability. [Before] ```python import os os.path.samefile("f1.py", "f2.py") ``` [After] ```python from pathlib import Path Path("f1.py").samefile("f2.py") ```',443'PTH122': 'Replace `os.path.splitext` with `pathlib.Path` methods for better readability. [Before] ```python import os (root, ext) = os.path.splitext("foo/bar.py") ``` [After] ```python from pathlib import Path path = Path("foo/bar.py") root = path.parent / path.stem ext = path.suffix ```',444'PTH123': 'Replace the use of the `open()` builtin with `Path.open()` for improved readability. [Before] ```python with open("f1.py", "wb") as fp: ... ``` [After] ```python from pathlib import Path with Path("f1.py").open("wb") as fp: ... ```',445'PTH124': 'Replace the use of the `py.path` library with the standard library\'s `pathlib` for better maintainability. [Before] ```python import py.path p = py.path.local("/foo/bar").join("baz/qux") ``` [After] ```python from pathlib import Path p = Path("/foo/bar") / "baz" / "qux" ```',446'PTH201': 'Remove unnecessary argument when initializing `Path` with the current directory. [Before] ```python from pathlib import Path _ = Path(".") ``` [After] ```python from pathlib import Path _ = Path() ```',447'PTH202': 'Replace `os.path.getsize()` with `Path.stat().st_size` for improved readability. [Before] ```python import os os.path.getsize(__file__) ``` [After] ```python from pathlib import Path Path(__file__).stat().st_size ```',448'PTH203': 'Replace `os.path.getatime` with `Path.stat().st_atime` for improved readability. [Before] ```python import os os.path.getatime(__file__) ``` [After] ```python from pathlib import Path Path(__file__).stat().st_atime ```',449'PTH204': 'Replace `os.path.getmtime` with `Path.stat().st_mtime` for improved readability. [Before] ```python import os os.path.getmtime(__file__) ``` [After] ```python from pathlib import Path Path(__file__).stat().st_mtime ```',450'PTH205': 'Replace `os.path.getctime` with `Path.stat().st_ctime` for improved readability. [Before] ```python import os os.path.getctime(__file__) ``` [After] ```python from pathlib import Path Path(__file__).stat().st_ctime ```',451'PTH206': 'Replace the use of `.split(os.sep)` with `pathlib.Path` for better path manipulation. [Before] ```python import os "path/to/file_name.txt".split(os.sep)[-1] "path/to/file_name.txt".split(os.sep)[-2] # Iterating over the path parts if any(part in blocklist for part in "my/file/path".split(os.sep)): ... ``` [After] ```python from pathlib import Path Path("path/to/file_name.txt").name Path("path/to/file_name.txt").parent.name # Iterating over the path parts if any(part in blocklist for part in Path("my/file/path").parts): ... ```',452'PTH207': 'Replace `glob.glob()` with `Path.glob()` for improved readability and functionality. [Before] ```python import glob import os glob.glob(os.path.join("my_path", "requirements*.txt")) ``` [After] ```python from pathlib import Path Path("my_path").glob("requirements*.txt") ```',453'PTH208': 'Replace `os.listdir` with `pathlib.Path.iterdir` for improved readability and type safety. [Before] ```python import os p = "." for d in os.listdir(p): ... if os.listdir(p): ... if "file" in os.listdir(p): ... ``` [After] ```python from pathlib import Path p = Path(".") for d in p.iterdir(): ... if any(p.iterdir()): ... if (p / "file").exists(): ... ```',454'PTH210': 'Add a leading dot to the suffix in `Path.with_suffix()` calls that lack it. [Before] ```python path.with_suffix("py") ``` [After] ```python path.with_suffix(".py") ```',455'FLY002': 'Replace `str.join` calls with f-strings for improved readability. [Before] ```python " ".join((foo, bar)) ``` [After] ```python f"{foo} {bar}" ```',456'I001': 'Ensure imports are consistently ordered to improve readability. [Before] ```python import pandas import numpy as np ``` [After] ```python import numpy as np import pandas ```',457'I002': 'Ensure that required imports are consistently included at the top of the file to avoid errors. [Before] ```python import typing ``` [After] ```python from __future__ import annotations import typing ``` This fix adds the necessary `from __future__ import annotations` statement to ensure compatibility and prevent potential issues in projects that require it.',458'C901': 'Refactor the function to reduce McCabe complexity by simplifying the nested if statements. [Before] ```python def foo(a, b, c): if a: if b: if c: return 1 else: return 2 else: return 3 else: return 4 ``` [After] ```python def foo(a, b, c): if not a: return 4 if not b: return 3 if not c: return 2 return 1 ```',459'NPY001': 'Replace deprecated NumPy type aliases with their built-in equivalents. [Before] ```python import numpy as np np.int ``` [After] ```python import numpy as np int ```',460'NPY002': 'Replace legacy `np.random` function calls with the new `Generator` instance for better performance and statistical properties. [Before] ```python import numpy as np np.random.seed(1337) np.random.normal() ``` [After] ```python import numpy as np rng = np.random.default_rng(1337) rng.normal() ```',461'NPY003': 'Replace deprecated `np.alltrue` with the recommended `np.all` for better compatibility and performance. [Before] ```python import numpy as np np.alltrue([True, False]) ``` [After] ```python import numpy as np np.all([True, False]) ```',462'NPY201': 'Replace deprecated NumPy constants and functions with their updated equivalents. [Before] ```python import numpy as np arr1 = [np.Infinity, np.NaN, np.nan, np.PINF, np.inf] arr2 = [np.float_(1.5), np.float64(5.1)] np.round_(arr2) ``` [After] ```python import numpy as np arr1 = [np.inf, np.nan, np.nan, np.inf, np.inf] arr2 = [np.float64(1.5), np.float64(5.1)] np.round(arr2) ```',463'N801': 'Change the class name to follow the `CamelCase` convention as recommended by PEP 8. [Before] ```python class my_class: pass ``` [After] ```python class MyClass: pass ```',464'N802': 'Change the function name to follow the `snake_case` convention. [Before] ```python def myFunction(): pass ``` [After] ```python def my_function(): pass ```',465'N803': 'Change argument names to follow the `snake_case` convention as recommended by PEP 8. [Before] ```python def my_function(A, myArg): pass ``` [After] ```python def my_function(a, my_arg): pass ```',466'N804': 'Change the first argument of the class method from `self` to `cls` to adhere to PEP 8 guidelines. [Before] ```python class Example: @classmethod def function(self, data): ... ``` [After] ```python class Example: @classmethod def function(cls, data): ... ```',467'N805': 'Change the first argument of the instance method from `cls` to `self` to adhere to PEP 8 guidelines. [Before] ```python class Example: def function(cls, data): ... ``` [After] ```python class Example: def function(self, data): ... ```',468'N806': 'Change the variable name from uppercase to lowercase to comply with PEP 8 naming conventions. [Before] ```python def my_function(a): B = a + 3 return B ``` [After] ```python def my_function(a): b = a + 3 return b ```',469'N807': 'Remove leading and trailing underscores from the function name to adhere to PEP 8 guidelines. [Before] ```python def __my_function__(): pass ``` [After] ```python def my_function(): pass ```',470'N811': 'Change the alias of the imported constant to match the naming convention for constants. [Before] ```python from example import CONSTANT_VALUE as ConstantValue ``` [After] ```python from example import CONSTANT_VALUE ```',471'N812': 'Change the alias of the imported module to match the lowercase naming convention. [Before] ```python from example import myclassname as MyClassName ``` [After] ```python from example import myclassname ```',472'N813': 'Change the alias of the imported class to match its naming convention. [Before] ```python from example import MyClassName as myclassname ``` [After] ```python from example import MyClassName ```',473'N814': 'Change the import alias to match the naming convention of the imported class. [Before] ```python from example import MyClassName as MY_CLASS_NAME ``` [After] ```python from example import MyClassName ```',474'N815': 'Change class variable names from `mixedCase` to `snake_case` to comply with PEP 8 guidelines. [Before] ```python class MyClass: myVariable = "hello" another_variable = "world" ``` [After] ```python class MyClass: my_variable = "hello" another_variable = "world" ```',475'N816': 'Change global variable names from `mixedCase` to `snake_case` to comply with PEP 8 guidelines. [Before] ```python myVariable = "hello" another_variable = "world" yet_anotherVariable = "foo" ``` [After] ```python my_variable = "hello" another_variable = "world" yet_another_variable = "foo" ```',476'N817': 'Change the import alias to match the naming convention of the imported class. [Before] ```python from example import MyClassName as MCN ``` [After] ```python from example import MyClassName ``` This fix aligns the import alias with the naming style of the imported class, adhering to PEP 8 recommendations.',477'N818': 'Add the `Error` suffix to custom exception class names to comply with PEP 8. [Before] ```python class Validation(Exception): ... ``` [After] ```python class ValidationError(Exception): ... ```',478'N999': 'The code should validate module names to ensure they follow the `snake_case` convention and are valid identifiers. [Before] ```python import re def is_valid_module_name(name): return re.match(r\'^[a-zA-Z0-9_]+$\', name) is not None ``` [After] ```python import re def is_valid_module_name(name): return re.match(r\'^[a-z_][a-z0-9_]*$\', name) is not None ``` The fixed code ensures that the module name starts with a lowercase letter or underscore and only contains lowercase letters, digits, and underscores, adhering to the `snake_case` convention.',479'PD002': 'Replace `inplace=True` with assignment to a new variable for better data handling and method chaining. [Before] ```python df.sort_values("col1", inplace=True) ``` [After] ```python sorted_df = df.sort_values("col1") ```',480'PD003': 'Replace `.isnull` with `.isna` for consistency and clarity in the Pandas API. [Before] ```python import pandas as pd animals_df = pd.read_csv("animals.csv") pd.isnull(animals_df) ``` [After] ```python import pandas as pd animals_df = pd.read_csv("animals.csv") pd.isna(animals_df) ```',481'PD004': 'Replace `.notnull` with `.notna` for consistency and clarity in checking for non-null values in Pandas. [Before] ```python import pandas as pd animals_df = pd.read_csv("animals.csv") pd.notnull(animals_df) ``` [After] ```python import pandas as pd animals_df = pd.read_csv("animals.csv") pd.notna(animals_df) ```',482'PD007': 'Replace the deprecated `.ix` method with `.iloc` for ordinal indexing. [Before] ```python import pandas as pd students_df = pd.read_csv("students.csv") students_df.ix[0] # 0th row or row with label 0? ``` [After] ```python import pandas as pd students_df = pd.read_csv("students.csv") students_df.iloc[0] # 0th row. ```',483'PD008': 'Replace the use of `.at` with `.loc` for better idiomatic usage and versatility. [Before] ```python import pandas as pd students_df = pd.read_csv("students.csv") students_df.at["Maria"] ``` [After] ```python import pandas as pd students_df = pd.read_csv("students.csv") students_df.loc["Maria"] ```',484'PD009': 'Replace the use of `.iat` with `.iloc` for better idiomatic usage in Pandas. [Before] ```python import pandas as pd students_df = pd.read_csv("students.csv") students_df.iat[0] ``` [After] ```python import pandas as pd students_df = pd.read_csv("students.csv") students_df.iloc[0] ```',485'PD010': 'Replace `.pivot` with `.pivot_table` for better flexibility and functionality. [Before] ```python import pandas as pd df = pd.read_csv("cities.csv") df.pivot(index="city", columns="year", values="population") ``` [After] ```python import pandas as pd df = pd.read_csv("cities.csv") df.pivot_table(index="city", columns="year", values="population") ```',486'PD011': 'Replace the use of `.values` with `.to_numpy()` for clarity and to adhere to best practices. [Before] ```python import pandas as pd animals = pd.read_csv("animals.csv").values # Ambiguous. ``` [After] ```python import pandas as pd animals = pd.read_csv("animals.csv").to_numpy() # Explicit. ```',487'PD012': 'Replace `pd.read_table` with `pd.read_csv` for better clarity and idiomatic usage when reading CSV files. [Before] ```python import pandas as pd cities_df = pd.read_table("cities.csv", sep=",") ``` [After] ```python import pandas as pd cities_df = pd.read_csv("cities.csv") ```',488'PD013': 'Replace the use of `.stack()` with `.melt()` for better functionality and ease of use. [Before] ```python import pandas as pd cities_df = pd.read_csv("cities.csv") cities_df.set_index("city").stack() ``` [After] ```python import pandas as pd cities_df = pd.read_csv("cities.csv") cities_df.melt(id_vars="city") ```',489'PD015': 'Use the `.merge` method on DataFrame objects for better readability and idiomatic code. [Before] ```python import pandas as pd cats_df = pd.read_csv("cats.csv") dogs_df = pd.read_csv("dogs.csv") rabbits_df = pd.read_csv("rabbits.csv") pets_df = pd.merge(pd.merge(cats_df, dogs_df), rabbits_df) # Hard to read. ``` [After] ```python import pandas as pd cats_df = pd.read_csv("cats.csv") dogs_df = pd.read_csv("dogs.csv") rabbits_df = pd.read_csv("rabbits.csv") pets_df = cats_df.merge(dogs_df).merge(rabbits_df) ```',490'PD101': 'Replace the use of `.nunique()` with a more efficient check for constant values in a Pandas Series. [Before] ```python import pandas as pd data = pd.Series(range(1000)) if data.nunique() <= 1: print("Series is constant") ``` [After] ```python import pandas as pd data = pd.Series(range(1000)) array = data.to_numpy() if array.shape[0] == 0 or (array[0] == array).all(): print("Series is constant") ```',491'PD901': 'Change the variable name from `df` to a more descriptive name like `animals` to improve code clarity and avoid potential name conflicts. [Before] ```python import pandas as pd df = pd.read_csv("animals.csv") ``` [After] ```python import pandas as pd animals = pd.read_csv("animals.csv") ```',492'PERF101': 'Remove the unnecessary `list()` call to improve performance when iterating over an iterable. [Before] ```python items = (1, 2, 3) for i in list(items): print(i) ``` [After] ```python items = (1, 2, 3) for i in items: print(i) ```',493'PERF102': 'Replace `dict.items()` with `dict.values()` when only the values are needed for iteration. [Before] ```python obj = {"a": 1, "b": 2} for key, value in obj.items(): print(value) ``` [After] ```python obj = {"a": 1, "b": 2} for value in obj.values(): print(value) ```',494'PERF203': 'Refactor the `try`-`except` blocks to optimize performance by moving the exception handling outside of loops and using dictionary `get()` method to avoid exceptions. [Before] ```python string_numbers: list[str] = ["1", "2", "three", "4", "5"] # `try`/`except` that could be moved out of the loop: int_numbers: list[int] = [] for num in string_numbers: try: int_numbers.append(int(num)) except ValueError as e: print(f"Couldn\'t convert to integer: {e}") break # `try`/`except` used when "look before you leap" idioms could be used: number_names: dict[int, str] = {1: "one", 3: "three", 4: "four"} for number in range(5): try: name = number_names[number] except KeyError: continue else: print(f"The name of {number} is {name}") ``` [After] ```python string_numbers: list[str] = ["1", "2", "three", "4", "5"] int_numbers: list[int] = [] try: for num in string_numbers: int_numbers.append(int(num)) except ValueError as e: print(f"Couldn\'t convert to integer: {e}") number_names: dict[int, str] = {1: "one", 3: "three", 4: "four"} for number in range(5): name = number_names.get(number) if name is not None: print(f"The name of {number} is {name}") ```',495'PERF401': 'Replace the for-loop with a list comprehension for better readability and performance. [Before] ```python original = list(range(10000)) filtered = [] for i in original: if i % 2: filtered.append(i) ``` [After] ```python original = list(range(10000)) filtered = [x for x in original if x % 2] ```',496'PERF402': 'Replace the for-loop with a direct list copy for improved readability and performance. [Before] ```python original = list(range(10000)) filtered = [] for i in original: filtered.append(i) ``` [After] ```python original = list(range(10000)) filtered = list(original) ```',497'PERF403': 'Replace the `for` loop with a dictionary comprehension for improved readability and performance. [Before] ```python pairs = (("a", 1), ("b", 2)) result = {} for x, y in pairs: if y % 2: result[x] = y ``` [After] ```python pairs = (("a", 1), ("b", 2)) result = {x: y for x, y in pairs if y % 2} ```',498'E101': 'Replace mixed indentation with consistent spaces for better readability and to avoid syntax errors. [Before] ```python if a == 0: a = 1 \\tb = 1 ``` [After] ```python if a == 0: a = 1 b = 1 ```',499'E111': 'Incorrect indentation using 3 spaces instead of 4. [Before] ```python if True: a = 1 ``` [After] ```python if True: a = 1 ``` This fix corrects the indentation to 4 spaces, adhering to PEP 8 guidelines for consistent code formatting.',500'E112': 'Indent the block inside the for loop to ensure valid Python syntax. [Before] ```python for item in items: pass ``` [After] ```python for item in items: pass ```',501'E113': 'Remove the unexpected indentation to ensure valid Python syntax. [Before] ```python a = 1 b = 2 ``` [After] ```python a = 1 b = 2 ```',502'E114': 'Adjust the indentation of the comment to be a multiple of 4 spaces for PEP 8 compliance. [Before] ```python if True: # a = 1 ``` [After] ```python if True: # a = 1 ```',503'E115': 'Indent the comment to align with the code block it describes. [Before] ```python for item in items: # Hi pass ``` [After] ```python for item in items: # Hi pass ```',504'E116': 'Correct the indentation of the comment to match the code block. [Before] ```python a = 1 # b = 2 ``` [After] ```python a = 1 # b = 2 ```',505'E117': 'Correct the indentation level to adhere to PEP 8 standards. [Before] ```python for item in items: pass ``` [After] ```python for item in items: pass ```',506'E201': 'Remove extraneous whitespace inside parentheses, brackets, or braces. [Before] ```python spam(ham[ 1], {eggs: 2}) spam( ham[1], {eggs: 2}) spam(ham[1], { eggs: 2}) ``` [After] ```python spam(ham[1], {eggs: 2}) spam(ham[1], {eggs: 2}) spam(ham[1], {eggs: 2}) ```',507'E202': 'Remove extraneous whitespace before closing parentheses, brackets, or braces to comply with PEP 8. [Before] ```python spam(ham[1], {eggs: 2} ) spam(ham[1 ], {eggs: 2}) spam(ham[1], {eggs: 2 }) ``` [After] ```python spam(ham[1], {eggs: 2}) spam(ham[1], {eggs: 2}) spam(ham[1], {eggs: 2}) ```',508'E203': 'Remove extraneous whitespace before commas in the assignment. [Before] ```python if x == 4: print(x, y); x, y = y , x ``` [After] ```python if x == 4: print(x, y); x, y = y, x ```',509'E204': 'Remove the whitespace after the `@` symbol to comply with PEP 8. [Before] ```python @ decorator def func(): pass ``` [After] ```python @decorator def func(): pass ```',510'E211': 'Remove extraneous whitespace before open parentheses or brackets. [Before] ```python spam (1) ``` [After] ```python spam(1) ```',511'E221': 'Remove extraneous whitespace around the operator to comply with PEP 8 guidelines. [Before] ```python a = 4 + 5 ``` [After] ```python a = 4 + 5 ```',512'E222': 'Remove extraneous whitespace after the operator to comply with PEP 8 guidelines. [Before] ```python a = 4 + 5 ``` [After] ```python a = 4 + 5 ```',513'E223': 'Remove extraneous tabs before operators to comply with PEP 8 guidelines. [Before] ```python a = 4\\t+ 5 ``` [After] ```python a = 4 + 5 ```',514'E224': 'Replace the tab character with a single space to comply with PEP 8 guidelines. [Before] ```python a = 4 +\\t5 ``` [After] ```python a = 4 + 5 ```',515'E225': 'Add whitespace around the equality operator for PEP 8 compliance. [Before] ```python if number==42: print(\'you have found the meaning of life\') ``` [After] ```python if number == 42: print(\'you have found the meaning of life\') ```',516'E226': 'Add whitespace around the arithmetic operator for PEP 8 compliance. [Before] ```python number = 40+2 ``` [After] ```python number = 40 + 2 ```',517'E227': 'Add whitespace around the bitwise shift operator for PEP 8 compliance. [Before] ```python x = 128<<1 ``` [After] ```python x = 128 << 1 ```',518'E228': 'Add whitespace around the modulo operator for PEP 8 compliance. [Before] ```python remainder = 10%2 ``` [After] ```python remainder = 10 % 2 ```',519'E231': 'Add whitespace after commas for better readability. [Before] ```python a = (1,2) ``` [After] ```python a = (1, 2) ```',520'E241': 'Remove extraneous whitespace after the comma for consistent formatting. [Before] ```python a = 4, 5 ``` [After] ```python a = 4, 5 ```',521'E242': 'Replace tabs after commas with a single space for proper formatting. [Before] ```python a = 4,\\t5 ``` [After] ```python a = 4, 5 ```',522'E251': 'Remove spaces around the equals sign in the function parameter definition. [Before] ```python def add(a = 0) -> int: return a + 1 ``` [After] ```python def add(a=0) -> int: return a + 1 ```',523'E252': 'Add a space before and after the equals sign in the function parameter annotation. [Before] ```python def add(a: int=0) -> int: return a + 1 ``` [After] ```python def add(a: int = 0) -> int: return a + 1 ```',524'E261': 'Ensure inline comments are separated by at least two spaces from the preceding statement. [Before] ```python x = x + 1 # Increment x ``` [After] ```python x = x + 1 # Increment x ```',525'E262': 'Ensure there is exactly one space after the `#` in inline comments. [Before] ```python x = x + 1 #Increment x x = x + 1 # Increment x x = x + 1 # \\xa0Increment x ``` [After] ```python x = x + 1 # Increment x x = x + 1 # Increment x x = x + 1 # Increment x ```',526'E265': 'Add a space after the `#` in block comments to comply with PEP 8 guidelines. [Before] ```python #Block comment ``` [After] ```python # Block comment ```',527'E266': 'Replace block comments starting with multiple `#` characters with a single `#` followed by a space. [Before] ```python ### Block comment ``` [After] ```python # Block comment ```',528'E271': 'Remove extraneous whitespace around keywords for cleaner code. [Before] [python] ```python True and False ``` [After] [python] ```python True and False ```',529'E272': 'Remove extraneous whitespace before keywords for cleaner code. [Before] ```python True and False ``` [After] ```python True and False ```',530'E273': 'Remove extraneous tabs after keywords for cleaner code. [Before] ```python True and\\tFalse ``` [After] ```python True and False ```',531'E274': 'Remove extraneous tabs before keywords for cleaner code. [Before] [python] ```python True\\tand False ``` [After] [python] ```python True and False ```',532'E275': 'Add a space after the `if` keyword for better readability. [Before] ```python if(True): pass ``` [After] ```python if (True): pass ```',533'E301': 'Add a blank line between methods to comply with PEP 8. [Before] ```python class MyClass(object): def func1(): pass def func2(): pass ``` [After] ```python class MyClass(object): def func1(): pass def func2(): pass ```',534'E302': 'Add two blank lines between top-level functions to comply with PEP 8. [Before] ```python def func1(): pass def func2(): pass ``` [After] ```python def func1(): pass def func2(): pass ```',535'E303': 'Remove extraneous blank lines to comply with PEP 8 guidelines. [Before] ```python def func1(): pass def func2(): pass ``` [After] ```python def func1(): pass def func2(): pass ```',536'E304': 'Remove the extraneous blank line between the decorator and the method definition. [Before] ```python class User(object): @property def name(self): pass ``` [After] ```python class User(object): @property def name(self): pass ```',537'E305': 'Add two blank lines after the class definition to comply with PEP 8 guidelines. [Before] ```python class User(object): pass user = User() ``` [After] ```python class User(object): pass user = User() ```',538'E306': 'Add a blank line between nested function definitions to comply with PEP 8 guidelines. [Before] ```python def outer(): def inner(): pass def inner2(): pass ``` [After] ```python def outer(): def inner(): pass def inner2(): pass ```',539'E401': 'Separate multiple imports into individual lines for better readability and adherence to PEP 8. [Before] ```python import sys, os ``` [After] ```python import os import sys ```',540'E402': 'Move all import statements to the top of the file or cell to comply with PEP 8 guidelines. [Before] ```python "One string" "Two string" a = 1 import os from sys import x ``` [After] ```python import os from sys import x "One string" "Two string" a = 1 ```',541'E501': 'The function call exceeds the recommended line length, which can hurt readability. [Before] ```python my_function(param1, param2, param3, param4, param5, param6, param7, param8, param9, param10) ``` [After] ```python my_function( param1, param2, param3, param4, param5, param6, param7, param8, param9, param10 ) ``` This format improves readability by breaking the function call into multiple lines, adhering to the recommended line length.',542'E502': 'Remove the redundant backslash for better readability and adherence to PEP 8 guidelines. [Before] ```python x = (2 + \\ 2) ``` [After] ```python x = (2 + 2) ```',543'E701': 'Compound statements should be split into separate lines for better readability and adherence to PEP 8. [Before] ```python if foo == "blah": do_blah_thing() ``` [After] ```python if foo == "blah": do_blah_thing() ```',544'E702': 'Separate multiline statements onto individual lines for better readability and adherence to PEP 8. [Before] ```python do_one(); do_two(); do_three() ``` [After] ```python do_one() do_two() do_three() ```',545'E703': 'Remove unnecessary trailing semicolons from statements in Python. [Before] [python] ```python do_four(); # useless semicolon ``` [After] [python] ```python do_four() # corrected by removing the semicolon ```',546'E711': 'Replace comparisons to `None` using `!=` or `==` with `is not` or `is`. [Before] ```python if arg != None: pass if None == arg: pass ``` [After] ```python if arg is not None: pass ```',547'E712': 'Replace equality comparisons to boolean literals with direct truth value checks. [Before] ```python if foo == True: ... if bar == False: ... ``` [After] ```python if foo: ... if not bar: ... ```',548'E713': 'Replace `not {element} in {collection}` with `{element} not in {collection}` for improved readability. [Before] ```python Z = not X in Y if not X.B in Y: pass ``` [After] ```python Z = X not in Y if X.B not in Y: pass ```',549'E714': 'Replace `not {foo} is {bar}` with `{foo} is not {bar}` for better readability. [Before] ```python if not X is Y: pass Z = not X.B is Y ``` [After] ```python if X is not Y: pass Z = X.B is not Y ```',550'E721': 'Replace type comparisons using `==` with `isinstance` for better type checking. [Before] ```python if type(obj) == type(1): pass if type(obj) == int: pass ``` [After] ```python if isinstance(obj, int): pass ```',551'E722': 'Replace bare `except` with `except Exception` to avoid catching system-exiting exceptions. [Before] ```python try: raise KeyboardInterrupt("You probably don\'t mean to break CTRL-C.") except: print("But a bare `except` will ignore keyboard interrupts.") ``` [After] ```python try: raise KeyboardInterrupt("You probably don\'t mean to break CTRL-C.") except Exception as e: print(f"But an `except Exception` will not ignore keyboard interrupts: {e}") ```',552'E731': 'Replace the lambda expression with a def statement for better readability and traceability. [Before] ```python f = lambda x: 2 * x ``` [After] ```python def f(x): return 2 * x ```',553'E741': 'Replace the variable names \'l\', \'O\', and \'I\' with \'L\', \'o\', and \'i\' to avoid confusion with similar-looking characters. [Before] ```python l = 0 O = 123 I = 42 ``` [After] ```python L = 0 o = 123 i = 42 ```',554'E742': 'Replace ambiguous class names with more descriptive alternatives to avoid confusion. [Before] ```python class I(object): ... ``` [After] ```python class Integer(object): ... ```',555'E743': 'Rename the function to avoid using the character \'l\' for clarity. [Before] ```python def l(x): ... ``` [After] ```python def long_name(x): ... ```',556'E902': 'The error message indicates a permissions issue when trying to read the file. To resolve this, ensure the file has the correct permissions for the user running the command. [Before] ```shell $ chmod 000 a.py ``` [After] ```shell $ chmod 644 a.py ``` This change sets the file permissions to allow the owner to read and write, while others can only read, thus resolving the permission denied error.',557'E999': 'The original code has a syntax error due to a missing value assignment. [Before] ```python x = ``` [After] ```python x = 1 ``` This fix assigns a value to `x`, resolving the syntax error and allowing the code to execute properly.',558'W191': 'Replace tabs with spaces for indentation to comply with PEP 8 guidelines. [Before] ```python def example_function(): \u2192print("Hello, World!") ``` [After] ```python def example_function(): print("Hello, World!") ``` This change replaces the tab character (\u2192) with four spaces, aligning with PEP 8\'s recommendation for using spaces for indentation.',559'W291': 'Remove the trailing whitespace after the function call to comply with PEP 8 guidelines. [Before] ```python spam(1) \\n# ``` [After] ```python spam(1)\\n# ```',560'W292': 'Add a newline character at the end of the file to ensure it adheres to best practices. [Before] [python] ```python spam(1) ``` [After] [python] ```python spam(1)\\n ```',561'W293': 'Remove trailing whitespace from blank lines to comply with PEP 8 guidelines. [Before] ```python class Foo(object):\\n \\n bang = 12 ``` [After] ```python class Foo(object):\\n\\n bang = 12 ```',562'W391': 'Remove multiple trailing blank lines while ensuring the last line ends with a newline. [Before] ```python spam(1)\\n\\n\\n ``` [After] ```python spam(1)\\n ``` This fix ensures that only a single newline remains at the end of the file, adhering to best practices for file formatting.',563'W505': 'The docstring exceeds the recommended line length, which affects readability. [Before] ```python def function(x): """Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis auctor purus ut ex fermentum, at maximus est hendrerit.""" ``` [After] ```python def function(x): """ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis auctor purus ut ex fermentum, at maximus est hendrerit. """ ```',564'W605': 'Use raw strings for regex patterns to avoid invalid escape sequences. [Before] ```python regex = "\\.png$" ``` [After] ```python regex = r"\\.png$" ``` Escape backslashes properly in strings containing valid escape sequences. [Before] ```python value = "new line\\nand invalid escape \\_ here" ``` [After] ```python value = "new line\\nand invalid escape \\\\_ here" ```',565'DOC201': 'Add a "Returns" section to the docstring to improve documentation completeness. [Before] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Args: distance: Distance traveled. time: Time spent traveling. """ return distance / time ``` [After] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Args: distance: Distance traveled. time: Time spent traveling. Returns: Speed as distance divided by time. """ return distance / time ```',566'DOC202': 'Remove the unnecessary "Returns" section from the docstring of a function that does not return a value. [Before] ```python def say_hello(n: int) -> None: """Says hello to the user. Args: n: Number of times to say hello. Returns: Doesn\'t return anything. """ for _ in range(n): print("Hello!") ``` [After] ```python def say_hello(n: int) -> None: """Says hello to the user. Args: n: Number of times to say hello. """ for _ in range(n): print("Hello!") ```',567'DOC402': 'Add a "Yields" section to the docstring to improve documentation completeness. [Before] ```python def count_to_n(n: int) -> int: """Generate integers up to *n*. Args: n: The number at which to stop counting. """ for i in range(1, n + 1): yield i ``` [After] ```python def count_to_n(n: int) -> int: """Generate integers up to *n*. Args: n: The number at which to stop counting. Yields: int: The number we\'re at in the count. """ for i in range(1, n + 1): yield i ```',568'DOC403': 'Remove the unnecessary "Yields" section from the docstring of the function. [Before] ```python def say_hello(n: int) -> None: """Says hello to the user. Args: n: Number of times to say hello. Yields: Doesn\'t yield anything. """ for _ in range(n): print("Hello!") ``` [After] ```python def say_hello(n: int) -> None: """Says hello to the user. Args: n: Number of times to say hello. """ for _ in range(n): print("Hello!") ```',569'DOC501': 'Add documentation for explicitly raised exceptions in the function docstring. [Before] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Args: distance: Distance traveled. time: Time spent traveling. Returns: Speed as distance divided by time. """ try: return distance / time except ZeroDivisionError as exc: raise FasterThanLightError from exc ``` [After] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Args: distance: Distance traveled. time: Time spent traveling. Returns: Speed as distance divided by time. Raises: FasterThanLightError: If speed is greater than the speed of light. """ try: return distance / time except ZeroDivisionError as exc: raise FasterThanLightError from exc ```',570'DOC502': 'Remove the `Raises` section from the docstring since the exception is not explicitly raised in the function body. [Before] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Args: distance: Distance traveled. time: Time spent traveling. Returns: Speed as distance divided by time. Raises: ZeroDivisionError: Divided by zero. """ return distance / time ``` [After] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Args: distance: Distance traveled. time: Time spent traveling. Returns: Speed as distance divided by time. """ return distance / time ```',571'D100': 'Add a module docstring to describe the purpose and contents of the module. [Before] ```python class FasterThanLightError(ZeroDivisionError): ... def calculate_speed(distance: float, time: float) -> float: ... ``` [After] ```python """Utility functions and classes for calculating speed. This module provides: - FasterThanLightError: exception when FTL speed is calculated; - calculate_speed: calculate speed given distance and time. """ class FasterThanLightError(ZeroDivisionError): ... def calculate_speed(distance: float, time: float) -> float: ... ```',572'D101': 'Add a docstring to the `Player` class to document its purpose, attributes, and methods. [Before] ```python class Player: def __init__(self, name: str, points: int = 0) -> None: self.name: str = name self.points: int = points def add_points(self, points: int) -> None: self.points += points ``` [After] ```python class Player: """A player in the game. Attributes ---------- name : str The name of the player. points : int The number of points the player has. Methods ------- add_points(points: int) -> None Add points to the player\'s score. """ def __init__(self, name: str, points: int = 0) -> None: self.name: str = name self.points: int = points def add_points(self, points: int) -> None: self.points += points ```',573'D102': 'Add a docstring to the `greet` method to document its behavior, parameters, and exceptions. [Before] ```python class Cat(Animal): def greet(self, happy: bool = True): if happy: print("Meow!") else: raise ValueError("Tried to greet an unhappy cat.") ``` [After] ```python class Cat(Animal): def greet(self, happy: bool = True): """Print a greeting from the cat. Parameters ---------- happy : bool, optional Whether the cat is happy, is True by default. Raises ------ ValueError If the cat is not happy. """ if happy: print("Meow!") else: raise ValueError("Tried to greet an unhappy cat.") ```',574'D103': 'Add a docstring to the `calculate_speed` function to document its purpose, parameters, return value, and exceptions. [Before] ```python def calculate_speed(distance: float, time: float) -> float: try: return distance / time except ZeroDivisionError as exc: raise FasterThanLightError from exc ``` [After] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Parameters ---------- distance : float Distance traveled. time : float Time spent traveling. Returns ------- float Speed as distance divided by time. Raises ------ FasterThanLightError If speed is greater than the speed of light. """ try: return distance / time except ZeroDivisionError as exc: raise FasterThanLightError from exc ```',575'D104': 'Add a package-level docstring to provide context and documentation for the public package. [Before] ```python __all__ = ["Player", "Game"] ``` [After] ```python """Game and player management package. This package provides classes for managing players and games. """ __all__ = ["Player", "Game"] ```',576'D105': 'Add a docstring to the magic method for clarity and documentation compliance. [Before] ```python class Cat(Animal): def __str__(self) -> str: return f"Cat: {self.name}" ``` [After] ```python class Cat(Animal): def __str__(self) -> str: """Return a string representation of the cat.""" return f"Cat: {self.name}" ```',577'D106': 'Add a docstring to the nested class to ensure it is documented properly. [Before] ```python class Foo: """Class Foo.""" class Bar: ... ``` [After] ```python class Foo: """Class Foo.""" class Bar: """Class Bar.""" ```',578'D107': 'Add a docstring to the `__init__` method to describe its purpose and parameters. [Before] ```python class City: def __init__(self, name: str, population: int) -> None: self.name: str = name self.population: int = population ``` [After] ```python class City: def __init__(self, name: str, population: int) -> None: """Initialize a city with a name and population.""" self.name: str = name self.population: int = population ```',579'D200': 'Convert multi-line docstrings to single-line format for consistency. [Before] ```python def average(values: list[float]) -> float: """ Return the mean of the given values. """ ``` [After] ```python def average(values: list[float]) -> float: """Return the mean of the given values.""" ```',580'D201': 'Remove the blank line between the function definition and its docstring for consistency. [Before] ```python def average(values: list[float]) -> float: """Return the mean of the given values.""" ``` [After] ```python def average(values: list[float]) -> float: """Return the mean of the given values.""" ```',581'D202': 'Remove unnecessary blank lines between the function docstring and the function body for consistency. [Before] ```python def average(values: list[float]) -> float: """Return the mean of the given values.""" return sum(values) / len(values) ``` [After] ```python def average(values: list[float]) -> float: """Return the mean of the given values.""" return sum(values) / len(values) ```',582'D203': 'Add a blank line before the class docstring for consistency. [Before] ```python class PhotoMetadata: """Metadata about a photo.""" ``` [After] ```python class PhotoMetadata: """Metadata about a photo.""" ```',583'D204': 'Add a blank line between the class docstring and the first method. [Before] ```python class PhotoMetadata: """Metadata about a photo.""" def __init__(self, file: Path): ... ``` [After] ```python class PhotoMetadata: """Metadata about a photo.""" def __init__(self, file: Path): ... ```',584'D205': 'Add a blank line between the summary and the description in the docstring. [Before] ```python def sort_list(l: list[int]) -> list[int]: """Return a sorted copy of the list. Sort the list in ascending order and return a copy of the result using the bubble sort algorithm. """ ``` [After] ```python def sort_list(l: list[int]) -> list[int]: """Return a sorted copy of the list. Sort the list in ascending order and return a copy of the result using the bubble sort algorithm. """ ```',585'D206': 'Replace tab indentation in the docstring with spaces to comply with PEP 8. [Before] ```python def sort_list(l: list[int]) -> list[int]: """Return a sorted copy of the list. \tSort the list in ascending order and return a copy of the result using the bubble \tsort algorithm. """ ``` [After] ```python def sort_list(l: list[int]) -> list[int]: """Return a sorted copy of the list. Sort the list in ascending order and return a copy of the result using the bubble sort algorithm. """ ```',586'D207': 'The docstring is under-indented, which violates PEP 257 guidelines. [Before] ```python def sort_list(l: list[int]) -> list[int]: """Return a sorted copy of the list. Sort the list in ascending order and return a copy of the result using the bubble sort algorithm. """ ``` [After] ```python def sort_list(l: list[int]) -> list[int]: """Return a sorted copy of the list. Sort the list in ascending order and return a copy of the result using the bubble sort algorithm. """ ```',587'D208': 'Correct the indentation of the docstring to align with PEP 257 guidelines. [Before] ```python def sort_list(l: list[int]) -> list[int]: """Return a sorted copy of the list. Sort the list in ascending order and return a copy of the result using the bubble sort algorithm. """ ``` [After] ```python def sort_list(l: list[int]) -> list[int]: """Return a sorted copy of the list. Sort the list in ascending order and return a copy of the result using the bubble sort algorithm. """ ```',588'D209': 'Ensure the closing quotes of multi-line docstrings are on their own line for better readability and compliance with PEP 257. [Before] ```python def sort_list(l: List[int]) -> List[int]: """Return a sorted copy of the list. Sort the list in ascending order and return a copy of the result using the bubble sort algorithm.""" ``` [After] ```python def sort_list(l: List[int]) -> List[int]: """Return a sorted copy of the list. Sort the list in ascending order and return a copy of the result using the bubble sort algorithm. """ ```',589'D210': 'Remove surrounding whitespace in docstrings for consistency. [Before] ```python def factorial(n: int) -> int: """ Return the factorial of n. """ ``` [After] ```python def factorial(n: int) -> int: """Return the factorial of n.""" ```',590'D211': 'Remove the blank line between the class definition and its docstring for consistency. [Before] ```python class PhotoMetadata: """Metadata about a photo.""" ``` [After] ```python class PhotoMetadata: """Metadata about a photo.""" ```',591'D212': 'Move the summary line of the docstring to the first physical line immediately after the opening quotes. [Before] ```python def sort_list(l: list[int]) -> list[int]: """ Return a sorted copy of the list. Sort the list in ascending order and return a copy of the result using the bubble sort algorithm. """ ``` [After] ```python def sort_list(l: list[int]) -> list[int]: """Return a sorted copy of the list. Sort the list in ascending order and return a copy of the result using the bubble sort algorithm. """ ```',592'D213': 'The summary line of the docstring should be on the second physical line, following a blank line after the opening quotes. [Before] ```python def sort_list(l: list[int]) -> list[int]: """Return a sorted copy of the list. Sort the list in ascending order and return a copy of the result using the bubble sort algorithm. """ ``` [After] ```python def sort_list(l: list[int]) -> list[int]: """ Return a sorted copy of the list. Sort the list in ascending order and return a copy of the result using the bubble sort algorithm. """ ```',593'D214': 'Correct the indentation of the docstring sections to follow the standard convention. [Before] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Args: distance: Distance traveled. time: Time spent traveling. Returns: Speed as distance divided by time. Raises: FasterThanLightError: If speed is greater than the speed of light. """ ``` [After] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Args: distance: Distance traveled. time: Time spent traveling. Returns: Speed as distance divided by time. Raises: FasterThanLightError: If speed is greater than the speed of light. """ ```',594'D215': 'Correct the indentation of the section headers in the docstring to match the numpy-style convention. [Before] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Parameters ---------- distance : float Distance traveled. time : float Time spent traveling. Returns ------- float Speed as distance divided by time. Raises ------ FasterThanLightError If speed is greater than the speed of light. """ ``` [After] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Parameters ---------- distance : float Distance traveled. time : float Time spent traveling. Returns ------- float Speed as distance divided by time. Raises ------ FasterThanLightError If speed is greater than the speed of light. """ ```',595'D300': 'Change single quotes to double quotes for docstrings to comply with PEP 257. [Before] ```python def kos_root(): \'\'\'Return the pathname of the KOS root directory.\'\'\' ``` [After] ```python def kos_root(): """Return the pathname of the KOS root directory.""" ```',596'D301': 'Change the docstring to a raw string literal to properly handle backslashes. [Before] ```python def foobar(): """Docstring for foo\\bar.""" ``` [After] ```python def foobar(): r"""Docstring for foo\\bar.""" ```',597'D400': 'Add a period at the end of the first line of the docstring to comply with PEP 257. [Before] ```python def average(values: list[float]) -> float: """Return the mean of the given values""" ``` [After] ```python def average(values: list[float]) -> float: """Return the mean of the given values.""" ```',598'D401': 'Change the first line of the docstring to use the imperative mood. [Before] ```python def average(values: list[float]) -> float: """Returns the mean of the given values.""" ``` [After] ```python def average(values: list[float]) -> float: """Return the mean of the given values.""" ```',599'D402': 'Remove the function signature from the docstring and provide a clear description of the function\'s purpose. [Before] ```python def foo(a, b): """foo(a: int, b: int) -> list[int]""" ``` [After] ```python def foo(a: int, b: int) -> list[int]: """Return a list of a and b.""" ```',600'D403': 'Capitalize the first letter of the docstring for grammatical correctness. [Before] ```python def average(values: list[float]) -> float: """return the mean of the given values.""" ``` [After] ```python def average(values: list[float]) -> float: """Return the mean of the given values.""" ```',601'D404': 'Change the docstring to start with an imperative verb for better compliance with PEP 257. [Before] ```python def average(values: list[float]) -> float: """This function returns the mean of the given values.""" ``` [After] ```python def average(values: list[float]) -> float: """Return the mean of the given values.""" ```',602'D405': 'Capitalize section headers in the docstring for consistency with style guidelines. [Before] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. args: distance: Distance traveled. time: Time spent traveling. returns: Speed as distance divided by time. raises: FasterThanLightError: If speed is greater than the speed of light. """ ``` [After] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Args: distance: Distance traveled. time: Time spent traveling. Returns: Speed as distance divided by time. Raises: FasterThanLightError: If speed is greater than the speed of light. """ ```',603'D406': 'Remove colons from section headers in the docstring to comply with numpy-style formatting. [Before] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Parameters: ----------- distance : float Distance traveled. time : float Time spent traveling. Returns: -------- float Speed as distance divided by time. Raises: ------- FasterThanLightError If speed is greater than the speed of light. """ ``` [After] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Parameters ---------- distance : float Distance traveled. time : float Time spent traveling. Returns ------- float Speed as distance divided by time. Raises ------ FasterThanLightError If speed is greater than the speed of light. """ ```',604'D407': 'Add underlines to section headers in the docstring to comply with the numpy-style format. [Before] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Parameters distance : float Distance traveled. time : float Time spent traveling. Returns float Speed as distance divided by time. Raises FasterThanLightError If speed is greater than the speed of light. """ ``` [After] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Parameters ---------- distance : float Distance traveled. time : float Time spent traveling. Returns ------- float Speed as distance divided by time. Raises ------ FasterThanLightError If speed is greater than the speed of light. """ ```',605'D408': 'The section underlines in the docstring should be directly below their respective headers without any blank lines in between. [Before] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Parameters ---------- distance : float Distance traveled. time : float Time spent traveling. Returns ------- float Speed as distance divided by time. Raises ------ FasterThanLightError If speed is greater than the speed of light. """ ``` [After] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Parameters ---------- distance : float Distance traveled. time : float Time spent traveling. Returns ------- float Speed as distance divided by time. Raises ------ FasterThanLightError If speed is greater than the speed of light. """ ```',606'D409': 'The section underlines in the docstring do not match the length of their corresponding section headers. [Before] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Parameters --- distance : float Distance traveled. time : float Time spent traveling. Returns --- float Speed as distance divided by time. Raises --- FasterThanLightError If speed is greater than the speed of light. """ ``` [After] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Parameters ---------- distance : float Distance traveled. time : float Time spent traveling. Returns ------- float Speed as distance divided by time. Raises ------ FasterThanLightError If speed is greater than the speed of light. """ ```',607'D410': 'Add a blank line between the "Parameters" and "Returns" sections in the docstring. [Before] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Parameters ---------- distance : float Distance traveled. time : float Time spent traveling. Returns ------- float Speed as distance divided by time. Raises ------ FasterThanLightError If speed is greater than the speed of light. """ ``` [After] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Parameters ---------- distance : float Distance traveled. time : float Time spent traveling. Returns ------- float Speed as distance divided by time. Raises ------ FasterThanLightError If speed is greater than the speed of light. """ ```',608'D411': 'Add blank lines between docstring sections for consistency. [Before] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Parameters ---------- distance : float Distance traveled. time : float Time spent traveling. Returns ------- float Speed as distance divided by time. Raises ------ FasterThanLightError If speed is greater than the speed of light. """ ``` [After] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Parameters ---------- distance : float Distance traveled. time : float Time spent traveling. Returns ------- float Speed as distance divided by time. Raises ------ FasterThanLightError If speed is greater than the speed of light. """ ```',609'D412': 'Remove the blank lines between section headers and their corresponding section bodies in the docstring. [Before] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Args: distance: Distance traveled. time: Time spent traveling. Returns: Speed as distance divided by time. Raises: FasterThanLightError: If speed is greater than the speed of light. """ ``` [After] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Args: distance: Distance traveled. time: Time spent traveling. Returns: Speed as distance divided by time. Raises: FasterThanLightError: If speed is greater than the speed of light. """ ```',610'D413': 'Add missing blank lines after the last section of the docstring for consistency. [Before] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Parameters ---------- distance : float Distance traveled. time : float Time spent traveling. Returns ------- float Speed as distance divided by time. Raises ------ FasterThanLightError If speed is greater than the speed of light. """ ``` [After] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Parameters ---------- distance : float Distance traveled. time : float Time spent traveling. Returns ------- float Speed as distance divided by time. Raises ------ FasterThanLightError If speed is greater than the speed of light. """ ```',611'D414': 'Add a description to the empty "Raises" section in the docstring. [Before] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Parameters ---------- distance : float Distance traveled. time : float Time spent traveling. Returns ------- float Speed as distance divided by time. Raises ------ """ ``` [After] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Parameters ---------- distance : float Distance traveled. time : float Time spent traveling. Returns ------- float Speed as distance divided by time. Raises ------ FasterThanLightError If speed is greater than the speed of light. """ ```',612'D415': 'Add a period at the end of the first line of the docstring for grammatical correctness. [Before] ```python def average(values: list[float]) -> float: """Return the mean of the given values""" ``` [After] ```python def average(values: list[float]) -> float: """Return the mean of the given values.""" ```',613'D416': 'Add colons to section headers in the docstring to comply with Google-style conventions. [Before] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Args distance: Distance traveled. time: Time spent traveling. Returns Speed as distance divided by time. Raises FasterThanLightError: If speed is greater than the speed of light. """ ``` [After] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Args: distance: Distance traveled. time: Time spent traveling. Returns: Speed as distance divided by time. Raises: FasterThanLightError: If speed is greater than the speed of light. """ ```',614'D417': 'Add missing parameter documentation in the function docstring. [Before] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Args: distance: Distance traveled. Returns: Speed as distance divided by time. Raises: FasterThanLightError: If speed is greater than the speed of light. """ ``` [After] ```python def calculate_speed(distance: float, time: float) -> float: """Calculate speed as distance divided by time. Args: distance: Distance traveled. time: Time spent traveling. Returns: Speed as distance divided by time. Raises: FasterThanLightError: If speed is greater than the speed of light. """ ```',615'D418': 'Remove docstrings from `@overload` function definitions to adhere to best practices. [Before] ```python from typing import overload @overload def factorial(n: int) -> int: """Return the factorial of n.""" @overload def factorial(n: float) -> float: """Return the factorial of n.""" def factorial(n): """Return the factorial of n.""" ``` [After] ```python from typing import overload @overload def factorial(n: int) -> int: ... @overload def factorial(n: float) -> float: ... def factorial(n): """Return the factorial of n.""" ```',616'D419': 'Replace the empty docstring with a meaningful description of the function\'s purpose. [Before] ```python def average(values: list[float]) -> float: """""" ``` [After] ```python def average(values: list[float]) -> float: """Return the mean of the given values.""" ```',617'F401': 'Remove unused import to improve code clarity and performance. [Before] ```python import numpy as np # unused import def area(radius): return 3.14 * radius**2 ``` [After] ```python def area(radius): return 3.14 * radius**2 ```',618'F402': 'Rename the loop variable to avoid shadowing the imported binding. [Before] ```python from os import path for path in files: print(path) ``` [After] ```python from os import path for filename in files: print(filename) ```',619'F403': 'Replace wildcard imports with explicit imports to improve code clarity and maintainability. [Before] ```python from math import * def area(radius): return pi * radius**2 ``` [After] ```python from math import pi def area(radius): return pi * radius**2 ```',620'F404': 'Move `__future__` imports to the top of the file to avoid `SyntaxError`. [Before] ```python from pathlib import Path from __future__ import annotations ``` [After] ```python from __future__ import annotations from pathlib import Path ```',621'F405': 'Replace the wildcard import with explicit imports to clarify which symbols are being used. [Before] ```python from math import * def area(radius): return pi * radius**2 ``` [After] ```python from math import pi def area(radius): return pi * radius**2 ```',622'F406': 'Move the wildcard import to the top-level of the module to avoid shadowing local variables. [Before] ```python def foo(): from math import * ``` [After] ```python from math import * def foo(): ... ```',623'F407': 'Ensure that only valid `__future__` imports are used based on the current Python version. [Before] ```python from __future__ import annotations, division, print_function ``` [After] ```python from __future__ import annotations, print_function # division is not needed in Python 3.x ``` In Python 3.x, `division` is the default behavior, so it should not be imported from `__future__`.',624'F501': 'The original code uses an incomplete format string that lacks a valid conversion specifier. [Before] [python] ```python "Hello, %" % "world" ``` [After] [python] ```python "Hello, %s" % "world" ```',625'F502': 'Use a dictionary for named placeholders in `printf`-style format strings to avoid `TypeError`. [Before] ```python "%(greeting)s, %(name)s" % ("Hello", "World") ``` [After] ```python "%(greeting)s, %(name)s" % {"greeting": "Hello", "name": "World"} ```',626'F503': 'Use named placeholders in `printf`-style format strings when passing mapping-type values to avoid `TypeError`. [Before] ```python "%s, %s" % {"greeting": "Hello", "name": "World"} ``` [After] ```python "%(greeting)s, %(name)s" % {"greeting": "Hello", "name": "World"} ```',627'F504': 'Remove unused mapping keys from the format string. [Before] ```python "Hello, %(name)s" % {"greeting": "Hello", "name": "World"} ``` [After] ```python "Hello, %(name)s" % {"name": "World"} ```',628'F505': 'Use `str.format()` or f-strings for safer string formatting to avoid `KeyError`. [Before] ```python "%(greeting)s, %(name)s" % {"name": "world"} ``` [After] ```python "Hello, {name}".format(name="world") ```',629'F506': 'Replace mixed positional and named placeholders with either all positional or all named placeholders. [Before] ```python "%s, %(name)s" % ("Hello", {"name": "World"}) ``` [After] ```python "%(greeting)s, %(name)s" % {"greeting": "Hello", "name": "World"} ```',630'F507': 'Remove the extra substitution value to match the number of placeholders in the format string. [Before] ```python "%s, %s" % ("Hello", "world", "!") ``` [After] ```python "%s, %s" % ("Hello", "world") ```',631'F508': 'Replace the dictionary with a tuple to avoid `TypeError` when using the `*` specifier. [Before] ```python from math import pi "%(n).*f" % {"n": (2, pi)} ``` [After] ```python from math import pi "%.*f" % (2, pi) # 3.14 ```',632'F509': 'Replace invalid format specifiers with valid ones to avoid runtime errors. [Before] ```python "Hello, %S" % "world" ``` [After] ```python "Hello, %s" % "world" ```',633'F521': 'The original code uses an invalid format string that lacks a closing brace. [Before] ```python "{".format(foo) ``` [After] ```python "{}".format(foo) ```',634'F522': 'Remove unused keyword arguments from `str.format` calls to avoid redundancy. [Before] ```python "Hello, {name}".format(greeting="Hello", name="World") ``` [After] ```python "Hello, {name}".format(name="World") ```',635'F523': 'Remove unused positional arguments from `str.format` calls to avoid redundancy. [Before] ```python "Hello, {0}".format("world", "!") ``` [After] ```python "Hello, {0}".format("world") ```',636'F524': 'Add missing argument for the placeholder in the `str.format` call. [Before] ```python "{greeting}, {name}".format(name="World") ``` [After] ```python "{greeting}, {name}".format(greeting="Hello", name="World") ```',637'F525': 'Replace the mixed numbering in the `str.format` call to avoid `ValueError`. [Before] ```python "{0}, {}".format("Hello", "World") ``` [After] ```python "{0}, {1}".format("Hello", "World") ``` This change ensures that all placeholders are consistently numbered, preventing runtime errors.',638'F541': 'Replace unnecessary f-strings without placeholders with regular strings for clarity. [Before] ```python f"Hello, world!" ``` [After] ```python "Hello, world!" ```',639'F601': 'Remove duplicate keys in the dictionary to ensure each key is unique. [Before] ```python foo = { "bar": 1, "baz": 2, "baz": 3, } foo["baz"] # 3 ``` [After] ```python foo = { "bar": 1, "baz": 2, } foo["baz"] # 2 ```',640'F602': 'Remove duplicate keys to ensure each key in the dictionary is unique. [Before] ```python foo = { bar: 1, baz: 2, baz: 3, } ``` [After] ```python foo = { bar: 1, baz: 2, } ``` This fix ensures that the dictionary maintains unique keys, preventing unintended overwriting of values.',641'F621': 'The code should limit the number of expressions in starred assignment statements to comply with Python\'s unpacking rules. [Before] ```python a, *b, c, *d = range(10) # Too many starred expressions ``` [After] ```python a, *b, c = range(10) # Fixed to comply with unpacking rules ```',642'F622': 'Remove the extra starred expression to avoid `SyntaxError`. [Before] ```python *foo, *bar, baz = (1, 2, 3) ``` [After] ```python *foo, baz = (1, 2, 3) ``` This fix ensures that only one starred expression is used in the assignment, complying with Python\'s syntax rules for unpacking.',643'F631': 'Replace non-empty tuple in `assert` statement with the actual condition to ensure proper assertion behavior. [Before] ```python assert (some_condition,) ``` [After] ```python assert some_condition ```',644'F632': 'Replace `is` with `==` for value comparison. [Before] ```python x = 200 if x is 200: print("It\'s 200!") ``` [After] ```python x = 200 if x == 200: print("It\'s 200!") ```',645'F633': 'Replace the outdated `print >>` syntax with the modern `print` function using the `file` keyword argument. [Before] ```python from __future__ import print_function import sys print >> sys.stderr, "Hello, world!" ``` [After] ```python import sys print("Hello, world!", file=sys.stderr) ```',646'F634': 'Replace the non-empty tuple condition with a direct boolean expression to avoid unintended behavior. [Before] ```python if (False,): print("This will always run") ``` [After] ```python if False: print("This will never run") ```',647'F701': 'The `break` statement must be placed inside a loop to avoid a `SyntaxError`. [Before] ```python def foo(): break ``` [After] ```python def foo(): for _ in range(1): # Example loop break ```',648'F702': 'The `continue` statement should be placed inside a loop to avoid a `SyntaxError`. [Before] ```python def foo(): continue # SyntaxError ``` [After] ```python def foo(): for i in range(5): continue # Correct usage inside a loop ```',649'F704': '`yield` and `await` should be used inside a function or method to avoid `SyntaxError`. [Before] ```python class Foo: yield 1 ``` [After] ```python def foo(): yield 1 ``` This change encapsulates the `yield` statement within a function, adhering to Python\'s syntax rules.',650'F706': 'Remove the `return` statement from the class body, as it is not allowed outside of a function. [Before] ```python class Foo: return 1 ``` [After] ```python class Foo: pass # Use \'pass\' or define methods instead ```',651'F707': 'The order of `except` blocks should be adjusted to ensure that the more specific exceptions are handled before the general exception. [Before] ```python def reciprocal(n): try: reciprocal = 1 / n except: print("An exception occurred.") except ZeroDivisionError: print("Cannot divide by zero.") else: return reciprocal ``` [After] ```python def reciprocal(n): try: reciprocal = 1 / n except ZeroDivisionError: print("Cannot divide by zero.") except: print("An exception occurred.") else: return reciprocal ```',652'F722': 'Use a valid type hint instead of an invalid string literal. [Before] ```python def foo() -> "/": ... ``` [After] ```python def foo() -> str: ... ``` This change replaces the invalid string literal with a valid type hint (`str`), ensuring proper type checking and avoiding potential errors.',653'F811': 'Remove redundant import statements to avoid shadowing unused variables. [Before] ```python import foo import bar import foo # Redefinition of unused `foo` from line 1 ``` [After] ```python import foo import bar ```',654'F821': 'Define the parameter `n` in the function to avoid `NameError`. [Before] ```python def double(): return n * 2 # raises `NameError` if `n` is undefined when `double` is called ``` [After] ```python def double(n): return n * 2 ```',655'F822': 'Undefined names in `__all__` should be defined in the module to avoid `NameError`. [Before] ```python from foo import bar __all__ = ["bar", "baz"] # undefined name `baz` in `__all__` ``` [After] ```python from foo import bar, baz __all__ = ["bar", "baz"] ```',656'F823': 'The error occurs because the local variable `x` is referenced before assignment. To fix this, declare `x` as a global variable within the function. [Before] ```python x = 1 def foo(): x += 1 ``` [After] ```python x = 1 def foo(): global x x += 1 ```',657'F841': 'Remove the unused variable `y` to clean up the function. [Before] ```python def foo(): x = 1 y = 2 return x ``` [After] ```python def foo(): x = 1 return x ```',658'F842': 'Remove the unused variable annotation to clean up the code. [Before] ```python def foo(): bar: int ``` [After] ```python def foo(): pass # No unused variables ```',659'F901': 'Replace `NotImplemented` with `NotImplementedError` to correctly indicate an unimplemented method. [Before] ```python class Foo: def bar(self): raise NotImplemented ``` [After] ```python class Foo: def bar(self): raise NotImplementedError ```',660'PGH001': 'Replace the use of `eval()` with a safer alternative to prevent arbitrary code execution. [Before] ```python def foo(): x = eval(input("Enter a number: ")) ... ``` [After] ```python def foo(): x = input("Enter a number: ") ... ```',661'PGH002': 'Replace the deprecated `warn` method with the recommended `warning` method in the logging module. [Before] ```python import logging def foo(): logging.warn("Something happened") ``` [After] ```python import logging def foo(): logging.warning("Something happened") ```',662'PGH003': 'Replace blanket `type: ignore` annotations with specific error codes to improve code clarity and maintainability. [Before] ```python from foo import secrets # type: ignore ``` [After] ```python from foo import secrets # type: ignore[attr-defined] ```',663'PGH004': 'Change blanket `noqa` annotations to specify the exact diagnostics being suppressed. [Before] ```python from .base import * # noqa ``` [After] ```python from .base import * # noqa: F403 ```',664'PGH005': 'Ensure that mock assertions are called as methods with parentheses. [Before] ```python my_mock.assert_called ``` [After] ```python my_mock.assert_called() ``` This fix adds parentheses to the assertion call, correctly invoking the method to check if the mock was called.',665'PLC0105': 'Rename type variables to follow PEP 484 naming conventions for covariance and contravariance. [Before] ```python from typing import TypeVar T = TypeVar("T", covariant=True) U = TypeVar("U", contravariant=True) V_co = TypeVar("V_co") ``` [After] ```python from typing import TypeVar T_co = TypeVar("T_co", covariant=True) U_contra = TypeVar("U_contra", contravariant=True) V = TypeVar("V") ```',666'PLC0131': 'Change the definition of `TypeVar` to avoid using both covariant and contravariant at the same time. [Before] ```python from typing import TypeVar T = TypeVar("T", covariant=True, contravariant=True) ``` [After] ```python from typing import TypeVar T_co = TypeVar("T_co", covariant=True) T_contra = TypeVar("T_contra", contravariant=True) ```',667'PLC0132': 'The name provided to the `TypeVar` constructor should match the variable name. [Before] ```python from typing import TypeVar T = TypeVar("U") ``` [After] ```python from typing import TypeVar T = TypeVar("T") ```',668'PLC0205': 'Change the assignment of `__slots__` from a string to a tuple to avoid confusion when iterating. [Before] ```python class Person: __slots__: str = "name" def __init__(self, name: str) -> None: self.name = name ``` [After] ```python class Person: __slots__: tuple[str, ...] = ("name",) def __init__(self, name: str) -> None: self.name = name ```',669'PLC0206': 'Use `.items()` for clearer and more efficient dictionary iteration. [Before] ```python ORCHESTRA = { "violin": "strings", "oboe": "woodwind", "tuba": "brass", "gong": "percussion", } for instrument in ORCHESTRA: print(f"{instrument}: {ORCHESTRA[instrument]}") ``` [After] ```python ORCHESTRA = { "violin": "strings", "oboe": "woodwind", "tuba": "brass", "gong": "percussion", } for instrument, section in ORCHESTRA.items(): print(f"{instrument}: {section}") ```',670'PLC0208': 'Replace the `set` literal with a `tuple` or `list` for more efficient iteration. [Before] ```python for number in {1, 2, 3}: ... ``` [After] ```python for number in (1, 2, 3): ... ```',671'PLC0414': 'Remove redundant import alias to improve code clarity. [Before] ```python import numpy as numpy ``` [After] ```python import numpy as np ``` or ```python import numpy ```',672'PLC0415': 'Move the `import` statement to the top-level scope of the module to comply with PEP 8 guidelines. [Before] ```python def print_python_version(): import platform print(python.python_version()) ``` [After] ```python import platform def print_python_version(): print(platform.python_version()) ```',673'PLC1802': 'Replace calls to `len()` in boolean contexts with direct truthiness checks. [Before] ```python fruits = ["orange", "apple"] vegetables = [] if len(fruits): print(fruits) if not len(vegetables): print(vegetables) ``` [After] ```python fruits = ["orange", "apple"] if fruits: print(fruits) if not vegetables: print(vegetables) ```',674'PLC1901': 'Replace the comparison to an empty string with a truthy check to improve code clarity and correctness. [Before] ```python x: str = ... if x == "": print("x is empty") ``` [After] ```python x: str = ... if not x: print("x is empty") ```',675'PLC2401': 'Replace non-ASCII characters in variable names with ASCII equivalents for better compatibility. [Before] ```python \u251c\u00edpple_count: int ``` [After] ```python apple_count: int ```',676'PLC2403': 'Replace non-ASCII characters in import statements with ASCII equivalents to avoid compatibility issues. [Before] ```python import b\u251c\u00edr ``` [After] ```python import bar ```',677'PLC2701': 'Replace the private import with a public API import to adhere to PEP 8 guidelines. [Before] ```python from foo import _bar ``` [After] ```python from foo import bar # Assuming \'bar\' is the public API equivalent of \'_bar\' ```',678'PLC2801': 'Replace explicit calls to dunder methods with their built-in equivalents or operators for better readability and adherence to Python best practices. [Before] ```python three = (3.0).__str__() twelve = "1".__add__("2") def is_greater_than_two(x: int) -> bool: return x.__gt__(2) ``` [After] ```python three = str(3.0) twelve = "1" + "2" def is_greater_than_two(x: int) -> bool: return x > 2 ```',679'PLC3002': 'Replace unnecessary direct calls to lambda expressions with inline calculations for improved readability. [Before] ```python area = (lambda r: 3.14 * r**2)(radius) ``` [After] ```python area = 3.14 * radius**2 ```',680'PLE0100': 'The `__init__` method should not use `yield` or `yield from`. Instead, assign values to instance variables directly. [Before] ```python class InitIsGenerator: def __init__(self, i): yield i ``` [After] ```python class InitIsGenerator: def __init__(self, i): self.value = i ```',681'PLE0101': 'Remove the return statement from the `__init__` method to avoid runtime errors. [Before] ```python class Example: def __init__(self): return [] ``` [After] ```python class Example: def __init__(self): self.value = [] ```',682'PLE0115': 'Remove the `nonlocal` declaration to avoid the `SyntaxError` since a variable cannot be both `nonlocal` and `global`. [Before] ```python counter = 0 def increment(): global counter nonlocal counter counter += 1 ``` [After] ```python counter = 0 def increment(): global counter counter += 1 ```',683'PLE0116': 'Replace the `continue` statement in the `finally` block with an appropriate control flow structure to avoid a `SyntaxError`. [Before] ```python while True: try: pass finally: continue ``` [After] ```python while True: try: pass except Exception: pass else: continue ```',684'PLE0117': 'Bind the `nonlocal` variable in the outer function to avoid `SyntaxError`. [Before] ```python def foo(): def get_bar(self): nonlocal bar ... ``` [After] ```python def foo(): bar = 1 def get_bar(self): nonlocal bar ... ```',685'PLE0118': 'Declare the `global` variable before using it in the function to avoid `SyntaxError`. [Before] ```python counter = 1 def increment(): print(f"Adding 1 to {counter}") global counter counter += 1 ``` [After] ```python counter = 1 def increment(): global counter print(f"Adding 1 to {counter}") counter += 1 ```',686'PLE0237': 'Add the `surname` attribute to the `__slots__` declaration to avoid `AttributeError`. [Before] ```python class Student: __slots__ = ("name",) def __init__(self, name, surname): self.name = name self.surname = surname # [assigning-non-slot] self.setup() def setup(self): pass ``` [After] ```python class Student: __slots__ = ("name", "surname") def __init__(self, name, surname): self.name = name self.surname = surname self.setup() def setup(self): pass ```',687'PLE0241': 'Remove duplicate base classes to prevent `TypeError` at runtime. [Before] ```python class Foo: pass class Bar(Foo, Foo): pass ``` [After] ```python class Foo: pass class Bar(Foo): pass ```',688'PLE0302': 'The `__len__` method should not accept any parameters other than `self`. [Before] ```python class Bookshelf: def __init__(self): self._books = ["Foo", "Bar", "Baz"] def __len__(self, index): # __len__ does not except an index parameter return len(self._books) def __getitem__(self, index): return self._books[index] ``` [After] ```python class Bookshelf: def __init__(self): self._books = ["Foo", "Bar", "Baz"] def __len__(self): return len(self._books) def __getitem__(self, index): return self._books[index] ```',689'PLE0303': 'Change the return type of the `__len__` method to a non-negative integer. [Before] ```python class Foo: def __len__(self): return "2" ``` [After] ```python class Foo: def __len__(self): return 2 ```',690'PLE0304': 'Ensure the `__bool__` method returns a `bool` type. [Before] ```python class Foo: def __bool__(self): return 2 ``` [After] ```python class Foo: def __bool__(self): return True # or return False, depending on the desired truthiness ```',691'PLE0305': 'Change the return type of the `__index__` method to an integer. [Before] ```python class Foo: def __index__(self): return "2" ``` [After] ```python class Foo: def __index__(self): return 2 ```',692'PLE0307': 'The `__str__` method should return a string instead of a boolean. [Before] ```python class Foo: def __str__(self): return True ``` [After] ```python class Foo: def __str__(self): return "Foo" ```',693'PLE0308': 'The `__bytes__` method should return a `bytes` object instead of an integer. [Before] ```python class Foo: def __bytes__(self): return 2 ``` [After] ```python class Foo: def __bytes__(self): return b"2" ```',694'PLE0309': 'Change the return type of the `__hash__` method to an integer. [Before] ```python class Foo: def __hash__(self): return "2" ``` [After] ```python class Foo: def __hash__(self): return 2 ```',695'PLE0604': 'Replace invalid objects in `__all__` with a list of strings representing public symbols. [Before] ```python __all__ = [Foo, 1, None] ``` [After] ```python __all__ = ["Foo", "Bar", "Baz"] ``` This change ensures that `__all__` contains only strings, which is the correct format for defining public symbols in a module.',696'PLE0605': 'Change the assignment of `__all__` to a tuple or list of strings to ensure it adheres to best practices. [Before] ```python __all__ = "Foo" ``` [After] ```python __all__ = ("Foo",) ```',697'PLE0643': 'Change the hard-coded index to a valid index within the bounds of the list. [Before] ```python print([0, 1, 2][3]) ``` [After] ```python print([0, 1, 2][2]) ``` This fix ensures that the index used to access the list is within its valid range, preventing an `IndexError`.',698'PLE0704': 'Replace the bare `raise` statement with a specific exception to provide clarity and avoid errors. [Before] ```python from typing import Any def is_some(obj: Any) -> bool: if obj is None: raise ``` [After] ```python from typing import Any def is_some(obj: Any) -> bool: if obj is None: raise ValueError("`obj` cannot be `None`") ```',699'PLE1132': 'Remove the duplicate keyword argument to avoid the exception. [Before] ```python func(1, 2, c=3, **{"c": 4}) ``` [After] ```python func(1, 2, c=4) ``` This fix eliminates the duplicate keyword argument `c`, ensuring the function call adheres to Python\'s rules regarding keyword arguments.',700'PLE1141': 'Use `.items()` to correctly iterate over key-value pairs in a dictionary. [Before] ```python data = {"Paris": 2_165_423, "New York City": 8_804_190, "Tokyo": 13_988_129} for city, population in data: print(f"{city} has population {population}.") ``` [After] ```python data = {"Paris": 2_165_423, "New York City": 8_804_190, "Tokyo": 13_988_129} for city, population in data.items(): print(f"{city} has population {population}.") ```',701'PLE1142': 'The function `foo` should be defined as `async` to use `await` correctly. [Before] ```python import asyncio def foo(): await asyncio.sleep(1) ``` [After] ```python import asyncio async def foo(): await asyncio.sleep(1) ```',702'PLE1205': 'The original logging statement incorrectly includes an extra argument, leading to a `TypeError`. [Before] ```python import logging try: function() except Exception as e: logging.error("Error occurred: %s", type(e), e) raise ``` [After] ```python import logging try: function() except Exception as e: logging.error("%s error occurred: %s", type(e), e) raise ```',703'PLE1206': 'The logging format string requires the type of the exception to be included as a separate argument to avoid a `TypeError`. [Before] ```python import logging try: function() except Exception as e: logging.error("%s error occurred: %s", e) raise ``` [After] ```python import logging try: function() except Exception as e: logging.error("%s error occurred: %s", type(e), e) raise ```',704'PLE1300': 'Replace the unsupported format type `z` with a valid one, such as `s` for string. [Before] ```python # `z` is not a valid format type. print("%z" % "1") print("{:z}".format("1")) ``` [After] ```python # Use \'s\' for string formatting. print("%s" % "1") print("{:s}".format("1")) ```',705'PLE1307': 'Use the correct type for the format specifier to avoid runtime errors. [Before] ```python print("%d" % "1") ``` [After] ```python print("%d" % 1) ```',706'PLE1310': 'Use `str.removeprefix` and `str.removesuffix` instead of `str.strip` to avoid redundant character removal. [Before] ```python # Evaluates to "foo". "bar foo baz".strip("bar baz ") ``` [After] ```python # Evaluates to "foo". "bar foo baz".removeprefix("bar ").removesuffix(" baz") ```',707'PLE1507': 'Ensure the `key` argument in `os.getenv` is a string to avoid `TypeError`. [Before] ```python os.getenv(1) ``` [After] ```python os.getenv("1") ```',708'PLE1519': 'Replace `@singledispatch` with `@singledispatchmethod` for method decoration. [Before] ```python from functools import singledispatch class Class: @singledispatch def method(self, arg): ... ``` [After] ```python from functools import singledispatchmethod class Class: @singledispatchmethod def method(self, arg): ... ```',709'PLE1520': 'Replace `@singledispatchmethod` with `@singledispatch` for non-method functions. [Before] ```python from functools import singledispatchmethod @singledispatchmethod def func(arg): ... ``` [After] ```python from functools import singledispatch @singledispatch def func(arg): ... ```',710'PLE1700': 'Replace `yield from` with an `async for` loop to avoid `SyntaxError` in async functions. [Before] [python] ```python async def numbers(): yield from [1, 2, 3, 4, 5] ``` [After] [python] ```python async def numbers(): async for number in [1, 2, 3, 4, 5]: yield number ```',711'PLE2502': 'Remove bidirectional characters to avoid potential obfuscation and security issues. [Before] ```python s = "\u256b\u00c9" * 100 # "\u256b\u00c9" is assigned print(s) # prints a 100-character string ``` [After] ```python s = "AB" * 100 # Use simple ASCII characters instead print(s) # prints a 200-character string ```',712'PLE2510': 'Replace the control character `BS` with the escape sequence `\\b` for consistent rendering across text editors. [Before] ```python x = "" ``` [After] ```python x = "\\b" ```',713'PLE2512': 'Replace the raw control character `SUB` with its hexadecimal escape sequence `\\x1A` for consistent visibility across editors. [Before] ```python x = "" ``` [After] ```python x = "\\x1A" ```',714'PLE2513': 'Replace the raw control character `ESC` with its escape sequence `\\x1B` for consistent rendering across editors. [Before] ```python x = "" ``` [After] ```python x = "\\x1b" ```',715'PLE2514': 'Replace the empty string with a string containing the `NUL` character to ensure consistent rendering across editors. [Before] ```python x = "" ``` [After] ```python x = "\\0" ```',716'PLE2515': 'Replace the zero width space character with its Unicode escape sequence for better visibility in all editors. [Before] ```python x = "Dear Sir/Madam" ``` [After] ```python x = "Dear Sir\\u200b/\\u200bMadam" # zero width space ```',717'PLE4703': 'Iterate over a copy of the `set` to avoid modifying it during iteration. [Before] ```python nums = {1, 2, 3} for num in nums: nums.add(num + 5) ``` [After] ```python nums = {1, 2, 3} for num in nums.copy(): nums.add(num + 5) ```',718'PLR0124': 'Replace self-comparison with `math.isnan` for checking NaN values. [Before] ```python foo == foo ``` [After] ```python import math math.isnan(foo) ```',719'PLR0133': 'Replace redundant constant comparison with its boolean result. [Before] ```python foo = 1 == 1 ``` [After] ```python foo = True ```',720'PLR0202': 'Use the `@classmethod` decorator for better readability and consistency. [Before] ```python class Foo: def bar(cls): ... bar = classmethod(bar) ``` [After] ```python class Foo: @classmethod def bar(cls): ... ```',721'PLR0203': 'Use the `@staticmethod` decorator for clarity and consistency. [Before] ```python class Foo: def bar(arg1, arg2): ... bar = staticmethod(bar) ``` [After] ```python class Foo: @staticmethod def bar(arg1, arg2): ... ```',722'PLR0206': 'Remove parameters from the property method definition to adhere to best practices. [Before] ```python class Cat: @property def purr(self, volume): ... ``` [After] ```python class Cat: @property def purr(self): ... def purr_volume(self, volume): ... ```',723'PLR0402': 'Replace the alias import with a direct submodule import for better readability. [Before] ```python import concurrent.futures as futures ``` [After] ```python from concurrent import futures ```',724'PLR0904': 'Refactor the `Linter` class to reduce the number of public methods by delegating functionality to separate classes. [Before] ```python class Linter: def __init__(self): pass def pylint(self): pass def pylint_settings(self): pass def flake8(self): pass def flake8_settings(self): pass def pydocstyle(self): pass def pydocstyle_settings(self): pass ``` [After] ```python class Linter: def __init__(self): self.pylint = Pylint() self.flake8 = Flake8() self.pydocstyle = Pydocstyle() def lint(self): pass class Pylint: def lint(self): pass def settings(self): pass class Flake8: def lint(self): pass def settings(self): pass class Pydocstyle: def lint(self): pass def settings(self): pass ```',725'PLR0911': 'Reduce the number of return statements by using a dictionary to map countries to their capitals. [Before] ```python def capital(country: str) -> str | None: if country == "England": return "London" elif country == "France": return "Paris" elif country == "Poland": return "Warsaw" elif country == "Romania": return "Bucharest" elif country == "Spain": return "Madrid" elif country == "Thailand": return "Bangkok" else: return None ``` [After] ```python def capital(country: str) -> str | None: capitals = { "England": "London", "France": "Paris", "Poland": "Warsaw", "Romania": "Bucharest", "Spain": "Madrid", "Thailand": "Bangkok", } return capitals.get(country) ```',726'PLR0912': 'Reduce the number of branches in the `grades_to_average_number` function by using dictionaries for grade values and modifiers, and streamline the logic. [Before] ```python def grades_to_average_number(grades): numbers = [] for grade in grades: # 1st branch if len(grade) not in {1, 2}: raise ValueError(f"Invalid grade: {grade}") if len(grade) == 2 and grade[1] not in {"+", "-"}: raise ValueError(f"Invalid grade: {grade}") letter = grade[0] if letter in {"F", "E"}: number = 0.0 elif letter == "D": number = 1.0 elif letter == "C": number = 2.0 elif letter == "B": number = 3.0 elif letter == "A": number = 4.0 else: raise ValueError(f"Invalid grade: {grade}") modifier = 0.0 if letter != "F" and grade[-1] == "+": modifier = 0.3 elif letter != "F" and grade[-1] == "-": modifier = -0.3 numbers.append(max(0.0, min(number + modifier, 4.0))) try: return sum(numbers) / len(numbers) except ZeroDivisionError: # 13th branch return 0 ``` [After] ```python def grades_to_average_number(grades): grade_values = {"F": 0.0, "E": 0.0, "D": 1.0, "C": 2.0, "B": 3.0, "A": 4.0} modifier_values = {"+": 0.3, "-": -0.3} numbers = [] for grade in grades: if len(grade) not in {1, 2} or (len(grade) == 2 and grade[1] not in modifier_values): raise ValueError(f"Invalid grade: {grade}") letter = grade[0] if letter not in grade_values: raise ValueError(f"Invalid grade: {grade}") number = grade_values[letter] modifier = modifier_values.get(grade[-1], 0.0) numbers.append(max(0.0, min(number + modifier, 4.0))) return sum(numbers) / len(numbers) if numbers else 0 ```',727'PLR0913': 'Refactor the function to reduce the number of arguments by using a `NamedTuple` to group related parameters. [Before] ```python def calculate_position(x_pos, y_pos, z_pos, x_vel, y_vel, z_vel, time): new_x = x_pos + x_vel * time new_y = y_pos + y_vel * time new_z = z_pos + z_vel * time return new_x, new_y, new_z ``` [After] ```python from typing import NamedTuple class Vector(NamedTuple): x: float y: float z: float def calculate_position(pos: Vector, vel: Vector, time: float) -> Vector: return Vector(*(p + v * time for p, v in zip(pos, vel))) ```',728'PLR0914': 'Refactor functions with too many local variables into smaller, more manageable functions. [Before] ```python def complex_function(): a = 1 b = 2 c = 3 d = 4 e = 5 f = 6 g = 7 h = 8 i = 9 j = 10 k = 11 l = 12 m = 13 n = 14 o = 15 # More logic here ``` [After] ```python def simple_function_part1(): a = 1 b = 2 # Logic for part 1 def simple_function_part2(): c = 3 d = 4 # Logic for part 2 def complex_function(): simple_function_part1() simple_function_part2() # Combine results if necessary ```',729'PLR0915': 'Refactor the function to simplify its logic and reduce the number of statements. [Before] ```python def is_even(number: int) -> bool: if number == 0: return True elif number == 1: return False elif number == 2: return True elif number == 3: return False elif number == 4: return True elif number == 5: return False else: ... ``` [After] ```python def is_even(number: int) -> bool: return number % 2 == 0 ```',730'PLR0916': 'Refactor the `if` statement to reduce the number of Boolean expressions for better readability. [Before] ```python if a and b and c and d and e and f and g and h: ... ``` [After] ```python conditions_met = a and b and c and d and e and f and g and h if conditions_met: ... ``` This change assigns the result of the Boolean expression to a variable, improving clarity and maintainability.',731'PLR0917': 'Refactor the function to use keyword-only arguments for better clarity and maintainability. [Before] ```python def plot(x, y, z, color, mark, add_trendline): ... plot(1, 2, 3, "r", "*", True) ``` [After] ```python def plot(x, y, z, *, color, mark, add_trendline): ... plot(1, 2, 3, color="r", mark="*", add_trendline=True) ```',732'PLR1701': 'Combine repeated `isinstance` calls into a single call for better readability and performance. [Before] ```python def is_number(x): return isinstance(x, int) or isinstance(x, float) or isinstance(x, complex) ``` [After] ```python def is_number(x): return isinstance(x, (int, float, complex)) ```',733'PLR1702': `The code does not include an implementation for checking nested blocks; you need to add a function to analyze the nesting level. [Before] [python] def check_nested_blocks(func): # Placeholder for checking nested blocks pass [After] [python] def check_nested_blocks(func): max_nesting = 5 nesting_level = 0 for line in func.__code__.co_lines: if line.startswith('if') or line.startswith('for') or line.startswith('while'): nesting_level += 1 if nesting_level > max_nesting: raise ValueError("Too many nested blocks") elif line.strip() == '': nesting_level = max(0, nesting_level - 1) # Decrease nesting on empty lines return True # If within limits`,734'PLR1704': 'Rename the loop variable to avoid shadowing the function parameter. [Before] ```python def show(host_id=10.11): for host_id, host in [[12.13, "Venus"], [14.15, "Mars"]]: print(host_id, host) ``` [After] ```python def show(host_id=10.11): for inner_host_id, host in [[12.13, "Venus"], [14.15, "Mars"]]: print(host_id, inner_host_id, host) ```',735'PLR1706': 'Replace the outdated ternary syntax using `and` and `or` with the modern if-expression for clarity and explicitness. [Before] ```python x, y = 1, 2 maximum = x >= y and x or y ``` [After] ```python x, y = 1, 2 maximum = x if x >= y else y ```',736'PLR1711': 'Remove unnecessary `return None` statements from functions that do not have other return statements. [Before] ```python def f(): print(5) return None ``` [After] ```python def f(): print(5) ```',737'PLR1714': 'Replace multiple equality comparisons with a membership test using the `in` operator for better readability and performance. [Before] ```python foo == "bar" or foo == "baz" or foo == "qux" ``` [After] ```python foo in {"bar", "baz", "qux"} ```',738'PLR1716': 'Simplify chained boolean operations for improved readability. [Before] ```python a = int(input()) b = int(input()) c = int(input()) if a < b and b < c: pass ``` [After] ```python a = int(input()) b = int(input()) c = int(input()) if a < b < c: pass ```',739'PLR1722': 'Replace `exit()` with `sys.exit()` to avoid potential `NameError` and ensure compatibility in all contexts. [Before] ```python if __name__ == "__main__": exit() ``` [After] ```python import sys if __name__ == "__main__": sys.exit() ```',740'PLR1730': 'Replace `if` statements that determine the maximum value with a `max()` function for improved readability. [Before] ```python if score > highest_score: highest_score = score ``` [After] ```python highest_score = max(highest_score, score) ```',741'PLR1733': 'Replace unnecessary key-based access with direct use of the value from the iteration. [Before] ```python FRUITS = {"apple": 1, "orange": 10, "berry": 22} for fruit_name, fruit_count in FRUITS.items(): print(FRUITS[fruit_name]) ``` [After] ```python FRUITS = {"apple": 1, "orange": 10, "berry": 22} for fruit_name, fruit_count in FRUITS.items(): print(fruit_count) ```',742'PLR1736': 'Remove unnecessary index-based access during `enumerate` iterations. [Before] ```python letters = ["a", "b", "c"] for index, letter in enumerate(letters): print(letters[index]) ``` [After] ```python letters = ["a", "b", "c"] for index, letter in enumerate(letters): print(letter) ```',743'PLR2004': 'Replace the unnamed constant in the comparison with a named constant for better readability and maintainability. [Before] ```python def apply_discount(price: float) -> float: if price <= 100: return price / 2 else: return price ``` [After] ```python MAX_DISCOUNT = 100 def apply_discount(price: float) -> float: if price <= MAX_DISCOUNT: return price / 2 else: return price ```',744'PLR2044': 'Remove unnecessary inline comments that do not provide any information. [Before] ```python class Foo: # pass ``` [After] ```python class Foo: pass ```',745'PLR5501': 'Replace nested `if` statements within an `else` block with `elif` to improve readability and reduce indentation. [Before] ```python def check_sign(value: int) -> None: if value > 0: print("Number is positive.") else: if value < 0: print("Number is negative.") else: print("Number is zero.") ``` [After] ```python def check_sign(value: int) -> None: if value > 0: print("Number is positive.") elif value < 0: print("Number is negative.") else: print("Number is zero.") ```',746'PLR6104': 'Replace standard assignment with augmented assignment where applicable for conciseness. [Before] ```python x = x + 1 ``` [After] ```python x += 1 ```',747'PLR6201': 'Replace membership tests on `list` or `tuple` literals with `set` literals for optimized performance. [Before] ```python 1 in [1, 2, 3] ``` [After] ```python 1 in {1, 2, 3} ```',748'PLR6301': 'Remove the unused `self` parameter from the method definition to improve code clarity and maintainability. [Before] ```python class Person: def greeting(self): print("Greetings friend!") ``` [After] ```python def greeting(): print("Greetings friend!") ``` or ```python class Person: @staticmethod def greeting(): print("Greetings friend!") ```',749'PLW0108': 'Replace the lambda function that directly calls another function with the function itself to reduce indirection. [Before] ```python df.apply(lambda x: str(x)) ``` [After] ```python df.apply(str) ```',750'PLW0120': 'Remove the redundant `else` clause from the loop since it always terminates normally. [Before] ```python for item in items: print(item) else: print("All items printed") ``` [After] ```python for item in items: print(item) print("All items printed") ```',751'PLW0127': 'Remove the self-assignment to avoid redundancy. [Before] ```python country = "Poland" country = country ``` [After] ```python country = "Poland" ```',752'PLW0128': 'Remove redundant assignments to the same variable in tuple unpacking. [Before] ```python a, b, a = (1, 2, 3) print(a) # 3 ``` [After] ```python _, b, a = (1, 2, 3) print(a) # 3 ``` This change eliminates the redundancy by using an underscore to ignore the first value, ensuring clarity in the assignment.',753'PLW0129': 'Replace the string literal in the `assert` statement with a boolean expression to ensure proper functionality. [Before] ```python assert "always true" ``` [After] ```python assert True # or replace with a meaningful condition ```',754'PLW0131': 'Replace named expression with a regular assignment for clarity. [Before] ```python (a := 42) ``` [After] ```python a = 42 ```',755'PLW0133': 'Replace the instantiation of the exception with a raise statement to ensure the exception is actually raised. [Before] ```python ValueError("...") ``` [After] ```python raise ValueError("...") ```',756'PLW0177': 'Replace direct comparison with NaN using `math.isnan()` for accurate checks. [Before] ```python if x == float("NaN"): pass ``` [After] ```python import math if math.isnan(x): pass ```',757'PLW0211': 'Change the first argument of the static method from `self` to a more appropriate name to avoid confusion. [Before] ```python class Wolf: @staticmethod def eat(self): pass ``` [After] ```python class Wolf: @staticmethod def eat(sheep): pass ```',758'PLW0244': 'Redefining a slot in a subclass can lead to inaccessible instance variables. Instead, use a tuple to extend the base class slots without redefining them. [Before] ```python class Base: __slots__ = ("a", "b") class Subclass(Base): __slots__ = ("a", "d") # slot "a" redefined ``` [After] ```python class Base: __slots__ = ("a", "b") class Subclass(Base): __slots__ = Base.__slots__ + ("d",) # extend slots without redefining ```',759'PLW0245': 'Use parentheses with `super` to correctly call the superclass method. [Before] ```python class Animal: @staticmethod def speak(): return "This animal says something." class Dog(Animal): @staticmethod def speak(): original_speak = super.speak() # ERROR: `super.speak()` return f"{original_speak} But as a dog, it barks!" ``` [After] ```python class Animal: @staticmethod def speak(): return "This animal says something." class Dog(Animal): @staticmethod def speak(): original_speak = super().speak() # Correct: `super().speak()` return f"{original_speak} But as a dog, it barks!" ```',760'PLW0406': 'Remove the self-import statement to avoid circular dependency. [Before] ```python # file: this_file.py from this_file import foo def foo(): ... ``` [After] ```python # file: this_file.py def foo(): ... ```',761'PLW0602': 'Remove unnecessary use of the `global` keyword when the variable is not modified. [Before] ```python DEBUG = True def foo(): global DEBUG if DEBUG: print("foo() called") ... ``` [After] ```python DEBUG = True def foo(): if DEBUG: print("foo() called") ... ```',762'PLW0603': 'Replace the use of `global` with a return value to avoid mutable global state. [Before] ```python var = 1 def foo(): global var # [global-statement] var = 10 print(var) foo() print(var) ``` [After] ```python var = 1 def foo(): print(var) return 10 var = foo() print(var) ```',763'PLW0604': 'Remove the use of the `global` keyword at the module level, as it is unnecessary. [Before] ```python global my_variable my_variable = 10 ``` [After] ```python my_variable = 10 ```',764'PLW0642': 'Avoid reassigning `self` and `cls` in methods to maintain clarity and adhere to conventions. [Before] ```python class Version: def add(self, other): self = self + other return self @classmethod def superclass(cls): cls = cls.__mro__[-1] return cls ``` [After] ```python class Version: def add(self, other): new_version = self + other return new_version @classmethod def superclass(cls): supercls = cls.__mro__[-1] return supercls ```',765'PLW0711': 'Replace the use of a binary operation in the `except` clause with a tuple to correctly catch multiple exceptions. [Before] ```python try: pass except A or B: pass ``` [After] ```python try: pass except (A, B): pass ```',766'PLW1501': 'The mode string in the `open` function should only contain valid characters and combinations. [Before] ```python with open("file", "rwx") as f: return f.read() ``` [After] ```python with open("file", "r") as f: return f.read() ``` This change corrects the mode from an invalid combination (`rwx`) to a valid one (`r`), ensuring the file is opened in read-only mode.',767'PLW1507': 'Use `os.environ.copy()` instead of `copy.copy(os.environ)` to avoid mutating the original `os.environ`. [Before] ```python import copy import os env = copy.copy(os.environ) ``` [After] ```python import os env = os.environ.copy() ```',768'PLW1508': 'Change the default value in `os.getenv` to a string to ensure consistent return types. [Before] ```python import os int(os.getenv("FOO", 1)) ``` [After] ```python import os int(os.getenv("FOO", "1")) ```',769'PLW1509': 'Replace the use of `preexec_fn` in `subprocess.Popen` with safer alternatives like `start_new_session` and `process_group`. [Before] ```python import os, subprocess subprocess.Popen(foo, preexec_fn=os.setsid) subprocess.Popen(bar, preexec_fn=os.setpgid(0, 0)) ``` [After] ```python import subprocess subprocess.Popen(foo, start_new_session=True) subprocess.Popen(bar, process_group=0) # Introduced in Python 3.11 ```',770'PLW1510': 'Add the `check` argument to `subprocess.run` to ensure proper error handling. [Before] ```python import subprocess subprocess.run(["ls", "nonexistent"]) # No exception raised. ``` [After] ```python import subprocess subprocess.run(["ls", "nonexistent"], check=True) # Raises exception. ```',771'PLW1514': 'Add an explicit `encoding` argument to the `open` function to ensure consistent behavior across platforms. [Before] ```python open("file.txt") ``` [After] ```python open("file.txt", encoding="utf-8") ```',772'PLW1641': 'Implement `__hash__` in the `Developer` class to ensure it remains hashable. [Before] ```python class Developer(Person): def __init__(self): super().__init__() self.language = "python" def __eq__(self, other): return ( super().__eq__(other) and isinstance(other, Developer) and self.language == other.language ) hash(Developer()) # TypeError: unhashable type: \'Developer\' ``` [After] ```python class Developer(Person): def __init__(self): super().__init__() self.language = "python" def __eq__(self, other): return ( super().__eq__(other) and isinstance(other, Developer) and self.language == other.language ) def __hash__(self): return hash((super().__hash__(), self.language)) ```',773'PLW2101': 'Assign the lock to a variable outside the `with` statement to ensure it can be shared between threads. [Before] ```python import threading counter = 0 def increment(): global counter with threading.Lock(): counter += 1 ``` [After] ```python import threading counter = 0 lock = threading.Lock() def increment(): global counter with lock: counter += 1 ```',774'PLW2901': 'Avoid reusing variable names in nested loops and `with` statements to prevent unintended overwriting of variables. [Before] ```python for i in range(10): i = 9 print(i) # prints 9 every iteration for i in range(10): for i in range(10): # original value overwritten pass print(i) # also prints 9 every iteration with path1.open() as f: with path2.open() as f: f = path2.open() print(f.readline()) # prints a line from path2 ``` [After] ```python for i in range(10): j = 9 # changed variable name print(j) # prints 9 every iteration for i in range(10): for j in range(10): # changed variable name pass print(i) # prints original i value with path1.open() as f1: # changed variable name with path2.open() as f2: # changed variable name f2 = path2.open() print(f1.readline()) # prints a line from path1 ```',775'PLW3201': 'The constructor method `__init__` is incorrectly defined with a single underscore instead of double underscores. [Before] ```python class Foo: def __init_(self): ... ``` [After] ```python class Foo: def __init__(self): ... ``` This fix corrects the method name to `__init__`, which is the proper dunder method for initializing instances in Python.',776'PLW3301': 'Flatten nested `min` and `max` calls for improved readability. [Before] ```python minimum = min(1, 2, min(3, 4, 5)) maximum = max(1, 2, max(3, 4, 5)) diff = maximum - minimum ``` [After] ```python minimum = min(1, 2, 3, 4, 5) maximum = max(1, 2, 3, 4, 5) diff = maximum - minimum ```',777'UP001': 'Remove the unnecessary `__metaclass__` declaration in class definitions. [Before] ```python class Foo: __metaclass__ = type ``` [After] ```python class Foo: ... ```',778'UP003': 'Replace the use of `type()` with the corresponding built-in type for clarity and conciseness. [Before] ```python type(1) ``` [After] ```python int ```',779'UP004': 'Remove explicit inheritance from `object` in class definitions. [Before] ```python class Foo(object): ... ``` [After] ```python class Foo: ... ```',780'UP005': 'Replace the deprecated method `assertEquals` with the non-deprecated `assertEqual`. [Before] ```python from unittest import TestCase class SomeTest(TestCase): def test_something(self): self.assertEquals(1, 1) ``` [After] ```python from unittest import TestCase class SomeTest(TestCase): def test_something(self): self.assertEqual(1, 1) ```',781'UP006': 'Replace `typing.List` with the built-in `list` for type annotations. [Before] ```python from typing import List foo: List[int] = [1, 2, 3] ``` [After] ```python foo: list[int] = [1, 2, 3] ``` This change utilizes the more concise and readable PEP 585 syntax, which is preferred in Python 3.9 and later.',782'UP007': 'Replace `typing.Union` with the `|` operator for union type annotations. [Before] ```python from typing import Union foo: Union[int, str] = 1 ``` [After] ```python foo: int | str = 1 ```',783'UP008': 'Remove redundant arguments from the `super` call for improved conciseness. [Before] ```python class A: def foo(self): pass class B(A): def bar(self): super(B, self).foo() ``` [After] ```python class A: def foo(self): pass class B(A): def bar(self): super().foo() ```',784'UP009': 'Remove unnecessary UTF-8 encoding declaration as it\'s redundant in Python 3. [Before] ```python # -*- coding: utf-8 -*- print("Hello, world!") ``` [After] ```python print("Hello, world!") ```',785'UP010': 'Remove unnecessary `__future__` import when the feature is already available in the current Python version. [Before] ```python from __future__ import print_function print("Hello, world!") ``` [After] ```python print("Hello, world!") ```',786'UP011': 'Remove unnecessary parentheses from the `functools.lru_cache` decorator. [Before] ```python import functools @functools.lru_cache() def foo(): ... ``` [After] ```python import functools @functools.lru_cache def foo(): ... ```',787'UP012': 'Replace unnecessary `encode` calls with bytes literals. [Before] ```python "foo".encode("utf-8") ``` [After] ```python b"foo" ```',788'UP013': 'Replace functional syntax of `TypedDict` with class syntax for better readability. [Before] ```python from typing import TypedDict Foo = TypedDict("Foo", {"a": int, "b": str}) ``` [After] ```python from typing import TypedDict class Foo(TypedDict): a: int b: str ```',789'UP014': 'Replace functional syntax of `NamedTuple` with class syntax for better readability. [Before] ```python from typing import NamedTuple Foo = NamedTuple("Foo", [("a", int), ("b", str)]) ``` [After] ```python from typing import NamedTuple class Foo(NamedTuple): a: int b: str ```',790'UP015': 'Remove redundant `open` mode argument for clarity. [Before] ```python with open("foo.txt", "r") as f: ... ``` [After] ```python with open("foo.txt") as f: ... ```',791'UP017': 'Replace `datetime.timezone.utc` with `datetime.UTC` for improved readability. [Before] ```python import datetime datetime.timezone.utc ``` [After] ```python import datetime datetime.UTC ```',792'UP018': 'Replace unnecessary constructor calls with their respective literal forms for improved readability. [Before] ```python str("foo") int(42) float(3.14) bool(False) ``` [After] ```python "foo" 42 3.14 False ```',793'UP019': 'Replace `typing.Text` with `str` to avoid using deprecated types. [Before] ```python from typing import Text foo: Text = "bar" ``` [After] ```python foo: str = "bar" ```',794'UP020': 'Replace `io.open` with `open` for idiomatic Python 3 code. [Before] ```python import io with io.open("file.txt") as f: ... ``` [After] ```python with open("file.txt") as f: ... ```',795'UP021': 'Replace the deprecated `universal_newlines` argument with `text` in `subprocess.run`. [Before] ```python import subprocess subprocess.run(["foo"], universal_newlines=True) ``` [After] ```python import subprocess subprocess.run(["foo"], text=True) ```',796'UP022': 'Replace `stdout` and `stderr` with `capture_output` for better readability. [Before] ```python import subprocess subprocess.run(["foo"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) ``` [After] ```python import subprocess subprocess.run(["foo"], capture_output=True) ```',797'UP023': 'Replace the deprecated `cElementTree` import with `ElementTree` for compatibility with Python 3.3 and later. [Before] ```python from xml.etree import cElementTree ``` [After] ```python from xml.etree import ElementTree ```',798'UP024': 'Replace the use of `IOError` with `OSError` for better compatibility and idiomatic code. [Before] ```python raise IOError ``` [After] ```python raise OSError ```',799'UP025': 'Remove the unnecessary Unicode prefix `u` from string literals in Python 3. [Before] ```python u"foo" ``` [After] ```python "foo" ```',800'UP026': 'Replace the deprecated `mock` import with `unittest.mock` for compatibility with Python 3.3 and later. [Before] ```python import mock ``` [After] ```python from unittest import mock ```',801'UP027': 'Replace the list comprehension with a generator expression to avoid unnecessary list allocation. [Before] ```python a, b, c = [foo(x) for x in items] ``` [After] ```python a, b, c = (foo(x) for x in items) ```',802'UP028': 'Replace `for` loops that yield values with `yield from` for conciseness. [Before] ```python for x in foo: yield x ``` [After] ```python yield from foo ```',803'UP029': 'Remove unnecessary import of builtins to avoid confusion. [Before] ```python from builtins import str str(1) ``` [After] ```python str(1) ```',804'UP030': 'Replace explicit positional indices in format strings with implicit ones for improved readability. [Before] ```python "{0}, {1}".format("Hello", "World") # "Hello, World" ``` [After] ```python "{}, {}".format("Hello", "World") # "Hello, World" ```',805'UP031': 'Replace `printf`-style string formatting with `str.format` or f-strings for better readability and safety. [Before] ```python "%s, %s" % ("Hello", "World") # "Hello, World" ``` [After] ```python "{}, {}".format("Hello", "World") # "Hello, World" ``` [Before] ```python "%s" % val ``` [After] ```python "{}".format(val) # Use with caution, ensure val is not ambiguous ```',806'UP032': 'Replace `str.format` calls with f-strings for improved readability. [Before] ```python "{}".format(foo) ``` [After] ```python f"{foo}" ```',807'UP033': 'Replace `functools.lru_cache(maxsize=None)` with `functools.cache` for improved readability and idiomatic usage in Python 3.9 and later. [Before] ```python import functools @functools.lru_cache(maxsize=None) def foo(): ... ``` [After] ```python import functools @functools.cache def foo(): ... ```',808'UP034': 'Remove unnecessary parentheses to enhance code readability. [Before] ```python print(("Hello, world")) ``` [After] ```python print("Hello, world") ```',809'UP035': 'Replace deprecated imports from `collections` with their updated equivalents from `collections.abc`. [Before] ```python from collections import Sequence ``` [After] ```python from collections.abc import Sequence ```',810'UP036': 'Remove outdated conditional blocks that check for Python versions older than the minimum supported version. [Before] ```python import sys if sys.version_info < (3, 0): print("py2") else: print("py3") ``` [After] ```python print("py3") ```',811'UP037': 'Remove unnecessary quotes from type annotations when using `from __future__ import annotations`. [Before] ```python from __future__ import annotations def foo(bar: "Bar") -> "Bar": ... ``` [After] ```python from __future__ import annotations def foo(bar: Bar) -> Bar: ... ``` [Before] ```python def foo() -> None: bar: "Bar" ``` [After] ```python def foo() -> None: bar: Bar ```',812'UP038': 'Replace tuple type checks with union type checks for `isinstance` and `issubclass` to improve code clarity and performance. [Before] ```python isinstance(x, (int, float)) ``` [After] ```python isinstance(x, int | float) ```',813'UP039': 'Remove unnecessary parentheses from class definitions that do not have any base classes. [Before] [python] ```python class Foo(): ... ``` [After] [python] ```python class Foo: ... ```',814'UP040': 'Replace `TypeAlias` and `TypeAliasType` with the new `type` keyword for defining type aliases in Python 3.12. [Before] ```python ListOfInt: TypeAlias = list[int] PositiveInt = TypeAliasType("PositiveInt", Annotated[int, Gt(0)]) ``` [After] ```python type ListOfInt = list[int] type PositiveInt = Annotated[int, Gt(0)] ```',815'UP041': 'Replace the use of `asyncio.TimeoutError` with the built-in `TimeoutError` for better compatibility and future-proofing. [Before] ```python raise asyncio.TimeoutError ``` [After] ```python raise TimeoutError ```',816'UP042': 'Replace inheritance from both `str` and `enum.Enum` with `enum.StrEnum` to align with Python 3.11 best practices. [Before] ```python import enum class Foo(str, enum.Enum): ... ``` [After] ```python import enum class Foo(enum.StrEnum): ... ```',817'UP043': 'Remove unnecessary default type arguments from `Generator` and `AsyncGenerator` type annotations. [Before] ```python from collections.abc import Generator, AsyncGenerator def sync_gen() -> Generator[int, None, None]: yield 42 async def async_gen() -> AsyncGenerator[int, None]: yield 42 ``` [After] ```python from collections.abc import Generator, AsyncGenerator def sync_gen() -> Generator[int]: yield 42 async def async_gen() -> AsyncGenerator[int]: yield 42 ```',818'UP044': 'Replace `Unpack[]` with the `*` operator for unpacking in function signatures. [Before] ```python from typing import Unpack def foo(*args: Unpack[tuple[int, ...]]) -> None: pass ``` [After] ```python def foo(*args: *tuple[int, ...]) -> None: pass ```',819'UP045': 'Replace `typing.Optional` with the new union type syntax using `|`. [Before] ```python from typing import Optional foo: Optional[int] = None ``` [After] ```python foo: int | None = None ```',820'UP046': 'Replace standalone `TypeVar` declarations with inline type parameters in generic class definitions. [Before] ```python from typing import TypeVar T = TypeVar("T") class GenericClass(Generic[T]): var: T ``` [After] ```python class GenericClass[T]: var: T ``` This change utilizes the new PEP 695 syntax for defining generic classes, improving readability and maintaining cleaner support for generics.',821'UP047': 'Replace standalone `TypeVar` with inline type parameters for better readability and compliance with PEP 695. [Before] ```python from typing import TypeVar T = TypeVar("T") def generic_function(var: T) -> T: return var ``` [After] ```python def generic_function[T](var: T) -> T: return var ```',822'UP049': 'Remove leading underscores from PEP 695 type parameters for better readability. [Before] ```python class GenericClass[_T]: var: _T def generic_function[_T](var: _T) -> list[_T]: return var[0] ``` [After] ```python class GenericClass[T]: var: T def generic_function[T](var: T) -> list[T]: return var[0] ```',823'FURB101': 'Replace `open` and `read` with `pathlib` methods for simplicity. [Before] ```python with open(filename) as f: contents = f.read() ``` [After] ```python from pathlib import Path contents = Path(filename).read_text() ```',824'FURB103': 'Replace `open` and `write` with `Path.write_text` for simplicity. [Before] ```python with open(filename, "w") as f: f.write(contents) ``` [After] ```python from pathlib import Path Path(filename).write_text(contents) ```',825'FURB105': 'Remove unnecessary empty string from `print` call. [Before] ```python print("") ``` [After] ```python print() ```',826'FURB110': 'Replace ternary `if` expressions with the `or` operator for brevity, ensuring no side effects are present. [Before] ```python z = x if x else y ``` [After] ```python z = x or y ```',827'FURB113': 'Replace consecutive `append` calls with a single `extend` call for better efficiency. [Before] ```python nums = [1, 2, 3] nums.append(4) nums.append(5) nums.append(6) ``` [After] ```python nums = [1, 2, 3] nums.extend((4, 5, 6)) ```',828'FURB116': 'Replace the use of `bin(...)[2:]` with an f-string for better readability. [Before] ```python print(bin(1337)[2:]) ``` [After] ```python print(f"{1337:b}") ```',829'FURB118': 'Replace the lambda function with the corresponding function from the `operator` module for clarity and conciseness. [Before] ```python import functools nums = [1, 2, 3] total = functools.reduce(lambda x, y: x + y, nums) ``` [After] ```python import functools import operator nums = [1, 2, 3] total = functools.reduce(operator.add, nums) ```',830'FURB122': 'Replace the use of `IOBase.write` in a loop with `IOBase.writelines` for better performance and idiomatic code. [Before] ```python with Path("file").open("w") as f: for line in lines: f.write(line) with Path("file").open("wb") as f: for line in lines: f.write(line.encode()) ``` [After] ```python with Path("file").open("w") as f: f.writelines(lines) with Path("file").open("wb") as f: f.writelines(line.encode() for line in lines) ```',831'FURB129': 'Replace the use of `readlines()` with direct iteration over the file object for better performance and simplicity. [Before] ```python with open("file.txt") as fp: for line in fp.readlines(): ... ``` [After] ```python with open("file.txt") as fp: for line in fp: ... ```',832'FURB131': 'Replace `del` statements that clear lists or dictionaries with the `clear()` method for better performance and readability. [Before] ```python names = {"key": "value"} nums = [1, 2, 3] del names[:] del nums[:] ``` [After] ```python names = {"key": "value"} nums = [1, 2, 3] names.clear() nums.clear() ```',833'FURB132': 'Replace `set.remove` with `set.discard` for more idiomatic code. [Before] ```python nums = {123, 456} if 123 in nums: nums.remove(123) ``` [After] ```python nums = {123, 456} nums.discard(123) ```',834'FURB136': 'Replace `if` expressions that determine the minimum or maximum of two values with `min()` or `max()` functions for improved readability. [Before] ```python highest_score = score1 if score1 > score2 else score2 ``` [After] ```python highest_score = max(score1, score2) ```',835'FURB140': 'Replace generator expression with `itertools.starmap` for improved readability and efficiency. [Before] ```python all(predicate(a, b) for a, b in some_iterable) ``` [After] ```python from itertools import starmap all(starmap(predicate, some_iterable)) ```',836'FURB142': 'Replace individual `.add()` and `.discard()` calls with `update()` and `difference_update()` for better performance and readability. [Before] ```python s = set() for x in (1, 2, 3): s.add(x) for x in (1, 2, 3): s.discard(x) ``` [After] ```python s = set() s.update((1, 2, 3)) s.difference_update((1, 2, 3)) ```',837'FURB145': 'Replace the unbounded slice expression with the `list.copy()` method for better readability and consistency. [Before] ```python a = [1, 2, 3] b = a[:] ``` [After] ```python a = [1, 2, 3] b = a.copy() ```',838'FURB148': 'Replace `enumerate` with direct iteration for better clarity and efficiency when only the index or value is needed. [Before] ```python for index, _ in enumerate(sequence): print(index) for _, value in enumerate(sequence): print(value) ``` [After] ```python for index in range(len(sequence)): print(index) for value in sequence: print(value) ```',839'FURB152': 'Replace hard-coded mathematical constants with the corresponding constants from the `math` module for better readability and precision. [Before] ```python A = 3.141592 * r**2 ``` [After] ```python import math A = math.pi * r**2 ```',840'FURB154': 'Combine multiple `global` statements into a single statement for better readability and conciseness. [Before] ```python def func(): global x global y print(x, y) ``` [After] ```python def func(): global x, y print(x, y) ```',841'FURB156': 'Replace hardcoded character sets with constants from the `string` module for improved readability and maintainability. [Before] ```python x = "0123456789" y in "abcdefghijklmnopqrstuvwxyz" ``` [After] ```python import string x = string.digits y in string.ascii_lowercase ```',842'FURB157': 'Remove unnecessary string or float casts when using the `Decimal` constructor for better readability. [Before] ```python Decimal("0") Decimal(float("Infinity")) ``` [After] ```python Decimal(0) Decimal("Infinity") ```',843'FURB161': 'Replace `bin(...).count("1")` with the more efficient `bit_count()` method introduced in Python 3.10. [Before] ```python x = bin(123).count("1") y = bin(0b1111011).count("1") ``` [After] ```python x = (123).bit_count() y = 0b1111011.bit_count() ```',844'FURB162': 'Remove unnecessary replacements of `Z` in ISO 8601 date strings when using `datetime.fromisoformat()`. [Before] ```python from datetime import datetime date = "2025-01-01T00:00:00Z" datetime.fromisoformat(date.replace("Z", "+00:00")) datetime.fromisoformat(date[:-1] + "-00") datetime.fromisoformat(date.strip("Z", "-0000")) datetime.fromisoformat(date.rstrip("Z", "-00:00")) ``` [After] ```python from datetime import datetime date = "2025-01-01T00:00:00Z" datetime.fromisoformat(date) ```',845'FURB163': 'Remove redundant base in `math.log` calls and use dedicated logarithm functions. [Before] ```python import math math.log(4, math.e) math.log(4, 2) math.log(4, 10) ``` [After] ```python import math math.log(4) math.log2(4) math.log10(4) ```',846'FURB164': 'Replace unnecessary `from_float` and `from_decimal` method calls with direct constructor usage for `Decimal` and `Fraction`. [Before] ```python Decimal.from_float(4.2) Decimal.from_float(float("inf")) Fraction.from_float(4.2) Fraction.from_decimal(Decimal("4.2")) ``` [After] ```python Decimal(4.2) Decimal("inf") Fraction(4.2) Fraction(Decimal(4.2)) ```',847'FURB166': 'Replace explicit base handling with automatic base deduction using `int(num, 0)`. [Before] ```python num = "0xABC" if num.startswith("0b"): i = int(num[2:], 2) elif num.startswith("0o"): i = int(num[2:], 8) elif num.startswith("0x"): i = int(num[2:], 16) print(i) ``` [After] ```python num = "0xABC" i = int(num, 0) print(i) ```',848'FURB167': 'Replace shorthand regex flag `re.I` with the more descriptive `re.IGNORECASE` for better readability. [Before] ```python import re if re.match("^hello", "hello world", re.I): ... ``` [After] ```python import re if re.match("^hello", "hello world", re.IGNORECASE): ... ```',849'FURB168': 'Replace `isinstance(obj, type(None))` with `obj is None` for better readability and efficiency. [Before] ```python isinstance(obj, type(None)) ``` [After] ```python obj is None ```',850'FURB169': 'Replace `type(obj) is type(None)` with `obj is None` for better readability and efficiency. [Before] ```python type(obj) is type(None) ``` [After] ```python obj is None ```',851'FURB171': 'Replace membership tests against single-item containers with direct comparisons for improved readability and efficiency. [Before] ```python 1 in [1] ``` [After] ```python 1 == 1 ```',852'FURB177': 'Use `Path.cwd()` for clarity when obtaining the current directory. [Before] ```python cwd = Path().resolve() ``` [After] ```python cwd = Path.cwd() ```',853'FURB180': 'Replace the use of `metaclass=abc.ABCMeta` with inheritance from `ABC` for defining abstract base classes. [Before] ```python class C(metaclass=ABCMeta): pass ``` [After] ```python class C(ABC): pass ```',854'FURB181': 'Use `.hexdigest()` instead of `.digest().hex()` for better readability and conciseness. [Before] ```python from hashlib import sha512 hashed = sha512(b"some data").digest().hex() ``` [After] ```python from hashlib import sha512 hashed = sha512(b"some data").hexdigest() ```',855'FURB187': 'Use the `.reverse()` method for in-place reversal to improve efficiency and avoid creating unnecessary copies of the list. [Before] ```python l = [1, 2, 3] l = reversed(l) l = [1, 2, 3] l = list(reversed(l)) l = [1, 2, 3] l = l[::-1] ``` [After] ```python l = [1, 2, 3] l.reverse() ```',856'FURB188': 'Replace conditional slicing with `str.removeprefix()` and `str.removesuffix()` for improved readability and efficiency. [Before] ```python def example(filename: str, text: str): filename = filename[:-4] if filename.endswith(".txt") else filename if text.startswith("pre"): text = text[3:] ``` [After] ```python def example(filename: str, text: str): filename = filename.removesuffix(".txt") text = text.removeprefix("pre") ```',857'FURB189': 'Replace direct subclassing of `dict`, `list`, or `str` with `UserDict`, `UserList`, and `UserString` from the `collections` module to avoid potential issues. [Before] ```python class CaseInsensitiveDict(dict): ... ``` [After] ```python from collections import UserDict class CaseInsensitiveDict(UserDict): ... ```',858'FURB192': 'Replace `sorted()` with `min()` and `max()` for better efficiency and readability. [Before] ```python nums = [3, 1, 4, 1, 5] lowest = sorted(nums)[0] highest = sorted(nums)[-1] highest = sorted(nums, reverse=True)[0] ``` [After] ```python nums = [3, 1, 4, 1, 5] lowest = min(nums) highest = max(nums) ```',859'RUF001': 'Replace ambiguous Unicode characters with their ASCII equivalents for clarity. [Before] ```python print("\u256c\u00f9ello, world!") # "\u256c\u00f9" is the Greek eta (`U+0397`). ``` [After] ```python print("Hello, world!") # "H" is the Latin capital H (`U+0048`). ```',860'RUF002': 'Replace ambiguous Unicode characters in the docstring with their ASCII equivalents for clarity. [Before] ```python """A lovely docstring (with a `U+FF09` parenthesis\u2229\u255d\u00eb.""" ``` [After] ```python """A lovely docstring (with no strange parentheses).""" ```',861'RUF003': 'Replace ambiguous Unicode characters in comments with their preferred ASCII equivalents. [Before] ```python foo() # n\u2568\u255bqa # "\u2568\u255b" is Cyrillic (`U+043E`) ``` [After] ```python foo() # noqa # "o" is Latin (`U+006F`) ```',862'RUF005': 'Replace the `+` operator with the unpacking operator `*` for better performance and readability when concatenating collections. [Before] ```python foo = [2, 3, 4] bar = [1] + foo + [5, 6] ``` [After] ```python foo = [2, 3, 4] bar = [1, *foo, 5, 6] ```',863'RUF006': 'Store the task returned by `asyncio.create_task` in a variable or collection to prevent it from being garbage collected. [Before] ```python import asyncio for i in range(10): asyncio.create_task(some_coro(param=i)) ``` [After] ```python import asyncio background_tasks = set() for i in range(10): task = asyncio.create_task(some_coro(param=i)) background_tasks.add(task) task.add_done_callback(background_tasks.discard) ```',864'RUF007': 'Replace `zip()` with `itertools.pairwise()` for better readability and intent clarity. [Before] ```python letters = "ABCD" zip(letters, letters[1:]) # ("A", "B"), ("B", "C"), ("C", "D") ``` [After] ```python from itertools import pairwise letters = "ABCD" pairwise(letters) # ("A", "B"), ("B", "C"), ("C", "D") ```',865'RUF008': 'Use `field(default_factory=...)` to avoid mutable default values in dataclass attributes. [Before] ```python from dataclasses import dataclass @dataclass class A: mutable_default: list[int] = [] ``` [After] ```python from dataclasses import dataclass, field @dataclass class A: mutable_default: list[int] = field(default_factory=list) ```',866'RUF009': 'Replace direct function call in dataclass attribute default with `field(default_factory=...)` to avoid shared mutable state. [Before] ```python from dataclasses import dataclass def simple_list() -> list[int]: return [1, 2, 3, 4] @dataclass class A: mutable_default: list[int] = simple_list() ``` [After] ```python from dataclasses import dataclass, field def creating_list() -> list[int]: return [1, 2, 3, 4] @dataclass class A: mutable_default: list[int] = field(default_factory=creating_list) ```',867'RUF010': 'Replace explicit type conversions in f-strings with dedicated conversion flags for better readability and idiomatic usage. [Before] ```python a = "some string" f"{repr(a)}" ``` [After] ```python a = "some string" f"{a!r}" ```',868'RUF011': 'Replace the static key in the dictionary comprehension with a dynamic key to avoid creating a dictionary with only one key. [Before] ```python data = ["some", "Data"] {"key": value.upper() for value in data} ``` [After] ```python data = ["some", "Data"] {value: value.upper() for value in data} ```',869'RUF012': 'Change mutable default values in class attributes to be initialized in `__init__` to avoid shared state across instances. [Before] ```python class A: variable_1: list[int] = [] variable_2: set[int] = set() variable_3: dict[str, int] = {} ``` [After] ```python class A: def __init__(self) -> None: self.variable_1: list[int] = [] self.variable_2: set[int] = set() self.variable_3: dict[str, int] = {} ```',870'RUF013': 'Use `Optional` or `T | None` for type annotations instead of implicit `Optional`. [Before] ```python def foo(arg: int = None): pass ``` [After] ```python from typing import Optional def foo(arg: Optional[int] = None): pass ``` Or for Python 3.10 and later: ```python def foo(arg: int | None = None): pass ```',871'RUF015': 'Replace eager list or tuple indexing with lazy evaluation using `next(iter(...))` to improve performance and memory usage. [Before] ```python head = list(x)[0] head = [x * x for x in range(10)][0] ``` [After] ```python head = next(iter(x)) head = next(x * x for x in range(10)) ```',872'RUF016': 'Replace the invalid index type with a valid integer index. [Before] ```python var = [1, 2, 3]["x"] ``` [After] ```python var = [1, 2, 3][0] ```',873'RUF017': 'Replace the use of `sum()` for flattening lists with `functools.reduce` to improve performance. [Before] ```python lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] joined = sum(lists, []) ``` [After] ```python import functools import operator lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] joined = functools.reduce(operator.iadd, lists, []) ```',874'RUF018': 'Replace named assignment expressions in `assert` statements with standard assignments to avoid issues when running Python with the `-O` flag. [Before] ```python assert (x := 0) == 0 print(x) ``` [After] ```python x = 0 assert x == 0 print(x) ```',875'RUF019': 'Replace unnecessary key checks with the `get` method for cleaner code. [Before] ```python if "key" in dct and dct["key"]: ... ``` [After] ```python if dct.get("key"): ... ```',876'RUF020': 'Remove `typing.Never` from the union type to avoid redundancy. [Before] ```python from typing import Never def func() -> Never | int: ... ``` [After] ```python def func() -> int: ... ```',877'RUF021': 'Add parentheses to clarify the order of operations in chained logical expressions. [Before] ```python a, b, c = 1, 0, 2 x = a or b and c d, e, f = 0, 1, 2 y = d and e or f ``` [After] ```python a, b, c = 1, 0, 2 x = a or (b and c) d, e, f = 0, 1, 2 y = (d and e) or f ```',878'RUF022': 'Reorder the `__all__` list according to isort-style sorting conventions. [Before] ```python import sys __all__ = [ "b", "c", "a", ] if sys.platform == "win32": __all__ += ["z", "y"] ``` [After] ```python import sys __all__ = [ "a", "b", "c", ] if sys.platform == "win32": __all__ += ["y", "z"] ```',879'RUF023': 'Ensure `__slots__` are defined in natural sort order for consistency and readability. [Before] ```python class Dog: __slots__ = "name", "breed" ``` [After] ```python class Dog: __slots__ = "breed", "name" ```',880'RUF024': 'Use a dictionary comprehension instead of `dict.fromkeys` to avoid shared mutable objects. [Before] ```python cities = dict.fromkeys(["UK", "Poland"], []) cities["UK"].append("London") cities["Poland"].append("Poznan") print(cities) # {\'UK\': [\'London\', \'Poznan\'], \'Poland\': [\'London\', \'Poznan\']} ``` [After] ```python cities = {country: [] for country in ["UK", "Poland"]} cities["UK"].append("London") cities["Poland"].append("Poznan") print(cities) # {\'UK\': [\'London\'], \'Poland\': [\'Poznan\']} ```',881'RUF026': 'Change the `default_factory` keyword argument to a positional argument when initializing a `defaultdict`. [Before] ```python defaultdict(default_factory=int) defaultdict(default_factory=list) ``` [After] ```python defaultdict(int) defaultdict(list) ```',882'RUF027': 'Add the `f` prefix to the string to enable f-string functionality. [Before] ```python name = "Sarah" day_of_week = "Tuesday" print("Hello {name}! It is {day_of_week} today!") ``` [After] ```python name = "Sarah" day_of_week = "Tuesday" print(f"Hello {name}! It is {day_of_week} today!") ```',883'RUF028': 'Replace incompatible suppression comments with the correct ones for Ruff\'s formatter. [Before] ```python def decorator(): pass @decorator # fmt: off def example(): if True: # fmt: skip expression = [ # fmt: off 1, 2, ] # yapf: disable # fmt: on # yapf: enable ``` [After] ```python def decorator(): pass @decorator # ruff: off def example(): if True: # ruff: skip expression = [ # ruff: off 1, 2, ] # ruff: disable # ruff: on # ruff: enable ``` Replace `# fmt:` and `# yapf:` comments with `# ruff:` to ensure compatibility with Ruff\'s formatter.',884'RUF029': 'Remove the `async` keyword from the function declaration since it does not use `await` or any asynchronous features. [Before] ```python async def foo(): bar() ``` [After] ```python def foo(): bar() ```',885'RUF030': 'Replace the `print` function in the assertion with a string message to ensure the correct error message is raised. [Before] ```python assert False, print("This is a message") ``` [After] ```python assert False, "This is a message" ```',886'RUF031': 'Remove parentheses from tuple subscripts to adhere to the default linting rule. [Before] ```python directions = {(0, 1): "North", (1, 0): "East", (0, -1): "South", (-1, 0): "West"} directions[(0, 1)] ``` [After] ```python directions = {(0, 1): "North", (1, 0): "East", (0, -1): "South", (-1, 0): "West"} directions[0, 1] ```',887'RUF032': 'Replace float literals with string literals when creating `Decimal` instances to ensure precision. [Before] ```python from decimal import Decimal num = Decimal(1.2345) ``` [After] ```python from decimal import Decimal num = Decimal("1.2345") ```',888'RUF033': 'Use `InitVar` for parameters in `__post_init__` to ensure they have default values in the dataclass\'s `__init__` method. [Before] ```python from dataclasses import InitVar, dataclass @dataclass class Foo: bar: InitVar[int] = 0 def __post_init__(self, bar: int = 1, baz: int = 2) -> None: print(bar, baz) foo = Foo() # Prints \'0 2\'. ``` [After] ```python from dataclasses import InitVar, dataclass @dataclass class Foo: bar: InitVar[int] = 1 baz: InitVar[int] = 2 def __post_init__(self, bar: int, baz: int) -> None: print(bar, baz) foo = Foo() # Prints \'1 2\'. ```',889'RUF034': 'Remove the unnecessary `if`-`else` condition that has identical arms for clarity. [Before] ```python foo = x if y else x ``` [After] ```python foo = x ```',890'RUF035': 'Replace direct interpolation of dynamic content in `Markup` with safe formatting to prevent XSS vulnerabilities. [Before] ```python from markupsafe import Markup content = "<script>alert(\'Hello, world!\')</script>" html = Markup(f"<b>{content}</b>") # XSS ``` [After] ```python from markupsafe import Markup content = "<script>alert(\'Hello, world!\')</script>" html = Markup("<b>{}</b>").format(content) # Safe ``` [Before] ```python from markupsafe import Markup lines = [ Markup("<b>heading</b>"), "<script>alert(\'XSS attempt\')</script>", ] html = Markup("<br>".join(lines)) # XSS ``` [After] ```python from markupsafe import Markup lines = [ Markup("<b>heading</b>"), Markup("<script>alert(\'XSS attempt\')</script>"), ] html = Markup("<br>").join(lines) # Safe ```',891'RUF036': 'Reorder type annotations to place `None` at the end of the union for better readability. [Before] ```python def func(arg: None | int): ... ``` [After] ```python def func(arg: int | None): ... ```',892'RUF037': 'Remove unnecessary empty iterable arguments when initializing `collections.deque`. [Before] ```python from collections import deque queue = deque(set()) queue = deque([], 10) ``` [After] ```python from collections import deque queue = deque() queue = deque(maxlen=10) ```',893'RUF038': 'Replace `Literal[True, False]` with `bool` for improved readability and conciseness. [Before] ```python from typing import Literal x: Literal[True, False] y: Literal[True, False, "hello", "world"] ``` [After] ```python from typing import Literal x: bool y: Literal["hello", "world"] | bool ```',894'RUF039': 'Ensure that regular expression functions use raw string literals to avoid double escaping. [Before] ```python re.compile("foo\\\\bar") ``` [After] ```python re.compile(r"foo\\bar") ```',895'RUF040': 'The assert statement should use a comparison operator instead of a comma to avoid incorrect usage of the message argument. [Before] ```python fruits = ["apples", "plums", "pears"] fruits.filter(lambda fruit: fruit.startwith("p")) assert len(fruits), 2 # True unless the list is empty ``` [After] ```python fruits = ["apples", "plums", "pears"] fruits.filter(lambda fruit: fruit.startwith("p")) assert len(fruits) == 2 ```',896'RUF041': 'Replace unnecessary nested `Literal` with a flat `Literal` for better readability. [Before] ```python AllModes = Literal[ Literal["r", "r+"], Literal["w", "w+", "wt", "w+t"], Literal["r+", "r+t"], Literal["a", "a+", "at", "a+t"], ] ``` [After] ```python AllModes = Literal[ "r", "r+", "w", "w+", "wt", "w+t", "r+", "r+t", "a", "a+", "at", "a+t" ] ```',897'RUF043': 'Ensure the `match` argument in `pytest.raises()` is a raw string or properly escaped to avoid unintended regex behavior. [Before] ```python import pytest with pytest.raises(Exception, match="A full sentence."): do_thing_that_raises() ``` [After] ```python import pytest with pytest.raises(Exception, match=r"A full sentence."): do_thing_that_raises() ```',898'RUF045': 'Add type annotations to class variables to avoid TypeError during instantiation. [Before] ```python @dataclass class C: a = 1 b: str = "" C(a = 42) # TypeError: C.__init__() got an unexpected keyword argument \'a\' ``` [After] ```python from typing import ClassVar @dataclass class C: a: ClassVar[int] = 1 b: str = "" ```',899'RUF046': 'Remove unnecessary `int` conversions for values that are already integers, while being cautious with certain functions. [Before] ```python int(len([])) int(round(foo, None)) ``` [After] ```python len([]) round(foo) ```',900'RUF047': 'Remove unnecessary `else` clause containing only `pass`. [Before] ```python if foo: bar() else: pass ``` [After] ```python if foo: bar() ```',901'RUF048': 'Replace the use of `map(int, ...)` with `packaging.version.parse()` to handle non-integer version components correctly. [Before] ```python import matplotlib # `__version__ == "3.9.1.post-1"` in our environment tuple(map(int, matplotlib.__version__.split("."))) ``` [After] ```python import packaging.version as version version.parse(matplotlib.__version__) ```',902'RUF049': 'Remove the `@dataclass` decorator from the enum class definition to avoid unexpected behavior. [Before] ```python from dataclasses import dataclass from enum import Enum @dataclass class E(Enum): ... ``` [After] ```python from enum import Enum class E(Enum): ... ```',903'RUF051': 'Use `.pop(..., None)` for a more concise and safe way to remove a key from a dictionary. [Before] ```python if key in dictionary: del dictionary[key] ``` [After] ```python dictionary.pop(key, None) ```',904'RUF052': 'Rename variables with leading underscores to avoid confusion and adhere to naming conventions. [Before] ```python def function(): _variable = 3 _id = 4 return _variable + _id ``` [After] ```python def function(): variable = 3 id_ = 4 return variable + id_ ```',905'RUF053': 'Remove the inheritance from `Generic` to avoid runtime errors when using type parameter lists. [Before] ```python from typing import Generic, ParamSpec, TypeVar, TypeVarTuple U = TypeVar("U") P = ParamSpec("P") Ts = TypeVarTuple("Ts") class C[T](Generic[U, P, *Ts]): ... ``` [After] ```python from typing import ParamSpec, TypeVar, TypeVarTuple U = TypeVar("U") P = ParamSpec("P") Ts = TypeVarTuple("Ts") class C[T, U, **P, *Ts]: ... ```',906'RUF054': 'Remove form feed characters from the leading whitespace to avoid undefined behavior in indentation calculations. [Before] ```python if foo():\\n \\fbar() ``` [After] ```python if foo():\\n bar() ```',907'RUF055': 'Replace `re.sub` with `str.replace` for simpler and faster string manipulation. [Before] ```python import re s = "abc def abc" result = re.sub("abc", "", s) ``` [After] ```python s = "abc def abc" result = s.replace("abc", "") ```',908'RUF056': 'Remove the unnecessary default value in `dict.get()` when checking for truthiness. [Before] ```python if dict.get(key, False): ... ``` [After] ```python if dict.get(key): ... ```',909'RUF057': 'Replace unnecessary `round()` calls on integer values with the value itself for clarity. [Before] ```python a = round(1, 0) ``` [After] ```python a = 1 ```',910'RUF058': 'Replace `starmap` with `map` when using `zip` to avoid unnecessary unpacking. [Before] ```python from itertools import starmap starmap(func, zip(a, b)) starmap(func, zip(a, b, strict=True)) ``` [After] ```python map(func, a, b) map(func, a, b, strict=True) ```',911'RUF100': 'Remove unnecessary `noqa` directive for unused imports. [Before] ```python import foo # noqa: F401 def bar(): foo.bar() ``` [After] ```python import foo def bar(): foo.bar() ``` The `noqa: F401` directive is unnecessary because the import is used in the function, so it should be removed to maintain clean code.',912'RUF101': 'Replace deprecated rule code with the canonical rule code for better codebase consistency. [Before] ```python x = eval(command) # noqa: PGH001 ``` [After] ```python x = eval(command) # noqa: S307 ```',913'RUF200': 'The authors\' format in `pyproject.toml` should be updated to use a dictionary for each author. [Before] ```toml [project] name = "crab" version = "1.0.0" authors = ["Ferris the Crab <[email protected]>"] ``` [After] ```toml [project] name = "crab" version = "1.0.0" authors = [ { name = "Ferris the Crab", email = "[email protected]" } ] ```',914'TRY002': 'Replace the generic `Exception` with a custom exception to avoid over-capturing unintended exceptions. [Before] ```python def main_function(): if not cond: raise Exception() def consumer_func(): try: do_step() prepare() main_function() except Exception: logger.error("Oops") ``` [After] ```python class CustomException(Exception): pass def main_function(): if not cond: raise CustomException() def consumer_func(): try: do_step() prepare() main_function() except CustomException: logger.error("Main function failed") except Exception: logger.error("Oops") ```',915'TRY003': 'Define the exception message within the exception class to ensure consistency across all instances. [Before] ```python class CantBeNegative(Exception): pass def foo(x): if x < 0: raise CantBeNegative(f"{x} is negative") ``` [After] ```python class CantBeNegative(Exception): def __init__(self, number): super().__init__(f"{number} is negative") def foo(x): if x < 0: raise CantBeNegative(x) ```',916'TRY004': 'Change the exception raised for type checks from `ValueError` to `TypeError` to align with Python\'s best practices. [Before] ```python def foo(n: int): if isinstance(n, int): pass else: raise ValueError("n must be an integer") ``` [After] ```python def foo(n: int): if isinstance(n, int): pass else: raise TypeError("n must be an integer") ```',917'TRY200': 'Add the `from` keyword when re-raising exceptions to maintain the exception context. [Before] ```python def reciprocal(n): try: return 1 / n except ZeroDivisionError: raise ValueError() ``` [After] ```python def reciprocal(n): try: return 1 / n except ZeroDivisionError as exc: raise ValueError() from exc ```',918'TRY201': 'Remove the redundant exception name in the `raise` statement when re-raising an exception. [Before] ```python def foo(): try: ... except ValueError as exc: raise exc ``` [After] ```python def foo(): try: ... except ValueError: raise ```',919'TRY203': 'Remove the unnecessary `try`-`except` block that captures and immediately re-raises the exception. [Before] ```python def foo(): try: bar() except NotImplementedError: raise ``` [After] ```python def foo(): bar() ```',920'TRY300': 'Move the `return` statement to the `else` block to avoid confusion with exception handling. [Before] ```python import logging def reciprocal(n): try: rec = 1 / n print(f"reciprocal of {n} is {rec}") return rec except ZeroDivisionError: logging.exception("Exception occurred") ``` [After] ```python import logging def reciprocal(n): try: rec = 1 / n except ZeroDivisionError: logging.exception("Exception occurred") else: print(f"reciprocal of {n} is {rec}") return rec ```',921'TRY301': 'Refactor the `bar` function to raise the exception directly, eliminating the need for a redundant `try` block in `foo`. [Before] ```python def bar(): pass def foo(): try: a = bar() if not a: raise ValueError except ValueError: raise ``` [After] ```python def bar(): raise ValueError def foo(): a = bar() # refactored `bar` to raise `ValueError` directly ```',922'TRY400': 'Replace `logging.error` with `logging.exception` to include the traceback in the log. [Before] ```python import logging def func(): try: raise NotImplementedError except NotImplementedError: logging.error("Exception occurred") ``` [After] ```python import logging def func(): try: raise NotImplementedError except NotImplementedError: logging.exception("Exception occurred") ```',923'TRY401': 'Remove the redundant exception object from the log message to avoid excessive logging. [Before] ```python try: ... except ValueError as e: logger.exception(f"Found an error: {e}") ``` [After] ```python try: ... except ValueError: logger.exception("Found an error") ```'924};925926927