> ## Documentation Index
> Fetch the complete documentation index at: https://docs.codeant.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Python

> Learn about Python Anti-Patterns and How they help you write better code, and avoid common pitfalls.

> [accordion] Remove conditional statements that never execute
>
> This rule identifies conditional statements in your code that will never execute, known as dead code, because their conditions are always false. Removing such statements cleans up the codebase, enhancing readability and potentially improving performance by eliminating unnecessary checks during execution. It's crucial for maintaining an efficient and easily navigable codebase.
>
> ```python Bad theme={"theme":"css-variables"}
> if False:
> print(3)
> if True:
> print(2)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print(2)
> ```

> [accordion] Fix raise statements to include missing 'from'
>
> This rule emphasizes the importance of using the 'from' keyword in 'raise' statements to chain exceptions explicitly. It enhances error traceability by providing a clear path from the original to the new exception, greatly aiding in debugging complex issues. Addressing this issue leads to better error handling practices and more maintainable code by making the causal relationship between exceptions clear.
>
> ```python Bad theme={"theme":"css-variables"}
> try:
> sketchy_function()
> except ValueError:
> raise RuntimeError()
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> try:
> sketchy_function()
> except ValueError as error:
> raise RuntimeError() from error
> ```

> [accordion] Move statements outside of loops where possible
>
> Advises on moving statements that do not change within the loop's scope to outside of the loop. This optimization can lead to significant performance improvements, especially in large or heavily iterated loops, by reducing the computational overhead within the loop. It not only speeds up execution but also improves code readability by simplifying the loop's body.
>
> ```python Bad theme={"theme":"css-variables"}
> for i in range(100):
> x = 10
> print(x + i)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = 10
> for i in range(100):
> print(x + i)
> ```

> [accordion] Remove functions and classes that are never used
>
> Targets functions and classes within the codebase that are never called or instantiated, marking them for removal. Cleaning up these unused elements can dramatically reduce code clutter, making the codebase easier to navigate and maintain. Moreover, it can highlight areas of the code that may require refactoring or optimization, contributing to overall better resource management.

> [accordion] Optimize singleton equality comparisons
>
> This rule focuses on optimizing comparisons with singletons (like None in Python) by using identity checks ('is' or 'is not') instead of equality checks ('==', '!='). Since singletons have a unique instance, identity checks are both logically appropriate and faster, leading to improved performance and code clarity.
>
> ```python Bad theme={"theme":"css-variables"}
> x == None and k != None
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x is None and k is not None
> ```

> [accordion] Break out common code from if-else blocks
>
> Encourages refactoring to break out code that is duplicated across multiple branches of an if-else statement. This practice not only makes the code more DRY (Don't Repeat Yourself) but also enhances readability and maintainability by reducing redundancy. It simplifies understanding the code's logic and can make further changes or bug fixes easier to implement.
>
> ```python Bad theme={"theme":"css-variables"}
> import random
> if random.random() < 2:
> print(100)
> print(3)
> else:
> print(100)
> print(21)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import random
> print(100)
> if random.random() < 2:
> print(3)
> else:
> print(21)
> ```

> [accordion] Simplify control flow within if statements
>
> Aims to streamline the control flow within if statements, reducing complexity and improving readability. This may involve eliminating unnecessary nested conditions or simplifying logical expressions. Simplifying control flow makes the code easier to follow, understand, and test, which is beneficial for both current and future developers working on the codebase.
>
> ```python Bad theme={"theme":"css-variables"}
> import random
> x = 11
> y = 12
> z = random.random()
> if z > 1 - z:
> do_stuff(x)
> do_stuff(y - x ** 2)
> print(doing_other_stuff(x) - do_stuff(y ** y))
> else:
> do_stuff(y)
> do_stuff(x - y ** 2)
> print(doing_other_stuff(y) - do_stuff(x ** x))
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import random
> x = 11
> y = 12
> z = random.random()
> if z > 1 - z:
> var_1 = x
> var_2 = y
> else:
> var_1 = y
> var_2 = x
>
> do_stuff(var_1)
> do_stuff(var_2 - var_1 ** 2)
> print(doing_other_stuff(var_1) - do_stuff(var_2 ** var_2))
> ```

> [accordion] Swap if-else branches where beneficial
>
> Suggests rearranging if-else branches to improve clarity or efficiency, particularly when it allows for a more straightforward condition or aligns with expected coding practices. This change can make the code more intuitive and align execution paths with likely scenarios first, potentially improving both readability and performance by optimizing for common cases.
>
> ```python Bad theme={"theme":"css-variables"}
> def f(x)  int:
> if x > 10:
> x += 1
> x *= 12
> print(x > 30)
> return 100 - sum(x, 2, 3)
> else:
> return 13
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def f(x)  int:
> if x <= 10:
> return 13
> else:
> x += 1
> x *= 12
> print(x > 30)
> return 100 - sum(x, 2, 3)
> ```

> [accordion] Apply early return pattern to simplify function
>
> Promotes using the early return pattern to exit functions as soon as a condition is met, avoiding additional indentation from nested if-else blocks. This pattern simplifies function logic, making it easier to understand and reducing the cognitive load required to follow the flow of the function. It can also decrease the function's execution time by avoiding unnecessary checks after conditions are met.
>
> ```python Bad theme={"theme":"css-variables"}
> def f(x)  int:
> if x > 10:
> x += 1
> x *= 12
> print(x > 30)
> y = 100 - sum(x, 2, 3)
> else:
> y = 13
> return y
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def f(x)  int:
> if x > 10:
> x += 1
> x *= 12
> print(x > 30)
> return 100 - sum(x, 2, 3)
> else:
> return 13
> ```

> [accordion] Use continue statement early in loops to reduce nesting
>
> Advises using the continue statement at the beginning of loops to immediately skip to the next iteration under certain conditions, reducing nesting and improving readability. This practice can make loops clearer by highlighting the conditions for continuing early and can improve performance by minimizing the execution of loop bodies under those conditions.
>
> ```python Bad theme={"theme":"css-variables"}
> for x in range(100):
> if x > 10:
>     y = 13
> else:
>     x += 1
>     x *= 12
>     print(x > 30)
>     y = 100 - sum(x, 2, 3)
> print(x)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> for x in range(100):
> if x > 10:
>     y = 13
>     continue
> else:
>     x += 1
>     x *= 12
>     print(x > 30)
>     y = 100 - sum(x, 2, 3)
> print(x)
> ```

> [accordion] Remove unnecessary enumerate calls
>
> Identifies situations where the enumerate function is used unnecessarily, typically when the index it provides is not used. Removing such redundant uses can simplify the code, making it more readable and potentially enhancing performance by eliminating the overhead associated with enumeration when it's not needed.
>
> ```python Bad theme={"theme":"css-variables"}
> (x for _, x in enumerate(y))
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> (x for x in y)
> ```

> [accordion] Remove unused arguments in zip
>
> Highlights instances where arguments provided to the zip function are never used, suggesting their removal for cleaner code. Addressing this issue not only improves code readability by eliminating superfluous elements but also can uncover potential logic errors or inefficiencies in how data structures are being used.
>
> ```python Bad theme={"theme":"css-variables"}
> x = (a for _, a in zip(range(3), range(1, 3)))
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = (a for a in range(1, 3))
> ```

> [accordion] Replace map and lambda with list comprehensions
>
> Recommends replacing combinations of the map function and lambda expressions with list comprehensions for more readable and concise code. List comprehensions are often more straightforward for developers to understand and can offer performance benefits over map and lambda by being more Pythonic and potentially faster in execution.
>
> ```python Bad theme={"theme":"css-variables"}
> x = map(lambda y: y > 0, (1, 2, 3))
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = (y > 0 for y in (1, 2, 3))
> ```

> [accordion] Replace filter and lambda with list comprehensions
>
> Similar to map and lambda, this rule suggests using list comprehensions instead of the filter function combined with lambda expressions. This change makes the code cleaner and more accessible by leveraging the more intuitive syntax of list comprehensions, which can also lead to slight performance improvements.
>
> ```python Bad theme={"theme":"css-variables"}
> x = filter(lambda y: y > 0, (1, 2, 3))
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = (y for y in (1, 2, 3) if y > 0)
> ```

> [accordion] Remove unnecessary else statements
>
> This rule is about removing unnecessary else statements in your code. An else statement is considered unnecessary when it follows a return statement in the if block. In such cases, the else block can be safely removed without changing the logic of the code. Unnecessary else statements can make your code harder to read and understand. They can also lead to more complex code structures, which can increase the likelihood of introducing bugs. By removing unnecessary else statements, you can make your code simpler and more readable.
>
> ```python Bad theme={"theme":"css-variables"}
> def f(x: int)  int:
> if x == 2:
>     return 10
> else:
>     return 11 - x
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def f(x: int)  int:
> if x == 2:
>     return 10
>
> return 11 - x
> ```

> [accordion] Replace complex filtering logic with filter function
>
> This rule suggests using the filter function to streamline complex filtering logic within loops or list comprehensions. By encapsulating filtering logic in a filter function, code becomes cleaner and more expressive, allowing for better readability. This pattern can also improve performance by using built-in Python optimizations for filtering collections.
>
> ```python Bad theme={"theme":"css-variables"}
> for x in range(10):
> if x:
> print(3)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> for x in filter(None, range(10)):
> print(3)
> ```

> [accordion] Merge chained comparisons into a single expression
>
> Encourages combining multiple comparison operations into a single, chained expression. This not only makes the code more readable by reducing complexity and enhancing clarity but can also improve execution speed by minimizing the number of comparison operations. Chained comparisons are more pythonic and can make conditional logic easier to understand at a glance.
>
> ```python Bad theme={"theme":"css-variables"}
> x = (y for y in (y for y in (3, 4, 5)))
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = (y for y in (3, 4, 5))
> ```

> [accordion] Remove unnecessary casts of comprehensions
>
> Targets unnecessary casts (like converting a list comprehension directly to a list) of comprehensions, suggesting their removal. Since comprehensions inherently create their target collection, extra casting is redundant and can negatively impact performance. Removing these casts simplifies the code and can slightly improve runtime efficiency by reducing unnecessary function calls.
>
> ```python Bad theme={"theme":"css-variables"}
> set({x for x in range(10)})
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> {x for x in range(10)}
> ```

> [accordion] Remove redundant casts in chained calls
>
> Focuses on eliminating redundant casts in sequences of function calls, where the outcome of one operation is immediately cast to another type without need. Addressing this issue can clean up the code by removing unnecessary operations, thereby enhancing readability and possibly improving performance by reducing the computational overhead.
>
> ```python Bad theme={"theme":"css-variables"}
> set(itertools.chain(range(10), range(11)))
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> {*range(10), *range(11)}
> ```

> [accordion] Fix if statements with unnecessary return
>
> This rule identifies if statements that end with a return statement and then have an unnecessary else block that also returns. It suggests removing the else block and placing the return statement outside, simplifying the control flow. This change makes the function easier to read and understand by reducing unnecessary nesting and highlighting the conditions under which different return values are provided.
>
> ```python Bad theme={"theme":"css-variables"}
> def f(x: int)  int:
> if x == 100:
>     return False
> return True
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def f(x: int)  int:
> return not x == 100
> ```

> [accordion] Refactor if statements that unnecessarily assign values
>
> Aims to refactor if statements that assign the same variable to different values in each branch by suggesting a more streamlined approach, such as using a conditional expression. This can significantly enhance code readability by reducing the number of lines and making the conditional assignment clearer and more direct.
>
> ```python Bad theme={"theme":"css-variables"}
> if x == 100:
> y = False
> else:
> y = True
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> y = not x == 100
> ```

> [accordion] Replace function calls with simpler literals where possible
>
> Suggests replacing calls to functions that simply return a static or simple dynamic value with literals or simpler expressions. This optimization can reduce the overhead associated with function calls, making the code more efficient and easier to read by directly presenting values or simple expressions instead of hiding them behind function calls.
>
> ```python Bad theme={"theme":"css-variables"}
> u = list()
> v = tuple()
> w = dict()
> a = dict(zip(range(4), range(1, 5)))
> b = list((1, 2, 3, 99))
> c = set([1, 2, 3])
> d = iter((1, 2, 3, 5))
> aa = (1 for u in (1, 2, 3, 5))
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> u = []
> v = ()
> w = {}
> a = dict(zip(range(4), range(1, 5)))
> b = [1, 2, 3, 99]
> c = {1, 2, 3}
> d = iter((1, 2, 3, 5))
> aa = (1 for u in (1, 2, 3, 5))
> ```

> [accordion] Use collection literals for adding or updating collections
>
> Recommends using collection literals (e.g., set or list literals) instead of adding or updating collections through method calls. This can make the code more concise and readable by clearly showing the intention to create or modify collections, and can improve performance by utilizing Python's optimized syntax for collection manipulation.
>
> ```python Bad theme={"theme":"css-variables"}
> x = {1, 2, 3}
> x.add(7)
> x.add(191)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = {1, 2, 3, 7, 191}
> ```

> [accordion] Simplify the unpacking of collections
>
> Targets the simplification of unpacking operations for collections, advocating for more straightforward or efficient ways to unpack items. This can improve both the readability of the code by making unpacking operations clearer and the performance by reducing the complexity of these operations.
>
> ```python Bad theme={"theme":"css-variables"}
> x = [*()]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = []
> ```

> [accordion] Remove duplicate elements from sets
>
> Identifies and suggests removing duplicate elements in set initializations. Since sets automatically enforce uniqueness, explicitly listing duplicate elements is unnecessary and can mislead readers about the code's intent, besides causing minor performance concerns during set creation.
>
> ```python Bad theme={"theme":"css-variables"}
> {1, 99, "s", 1, sum(range(11)), sum(range(11))}
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> {1, 99, "s", sum(range(11))}
> ```

> [accordion] Break out starred arguments into separate variables
>
> Encourages breaking out arguments that are passed with the star (\*) operator into explicit variables, if practical. This can improve readability by making the function's expected arguments clearer and can enhance maintainability by making it easier to identify and modify the use of these arguments in the function call.
>
> ```python Bad theme={"theme":"css-variables"}
> x = foo(a, b, *(c, d), e, *{f}, *[k, v, h])
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = foo(a, b, c, d, e, f, k, v, h)
> ```

> [accordion] Replace .loc and .at with .iloc and .iat for performance
>
> Advises on replacing .loc and .at with .iloc and .iat in pandas DataFrames for improved performance. .iloc and .iat are designed for position-based indexing and are generally faster than .loc and .at, which are label-based. This switch can lead to significant performance gains, especially in large datasets, by optimizing data access patterns.
>
> ```python Bad theme={"theme":"css-variables"}
> y = x.loc[1, 2]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> y = x.at[1, 2]
> ```

> [accordion] Replace .iterrows with direct indexing for performance
>
> This rule recommends replacing the use of .iterrows in pandas DataFrames with direct indexing where possible for enhanced performance. Direct indexing accesses elements more efficiently than .iterrows, which iterates over DataFrame rows in a slower, row-wise manner. This change can lead to significant speed improvements in data processing scripts by leveraging faster data access patterns.
>
> ```python Bad theme={"theme":"css-variables"}
> for x, _ in df.iterrows():
> print(x)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> for x in df.index:
> print(x)
> ```

> [accordion] Replace .iterrows with .itertuples for better performance
>
> Suggests substituting .iterrows with .itertuples for iterating over DataFrame rows in pandas. .itertuples is generally faster than .iterrows because it returns namedtuples of the row data, reducing overhead and improving performance in row-wise operations. This modification can greatly speed up loop iterations over DataFrame rows, making code more efficient.
>
> ```python Bad theme={"theme":"css-variables"}
> for _, x in df.iterrows():
> print(x["value"])
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> for x in df.itertuples():
> print(x.value)
> ```

> [accordion] Replace for loops with set or list comprehensions
>
> Encourages replacing for loops that build sets or lists with set or list comprehensions. Comprehensions provide a more concise, readable, and pythonic way to create collections compared to loops, and they often offer performance benefits by being optimized for collection creation. This leads to cleaner code that's easier to understand and faster to execute.
>
> ```python Bad theme={"theme":"css-variables"}
> x = []
> for i in range(10):
> x.append(i)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = [i for i in range(10)]
> ```

> [accordion] Replace set comprehensions with union operations
>
> Advises on replacing set comprehensions followed by addition operations with set union operations. Set unions are more efficient and semantically clear for combining sets than adding elements in a loop, leading to code that's both faster and easier to read by expressing the intent more directly.
>
> ```python Bad theme={"theme":"css-variables"}
> x = {foo(z) ** 2 for z in range(3)}
> for zua in range(3):
> x.add(zua - 1)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = {foo(z) ** 2 for z in range(3)} | {zua - 1 for zua in range(3)}
> ```

> [accordion] Replace list append in a loop with concatenation
>
> Recommends using list concatenation instead of appending to a list within a loop. Concatenation can be more efficient, especially when dealing with small lists or when the total size is known beforehand, as it can reduce the overhead of repeated append operations. This approach also makes the code more succinct and readable by clearly showing the intention to combine list elements.
>
> ```python Bad theme={"theme":"css-variables"}
> x = [foo(z) ** 2 for z in range(3)]
> for zua in range(3):
> x.append(zua - 1)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = [foo(z) ** 2 for z in range(3)] + [zua - 1 for zua in range(3)]
> ```

> [accordion] Replace for loops with dictionary comprehensions
>
> Promotes the use of dictionary comprehensions instead of for loops for creating dictionaries. Dictionary comprehensions offer a concise, readable alternative to loops, enhancing code clarity and potentially improving execution speed by optimizing the dictionary creation process.
>
> ```python Bad theme={"theme":"css-variables"}
> x = {}
> for i in range(10):
> x[i] = 10
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = {i: 10 for i in range(10)}
> ```

> [accordion] Use implicit dictionary keys, values, and items
>
> Encourages the use of the implicit form of dictionary keys(), values(), and items() methods in looping constructs. This practice can make the code more pythonic and readable by reducing verbosity without compromising functionality or performance.
>
> ```python Bad theme={"theme":"css-variables"}
> (x for x, _ in d.items())
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> (x for x in d.keys())
> ```

> [accordion] Replace dictionary assignments with literals
>
> Suggests replacing sequential dictionary assignments with dictionary literals. Using literals can make the code more concise and easier to understand by displaying the dictionary's contents directly, and can improve performance by reducing the number of assignment operations.
>
> ```python Bad theme={"theme":"css-variables"}
> x = {}
> x[10] = 100
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = {10: 100}
> ```

> [accordion] Replace dictionary update with literal merge
>
> Recommends using literal syntax for merging dictionaries instead of the update method. This approach is more direct and readable, showing the intent to combine dictionaries clearly, and can offer slight performance benefits by leveraging Python's optimized syntax for literal merges.
>
> ```python Bad theme={"theme":"css-variables"}
> x = {}
> x.update({10: 100})
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = {**{10: 100}}
> ```

> [accordion] Replace dict comp assignments with literals
>
> Targets replacing dictionary comprehensions that are immediately assigned to a dictionary with direct dictionary literals. This can enhance readability by presenting the dictionary's content in a straightforward manner and may improve performance by avoiding the overhead of the comprehension and assignment steps.
>
> ```python Bad theme={"theme":"css-variables"}
> x = {z: 21 for z in range(3)}
> x[10] = 100
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = {**{z: 21 for z in range(3)}, 10: 100}
> ```

> [accordion] Replace dict comp updates with literal merge
>
> Advises on using dictionary literals for updating dictionaries instead of comprehensions followed by updates. This method is clearer and more efficient, directly showing the updated content and potentially reducing runtime by avoiding the two-step process of comprehension creation and update.
>
> ```python Bad theme={"theme":"css-variables"}
> x = {z: 21 for z in range(3)}
> x.update({10: 100})
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = {**{z: 21 for z in range(3)}, **{10: 100}}
> ```

> [accordion] Simplify the unpacking of dictionaries
>
> Focuses on simplifying the unpacking of dictionaries, especially in function calls or assignments. Simplifying unpacking operations can make the code more readable and maintainable by clearly showing which keys and values are being used, and can optimize the code by reducing unnecessary complexity in data handling.
>
> ```python Bad theme={"theme":"css-variables"}
> x = {**{}}
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = {}
> ```

> [accordion] Remove duplicate keys from dictionaries
>
> Identifies and suggests removing duplicate keys in dictionary literals. Duplicate keys in dictionaries are usually an error or oversight, as they can lead to unpredictable behavior by overwriting values. Removing them improves code clarity and correctness, ensuring that each key-value pair is unique and intentional.
>
> ```python Bad theme={"theme":"css-variables"}
> {1: 2, 99: 101, "s": 4, 1: 22, sum(range(11)): 9999, sum(range(11)): 9999}
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> {1: 22, 99: 101, "s": 4, sum(range(11)): 9999}
> ```

> [accordion] Replace implicit matrix multiplication for clarity and performance
>
> This rule recommends replacing implicit matrix multiplication operations with explicit ones to enhance both clarity and performance. Explicit matrix multiplication, typically done with the @ operator in Python, makes the operation clear to the reader and can be optimized by libraries for better performance, especially with large datasets or complex mathematical computations.
>
> ```python Bad theme={"theme":"css-variables"}
> import numpy as np
>
> i, j, k = 10, 11, 12
>
> a = np.random.random((i, j))
> b = np.random.random((j, k))
>
> u = np.array([[np.dot(a_, b_) for a_ in a] for b_ in b.T]).T
> v = np.array([[np.dot(b_, a_) for b_ in b.T] for a_ in a])
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import numpy as np
>
> i, j, k = 10, 11, 12
>
> a = np.random.random((i, j))
> b = np.random.random((j, k))
>
> u = np.matmul(a, b)
> v = np.matmul(a, b)
> ```

> [accordion] Replace subscript looping with more efficient methods
>
> Suggests replacing looping over sequences with subscripts (e.g., for i in range(len(sequence)): item = sequence\[i]) with more direct iteration methods (e.g., for item in sequence). This change improves readability by reducing boilerplate code and can enhance performance by eliminating the need for indexing operations.
>
> ```python Bad theme={"theme":"css-variables"}
> import numpy
> [a[i] for i in range(len(a))]
> [a[i, :] for i in range(len(a))]
> [a[i, :] for i in range(a.shape[0])]
> [a[:, i] for i in range(a.shape[1])]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import numpy
> list(a)
> list(a)
> list(a)
> list(a.T)
> ```

> [accordion] Replace implicit dot products with explicit calls
>
> Advises on replacing implicit dot product operations with explicit function calls to dot products. Explicit calls can make the code more understandable by clearly indicating the operation being performed and can allow for optimizations specific to dot product calculations, thus potentially improving performance.

> [accordion] Simplify unnecessary transposes in arrays
>
> Targets unnecessary transpose operations in arrays, suggesting their removal or simplification. Transposes can be computationally expensive and may not be needed, especially if followed by operations that negate their effects. Simplifying or removing them can improve both performance and code clarity.

> [accordion] Optimize matrix multiplications with transpose operations
>
> Recommends optimizing matrix multiplication operations that involve unnecessary transposes. By rearranging or eliminating these transposes, the efficiency of matrix multiplications can be improved, resulting in faster computations and clearer code that more directly expresses the intended mathematical operations.

> [accordion] Use defaultdict for cleaner default value handling
>
> Encourages the use of defaultdict from the collections module for handling default values in dictionaries more cleanly. defaultdict automatically initializes missing keys with a default value, simplifying code and improving readability by avoiding explicit checks or assignments for missing keys.
>
> ```python Bad theme={"theme":"css-variables"}
> def f(x: int)  int:
>     return x+1
> d = {}
> for x in range(10):
> y = f(x)
> if x in d:
>     d[x].append(y)
> else:
>     d[x] = [y]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def f(x: int)  int:
>     return x+1
> d = collections.defaultdict(list)
> for x in range(10):
>     y = f(x)
>     d[x].append(y)
> ```

> [accordion] Remove redundant lambdas and use direct function calls
>
> Identifies and suggests removing redundant lambda functions that wrap direct function calls without modification. Using the functions directly can simplify the code, making it more readable and potentially improving performance by reducing the overhead associated with lambda expressions.
>
> ```python Bad theme={"theme":"css-variables"}
> lambda *args: w(*args)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> w
> ```

> [accordion] Remove unnecessary comprehensions
>
> Highlights unnecessary comprehensions that could be replaced with simpler constructs or direct operations. Removing these can make the code more concise and readable, as well as improve performance by avoiding the overhead of the comprehension syntax for straightforward operations.
>
> ```python Bad theme={"theme":"css-variables"}
> a = {x: y for x, y in zip(range(4), range(1, 5))}
> b = [w for w in (1, 2, 3, 99)]
> c = {v for v in [1, 2, 3]}
> d = (u for u in (1, 2, 3, 5))
> aa = (1 for u in (1, 2, 3, 5))
> ww = {x: y for x, y in zip((1, 2, 3), range(3)) if x > y > 1}
> ww = {x: y for y, x in zip((1, 2, 3), range(3))}
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> a = dict(zip(range(4), range(1, 5)))
> b = list((1, 2, 3, 99))
> c = set([1, 2, 3])
> d = iter((1, 2, 3, 5))
> aa = (1 for u in (1, 2, 3, 5))
> ww = {x: y for x, y in zip((1, 2, 3), range(3)) if x > y > 1}
> ww = {x: y for y, x in zip((1, 2, 3), range(3))}
> ```

> [accordion] Simplify complex boolean expressions
>
> Focuses on simplifying complex boolean expressions to enhance readability and maintainability. Complex expressions can often be rewritten more concisely without changing their logical outcome, making the code easier to understand and less prone to errors.
>
> ```python Bad theme={"theme":"css-variables"}
> x and False and y
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> False
> ```

> [accordion] Simplify constrained range expressions
>
> Suggests simplifying expressions that constrain ranges redundantly, such as using min and max functions in a range where the limits are already clear. Simplifying these expressions can improve readability and performance by removing unnecessary function calls and making the intended range constraints more direct.
>
> ```python Bad theme={"theme":"css-variables"}
> (x for x in range(10) if x > 4)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> (x for x in range(5, 10))
> ```

> [accordion] Simplify boolean expressions using symbolic math
>
> Recommends using symbolic mathematics libraries to simplify complex boolean expressions. This approach can reveal simplifications that are not immediately obvious, making the code cleaner and often more efficient by reducing the complexity of conditional logic.
>
> ```python Bad theme={"theme":"css-variables"}
> x and not x
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> False
> ```

> [accordion] Inline comprehensions in mathematical expressions
>
> Advises inlining list or set comprehensions directly into mathematical expressions where possible. This can enhance readability by reducing the amount of code and improving performance by eliminating the need for intermediate collection construction during complex mathematical operations.
>
> ```python Bad theme={"theme":"css-variables"}
> z = {a for a in range(10)}
> x = sum(z)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = sum({a for a in range(10)})
> ```

> [accordion] Simplify iterators in mathematical expressions
>
> Targets simplification of iterators used in mathematical expressions, recommending more straightforward iteration patterns. Simplifying these iterators can make the code easier to understand and reduce computational overhead in mathematical computations.
>
> ```python Bad theme={"theme":"css-variables"}
> x = sum(range(10))
> y = sum(range(3, 17))
> h = sum((1, 2, 3))
> q = sum([1, 2, 3, 99, 99, -8])
> r = sum({1, 2, 3, 99, 99, -8})
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = 45
> y = 133
> h = 6
> q = 196
> r = sum({1, 2, 3, 99, 99, -8})
> ```

> [accordion] Replace negated numeric comparisons with direct comparisons
>
> Suggests replacing negated numeric comparisons with their direct counterparts for clarity and efficiency. For example, instead of using !(a > b), use a `<= b`. This makes the intended comparison more explicit and can improve both the readability of the code and its execution speed by using simpler operations.
>
> ```python Bad theme={"theme":"css-variables"}
> not x > 3
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x <= 3
> ```

> [accordion] Optimize type checks within 'in' and 'not in' expressions
>
> This rule encourages the optimization of 'contain' types to enhance both performance and readability of the code. It focuses on improving the efficiency of checking whether an object is part of a collection. By using the most suitable and efficient methods for these checks, we can reduce computational overhead and improve the overall speed of the program.
>
> ```python Bad theme={"theme":"css-variables"}
> 1 in (1, 2, 3)
> x in {1, 2, ()}
> x in [1, 2, []]
> w in [1, 2, {}]
> w in {foo, bar, "asdf", coo}
> w in (foo, bar, "asdf", coo)
> w in {x for x in range(10)}
> w in [x for x in range(10)]
> w in (x for x in range(10))
> w in {x for x in [1, 3, "", 909, ()]}
> w in [x for x in [1, 3, "", 909, ()]]
> w in (x for x in [1, 3, "", 909, ()])
> x in sorted([1, 2, 3])
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> 1 in {1, 2, 3}
> x in {1, 2, ()}
> x in (1, 2, [])
> w in (1, 2, {})
> w in {foo, bar, "asdf", coo}
> w in (foo, bar, "asdf", coo)
> w in (x for x in range(10))
> w in (x for x in range(10))
> w in (x for x in range(10))
> w in (x for x in [1, 3, "", 909, ()])
> w in (x for x in [1, 3, "", 909, ()])
> w in (x for x in [1, 3, "", 909, ()])
> x in {1, 2, 3}
> ```

> [accordion] Remove redundant chained method calls
>
> Identifies and recommends removing redundant method calls chained together where earlier calls do not affect the outcome of the chain. This simplification not only enhances code readability by eliminating unnecessary operations but also improves performance by reducing the computational overhead associated with executing these redundant method calls.
>
> ```python Bad theme={"theme":"css-variables"}
> sorted(tuple(v))
> sorted(list(v))
> list(iter(v))
> list(tuple(v))
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> sorted(v)
> sorted(v)
> list(v)
> list(v)
> ```

> [accordion] Remove unnecessary calls to iter()
>
> Targets unnecessary calls to iter(), suggesting their removal. In many cases, Python's for loops and other iterators implicitly call iter() on collections, making explicit calls redundant. Removing them simplifies the code and can slightly improve performance by avoiding superfluous function calls.

> [accordion] Replace sorted calls with heapq for performance in large collections
>
> Recommends replacing the sorted() function with heapq functions for performance improvements in scenarios involving large collections. When only the smallest or largest elements are needed, heapq can provide these more efficiently than sorting the entire collection, leading to significant performance gains in handling large datasets.

> [accordion] Add missing context managers for file and resource handling
>
> Advises adding missing context managers for file and resource handling to ensure that resources are properly managed and released, even in the event of errors. Using context managers improves code reliability and readability by clearly defining the scope of resource usage.
>
> ```python Bad theme={"theme":"css-variables"}
> import requests
>
> session = requests.Session()
> session.get("https://www.google.com")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import requests
>
> with requests.Session() as session:
> session.get("https://www.google.com")
> ```

> [accordion] Remove functions that are duplicated in the codebase
>
> Identifies functions that are duplicated within the codebase and suggests removing the duplicates. Duplicate functions can lead to maintenance issues, inconsistencies, and increased code size, making it harder to manage and understand the codebase.

> [accordion] Remove duplicate import statements
>
> Targets duplicate import statements for removal. Duplicate imports can clutter the code and lead to confusion about the namespace's structure, without offering any benefit. Streamlining imports can enhance code clarity and organization.
>
> ```python Bad theme={"theme":"css-variables"}
> from logging import info
> from logging import warning
> from logging import error, info, log
> from logging import (
> warning,
> critical   ,
> error, error, error as error)
> from logging import critical
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from logging import critical, error, info, log, warning
> ```

> [accordion] Remove unused import statements
>
> Recommends removing import statements that are not used within the code. Unused imports can lead to unnecessary dependencies and can potentially slow down program startup time. Cleaning up imports can improve code readability and performance.
>
> ```python Bad theme={"theme":"css-variables"}
> import numpy as np, pandas as pd
> print(pd)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import pandas as pd
> print(pd)
> ```

> [accordion] Transforms keys in the source to items
>
> Suggests transforming dictionary keys in the source to key-value pairs (items), providing a more comprehensive view of the data structure being iterated over or manipulated. This can enhance both the expressiveness and efficiency of operations that require access to both keys and values.

> [accordion] Transforms items in the source to keys
>
> Advises on transforming item tuples back to keys when only the keys are needed from a dictionary that was initially accessed for its items. This can simplify data handling by focusing on the relevant part of the data structure for the given context.

> [accordion] Transforms items in the source to values
>
> Recommends transforming item tuples to values, focusing on the value part of key-value pairs in a dictionary. This is useful in contexts where the values are of primary interest, streamlining the code by removing unnecessary references to keys.

> [accordion] Applies a transformation for keys to items in the source
>
> Applies a transformation from keys to items in the source, suggesting a shift in focus from operating solely on keys to working with both keys and values. This can be particularly beneficial in scenarios where both elements are needed for processing or decision-making.

> [accordion] Applies a transformation for items to keys in the source
>
> Implies a transformation for items to keys, advocating for a simplification in cases where the operation initially involves both keys and values but ultimately requires only the keys. This simplification can make the code more focused and readable.

> [accordion] Applies a transformation for items to values in the source
>
> Suggests a shift from handling item tuples to focusing solely on their values. This transformation is recommended when the values hold the necessary data for the operation, allowing the code to be more concise and targeted.

> [accordion] Simplify assignments that are immediately returned
>
> Identifies scenarios where a value is assigned to a variable only to be immediately returned and suggests simplifying this by returning the value directly. This change can make the code cleaner and more straightforward by eliminating an unnecessary variable assignment.

> [accordion] Swap explicit if-else branches where beneficial
>
> Recommends swapping explicit if-else branches when it results in clearer or more efficient code. For example, changing the order of if-else branches can improve readability by placing the most common or simplest case first, or it can enhance performance by optimizing the order of condition evaluation.
>
> ```python Bad theme={"theme":"css-variables"}
> def f(x)  int:
> if x > 10:
>     x += 1
>     x *= 12
>     print(x > 30)
>     return 100 - sum(x, 2, 3)
> else:
>     return 13
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def f(x)  int:
> if x <= 10:
>     return 13
> else:
>     x += 1
>     x *= 12
>     print(x > 30)
>     return 100 - sum(x, 2, 3)
> ```

> [accordion] Simplify assignments that are immediately returned
>
> This rule identifies scenarios where a value is assigned to a variable only to be immediately returned by the function. Simplifying this pattern by returning the value directly can make the function more straightforward and concise, eliminating unnecessary intermediate variables and clearly communicating the return value.
>
> ```python Bad theme={"theme":"css-variables"}
> def foo():
> x = 100
> return x
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def foo():
> return 100
> ```

> [accordion] Swaps explicit if-else branches where beneficial
>
> Recommends reordering explicit if-else branches when such a change leads to clearer or more logically organized code. Swapping if-else branches can enhance readability, especially when it aligns the code's structure with its intended logic or prioritizes more common conditions, making the code easier to follow and sometimes more efficient.

> [accordion] replace string concatenation with f-strings
>
> Advises replacing string concatenation operations with f-strings for improved readability and performance. F-strings, introduced in Python 3.6, provide a more concise and intuitive syntax for embedding expressions inside string literals, making the code cleaner and often faster than traditional concatenation methods.
>
> ```python Bad theme={"theme":"css-variables"}
> a = "Hello" + name
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> a = f"Hello{name}"
> ```

> [accordion] Abstract class %r with abstract methods instantiated
>
> Flags an instance being created from an abstract class that contains abstract methods. Abstract classes are designed to be subclassed, not instantiated directly, and doing so can lead to runtime errors if the abstract methods are not implemented. This rule helps ensure that the code's design intentions are respected and that subclasses provide concrete implementations for abstract methods.
>
> ```python Bad theme={"theme":"css-variables"}
> import abc
>
>
> class Animal(abc.ABC):
> @abc.abstractmethod
> def make_sound(self):
>     pass
>
>
> sheep = Animal()  # [abstract-class-instantiated]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import abc
>
>
> class Animal(abc.ABC):
> @abc.abstractmethod
> def make_sound(self):
>     pass
>
>
> class Sheep(Animal):
> def make_sound(self):
>     print("bhaaaaa")
>
>
> sheep = Sheep()
> ```

> [accordion] Access to member %r before its definition line %s
>
> Identifies access to a class member before its definition has occurred. This can lead to errors or unintended behavior, as the member may not be initialized at the time of access. Ensuring members are defined before they are accessed improves code reliability and readability.
>
> ```python Bad theme={"theme":"css-variables"}
> class Unicorn:
> def __init__(self, fluffiness_level):
>     if self.fluffiness_level > 9000:  # [access-member-before-definition]
>         print("It's OVER-FLUFFYYYY ! *crush glasses*")
>     self.fluffiness_level = fluffiness_level
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Unicorn:
> def __init__(self, fluffiness_level):
>     self.fluffiness_level = fluffiness_level
>     if self.fluffiness_level > 9000:
>         print("It's OVER-FLUFFYYYY ! *crush glasses*")
> ```

> [accordion] Assigning to attribute %r not defined in class slots
>
> Detects assignments to attributes not defined in the class **slots**. Using **slots** is a way to declare explicitly which attributes the class will have, offering memory savings and faster attribute access. Assigning to non-slot attributes breaks the constraints set by **slots** and can lead to unexpected behavior or inefficiencies.
>
> ```python Bad theme={"theme":"css-variables"}
> class Student:
> __slots__ = ("name",)
>
> def __init__(self, name, surname):
>     self.name = name
>     self.surname = surname  # [assigning-non-slot]
>     self.setup()
>
> def setup(self):
>     pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Student:
> __slots__ = ("name", "surname")
>
> def __init__(self, name, surname):
>     self.name = name
>     self.surname = surname
>     self.setup()
>
> def setup(self):
>     pass
> ```

> [accordion] Assigning result of a function call, where the function has no return
>
> Catches attempts to assign the result of a function call to a variable when the function does not explicitly return a value. This usually results in the variable being assigned None, which can be a source of bugs if not intended. Highlighting these cases encourages more explicit control flow and return value handling.
>
> ```python Bad theme={"theme":"css-variables"}
> def add(x, y):
> print(x + y)
>
>
> value = add(10, 10)  # [assignment-from-no-return]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def add(x, y):
> return x + y
>
>
> value = add(10, 10)
> ```

> [accordion] Assigning result of a function call, where the function returns None
>
> Similar to the above, this rule flags assignments of the result of function calls where the function is known to return None. Such assignments are often unintended and can lead to logic errors if the None value is not handled properly.
>
> ```python Bad theme={"theme":"css-variables"}
> def function():
> return None
>
>
> f = function()  # [assignment-from-none]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def function():
> return None
>
>
> f = function() if function() else 1
> ```

# step 1

> [accordion] 'await' should be used within an async function
>
> Identifies the use of 'await' for an asynchronous call outside of an async function. This is a syntax error as 'await' can only be used within async functions. This rule helps prevent runtime errors by ensuring that asynchronous calls are correctly placed within the asynchronous execution context.
>
> ```python Bad theme={"theme":"css-variables"}
> import asyncio
>
>
> def main():
> await asyncio.sleep(1)  # [await-outside-async]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import asyncio
>
>
> async def main():
> await asyncio.sleep(1)
> ```

> [accordion] Misconfigured section detected
>
> Points out misconfigurations in configuration files or sections of code that are not set up correctly. Proper configuration is crucial for the successful execution and behavior of applications, and this rule aids in identifying and correcting configuration errors.

> [accordion] Bad except clauses order (%s)
>
> Warns about incorrectly ordered except clauses in try-except blocks. Specific exceptions should be listed before more general ones to prevent the general exceptions from catching exceptions intended for the specific handlers. This ensures that exceptions are handled appropriately and that error handling logic is clear and effective.
>
> ```python Bad theme={"theme":"css-variables"}
> try:
> print(int(input()))
> except Exception:
> raise
> except TypeError:  # [bad-except-order]
> # This block cannot be reached since TypeError exception
> # is caught by previous exception handler.
> raise
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> try:
> print(int(input()))
> except TypeError:
> raise
> except Exception:
> raise
> ```

> [accordion] Exception cause set to something which is not an exception, nor None
>
> Flags instances where the cause of an exception (using the 'from' keyword) is set to something that is not an exception or None. The 'from' keyword is used for exception chaining, to help clarify the cause of secondary exceptions. Setting it incorrectly can lead to confusion and make error diagnosis more difficult.
>
> ```python Bad theme={"theme":"css-variables"}
> def divide(x, y):
> result = 0
> try:
>     result = x / y
> except ZeroDivisionError:
>     # +1: [bad-exception-cause]
>     raise ValueError(f"Division by zero when dividing {x} by {y} !") from result
> return result
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def divide(x, y):
> result = 0
> try:
>     result = x / y
> except ZeroDivisionError as exc:
>     raise ValueError(f"Division by zero when dividing {x} by {y} !") from exc
> return result
> ```

> [accordion] Unsupported format character %r (%#02x) at index %d
>
> Flags the use of an unsupported format character in a string format operation. This typically indicates a typo or misunderstanding of the format specification, and can lead to runtime errors or incorrect string formatting. Correcting these characters ensures the intended output is produced reliably.
>
> ```python Bad theme={"theme":"css-variables"}
> print("%s %z" % ("hello", "world"))  # [bad-format-character]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print("%s %s" % ("hello", "world"))
> ```

> [accordion] Invalid value for plugin
>
> Indicates an invalid value has been provided for a pylint plugin configuration. Plugins extend pylint's functionality, and providing valid configuration values is crucial for their correct operation. This rule helps maintain the integrity and usefulness of extended linting capabilities.

> [accordion] The first reversed() argument is not a sequence
>
> Warns when the first argument passed to reversed() is not a sequence. Since reversed() is designed to iterate over sequences in reverse order, passing a non-sequence type indicates a logical error in the code, potentially leading to runtime errors.
>
> ```python Bad theme={"theme":"css-variables"}
> reversed({1, 2, 3, 4})  # [bad-reversed-sequence]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> reversed([1, 2, 3, 4])
> ```

> [accordion] Suspicious argument in %s.%s call
>
> Identifies suspicious arguments passed to string strip methods (strip, lstrip, rstrip). These methods are often used incorrectly with multiple characters, leading to unexpected behavior. Ensuring the correct use of these methods helps maintain the intended functionality of string manipulation.

> [accordion] Argument %r does not match format type %r
>
> Flags format strings where an argument does not match the expected format type, indicating a mismatch between the data type of the argument and the format specifier. This can prevent runtime errors and ensure that string formatting operations produce the intended result.
>
> ```python Bad theme={"theme":"css-variables"}
> print("%d" % "1")  # [bad-string-format-type]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print("%d" % 1)
> ```

> [accordion] Bad first argument %r given to super()
>
> Detects incorrect first arguments given to super(), which can lead to incorrect method resolution and potentially runtime errors. Using super() correctly is crucial for accessing parent class methods reliably in inheritance hierarchies.
>
> ```python Bad theme={"theme":"css-variables"}
> class Animal:
> pass
>
>
> class Tree:
> pass
>
>
> class Cat(Animal):
> def __init__(self):
>     super(Tree, self).__init__()  # [bad-super-call]
>     super(Animal, self).__init__()
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Animal:
> pass
>
>
> class Tree:
> pass
>
>
> class Cat(Animal):
> def __init__(self):
>     super(Animal, self).__init__()
> ```

> [accordion] Contains control characters that can permit obfuscated code executed differently than displayed
>
> Highlights the presence of bidirectional Unicode text that may contain control characters capable of obfuscating code. This can make the code appear different from its actual execution, posing a security risk by hiding malicious code within seemingly benign text.
>
> ```python Bad theme={"theme":"css-variables"}
> # +1: [bidirectional-unicode]
> example = "x‏" * 100  #    "‏x" is assigned
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> example = "x[U+2194]" * 100
> ```

> [accordion] Broken callable in collections
>
> Points out issues with callables intended for use in collection classes that do not work as expected. Ensuring callables are correctly implemented is essential for the proper functioning of custom collection behaviors.
>
> ```python Bad theme={"theme":"css-variables"}
> from collections.abc import Callable
> from typing import Optional
>
>
> def func()  Optional[Callable[[int], None]]:  # [broken-collections-callable]
> ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from typing import Callable, Optional
>
>
> def func()  Optional[Callable[[int], None]]: ...
> ```

> [accordion] Non-returning function returns
>
> Flags functions declared to not return a value (e.g., by typing annotations) that contain return statements. This inconsistency can lead to confusion about the function's behavior and should be corrected for clarity and correctness.
>
> ```python Bad theme={"theme":"css-variables"}
> from typing import NoReturn, Union
>
>
> def exploding_apple(apple)  Union[None, NoReturn]:  # [broken-noreturn]
> print(f"{apple} is about to explode")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from typing import NoReturn
>
>
> def exploding_apple(apple)  NoReturn:
> print(f"{apple} is about to explode")
> raise Exception("{apple} exploded !")
> ```

> [accordion] Catching an exception which doesn't inherit from Exception: %s
>
> Warns about catching objects that do not inherit from Exception. Only objects derived from Exception should be caught by except clauses. This rule ensures that error handling in try-except blocks is correctly targeted and meaningful.
>
> ```python Bad theme={"theme":"css-variables"}
> class FooError:
> pass
>
>
> try:
> 1 / 0
> except FooError:  # [catching-non-exception]
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class FooError(Exception):
> pass
>
>
> try:
> 1 / 0
> except FooError:
> pass
> ```

> [accordion] Value %r in slots conflicts with class variable
>
> Detects conflicts between **slots** declarations and class variables. **slots** are used to declare instance variables and prevent the creation of **dict** and **weakref** for each instance, and conflicts can lead to unexpected behavior or inefficiencies.
>
> ```python Bad theme={"theme":"css-variables"}
> class Person:
> # +1: [class-variable-slots-conflict, class-variable-slots-conflict, class-variable-slots-conflict]
> __slots__ = ("age", "name", "say_hi")
> name = None
>
> def __init__(self, age, name):
>     self.age = age
>     self.name = name
>
> @property
> def age(self):
>     return self.age
>
> def say_hi(self):
>     print(f"Hi, I'm {self.name}.")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Person:
> __slots__ = ("_age", "name")
>
> def __init__(self, age, name):
>     self._age = age
>     self.name = name
>
> @property
> def age(self):
>     return self._age
>
> def say_hi(self):
>     print(f"Hi, I'm {self.name}.")
> ```

> [accordion] 'continue' not supported inside 'finally' clause
>
> Identifies the use of 'continue' within a 'finally' clause, which is not supported and can lead to a syntax error. This rule helps prevent control flow errors in complex try-except-finally structures.
>
> ```python Bad theme={"theme":"css-variables"}
> while True:
> try:
>     pass
> finally:
>     continue  # [continue-in-finally]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> while True:
> try:
>     pass
> except ValueError:
>     pass
> else:
>     continue
> ```

> [accordion] Unpacking a dictionary in iteration without calling .items()
>
> Flags the unpacking of a dictionary in iteration without explicitly calling .items(). This can lead to errors or unintended behavior when expecting key-value pairs but only keys are provided. Ensuring .items() is called makes the intention clear and the code more reliable.
>
> ```python Bad theme={"theme":"css-variables"}
> data = {"Paris": 2_165_423, "New York City": 8_804_190, "Tokyo": 13_988_129}
> for city, population in data:  # [dict-iter-missing-items]
> print(f"{city} has population {population}.")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> 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}.")
> ```

> [accordion] Duplicate argument name %s in function definition
>
> Detects duplicate argument names in a function definition, which can lead to confusion and errors in how arguments are passed and used within the function. Unique argument names ensure clarity in function signatures.
>
> ```python Bad theme={"theme":"css-variables"}
> def get_fruits(apple, banana, apple):  # [duplicate-argument-name]
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def get_fruits(apple, banana, orange):
> pass
> ```

> [accordion] Duplicate bases for class %r
>
> Warns about a class being defined with duplicate bases, which is redundant and can lead to confusion about the class's inheritance hierarchy. Removing duplicate bases clarifies the class structure.
>
> ```python Bad theme={"theme":"css-variables"}
> class Animal:
> pass
>
>
> class Cat(Animal, Animal):  # [duplicate-bases]
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Animal:
> pass
>
>
> class Bird(Animal):
> pass
>
>
> class Cat(Animal):
> pass
> ```

> [accordion] Expected mapping for format string, not %s
>
> Indicates a format string that expects a mapping (e.g., a dictionary) but is provided with a different type. This mismatch can lead to runtime errors during string formatting operations. Ensuring the correct type is provided to format strings maintains their intended functionality.
>
> ```python Bad theme={"theme":"css-variables"}
> print("%(x)d %(y)d" % [1, 2])  # [format-needs-mapping]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print("%(x)d %(y)d" % {"x": 1, "y": 2})
> ```

> [accordion] %s already defined line %s
>
> Flags instances where a function is redefined within the same scope, potentially overwriting the previous definition. This can lead to unexpected behavior and logic errors. Ensuring each function has a unique name within its scope prevents these issues.
>
> ```python Bad theme={"theme":"css-variables"}
> def get_email():
> pass
>
>
> def get_email():  # [function-redefined]
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def get_email():
> pass
> ```

> [accordion] Unable to import %s
>
> Indicates an error in importing a module or package, which could be due to a missing dependency, incorrect path, or other issues. Resolving import errors is crucial for ensuring that all code dependencies are correctly managed and accessible.
>
> ```python Bad theme={"theme":"css-variables"}
> from patlib import Path  # [import-error]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from pathlib import Path
> ```

> [accordion] Inconsistent method resolution order for class %r
>
> Detects classes with an inconsistent method resolution order (MRO), which can lead to errors in method inheritance and overriding. Ensuring a consistent MRO is essential for the predictable behavior of class hierarchies.
>
> ```python Bad theme={"theme":"css-variables"}
> class A:
> pass
>
>
> class B(A):
> pass
>
>
> class C(A, B):  # [inconsistent-mro]
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class A:
> pass
>
>
> class B(A):
> pass
>
>
> class C(B):  # or 'B, A' or 'A' but not 'A, B'
> pass
> ```

> [accordion] Inheriting %r, which is not a class.
>
> Flags instances where an attempt is made to inherit from a non-class object. This rule is important because Python's class inheritance mechanism requires that all bases of a class are themselves classes. Attempting to inherit from non-class objects will lead to a TypeError at runtime.
>
> ```python Bad theme={"theme":"css-variables"}
> class Fruit(bool):  # [inherit-non-class]
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Fruit:
> def __bool__(self):
>     pass
> ```

> [accordion] **init** method is a generator
>
> Identifies if the **init** method of a class is defined as a generator, which is incorrect because **init** should initialize the instance and cannot yield values. This rule helps prevent a common mistake that can lead to unexpected behavior or runtime errors.
>
> ```python Bad theme={"theme":"css-variables"}
> class Fruit:
> def __init__(self, worms):  # [init-is-generator]
>     yield from worms
>
>
> apple = Fruit(["Fahad", "Anisha", "Tabatha"])
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Fruit:
> def __init__(self, worms):
>     self.__worms = worms
>
> def worms(self):
>     yield from self.__worms
>
>
> apple = Fruit(["Fahad", "Anisha", "Tabatha"])
> for worm in apple.worms():
> pass
> ```

> [accordion] Invalid format for **all**, must be tuple or list
>
> Warns when the **all** variable, which should explicitly export module symbols, is not formatted as a tuple or list. Correctly defining **all** is crucial for module encapsulation and namespace control, ensuring that only intended names are exported.
>
> ```python Bad theme={"theme":"css-variables"}
> __all__ = "CONST"  # [invalid-all-format]
>
> CONST = 42
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> __all__ = ("CONST",)
>
> CONST = 42
> ```

> [accordion] Invalid object %r in **all**, must contain only strings
>
> Indicates that an object within the **all** list or tuple is not a string. Since **all** should contain the names of objects to be exported by a module, having non-string objects can lead to errors when the module is imported or used.
>
> ```python Bad theme={"theme":"css-variables"}
> __all__ = (
> None,  # [invalid-all-object]
> Fruit,
> Worm,
> )
>
>
> class Fruit:
> pass
>
>
> class Worm:
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> __all__ = ["Fruit", "Worm"]
>
>
> class Fruit:
> pass
>
>
> class Worm:
> pass
> ```

> [accordion] **bool** does not return bool
>
> Flags cases where a custom **bool** method does not return a boolean value. The **bool** method is used to determine the truth value of an object, and returning non-bool values can lead to incorrect behavior in boolean contexts.
>
> ```python Bad theme={"theme":"css-variables"}
> class CustomBool:
> """__bool__ returns an int"""
>
> def __bool__(self):  # [invalid-bool-returned]
>     return 1
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class CustomBool:
> """__bool__ returns `bool`"""
>
> def __bool__(self):
>     return True
> ```

> [accordion] **bytes** does not return bytes
>
> Identifies when a **bytes** method does not return a bytes object. This method should return the bytes representation of the object, and returning anything other than bytes can cause type errors or unexpected behavior.
>
> ```python Bad theme={"theme":"css-variables"}
> class CustomBytes:
> """__bytes__ returns <type 'str'>"""
>
> def __bytes__(self):  # [invalid-bytes-returned]
>     return "123"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class CustomBytes:
> """__bytes__ returns <type 'bytes'>"""
>
> def __bytes__(self):
>     return b"some bytes"
> ```

> [accordion] Invalid unescaped character backspace, use \\'\\\b\\' instead.
>
> Warns about the use of an invalid, unescaped backspace character in a string. It suggests using "" for a backspace character to avoid syntax errors or unintended behavior in strings.
>
> ```python Bad theme={"theme":"css-variables"}
> STRING = "Invalid character backspace "  # [invalid-character-backspace]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> STRING = "Valid character backspace "
> ```

> [accordion] Invalid unescaped character carriage-return, use \\'\\\r\\' instead.
>
> Highlights the use of an invalid, unescaped carriage return character, recommending the use of "
> " instead. Proper escaping is necessary to ensure the character is interpreted correctly by Python.

> [accordion] Invalid unescaped character esc, use \\'\\\x1B\\' instead.
>
> Flags the improper use of an unescaped ESC character in a string, suggesting the use of "" for clarity and correctness. Escaping special characters prevents errors in string processing.
>
> ```python Bad theme={"theme":"css-variables"}
> STRING = "Invalid escape character "  # [invalid-character-esc]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> STRING = "Valid escape character "
> ```

> [accordion] Invalid unescaped character nul, use \\'\\\0\\' instead.
>
> Indicates an invalid unescaped NUL character in a string, recommending the use of "�" instead. The NUL character must be properly escaped to be included in strings without causing errors.

> [accordion] Invalid unescaped character sub, use \\'\\\x1A\\' instead.
>
> Warns about the use of an unescaped SUB (substitute) character, advising to use "" for correct representation. Proper escaping ensures that control characters are treated correctly in strings.
>
> ```python Bad theme={"theme":"css-variables"}
> STRING = "Invalid character sub "  # [invalid-character-sub]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> STRING = "Valid character sub x1A"
> ```

> [accordion] Invalid unescaped character zero-width-space, use \\'\\\u200B\\' instead.
>
> Identifies the improper use of an unescaped zero-width space character, recommending "​" for correct inclusion in strings. Escaping this character is necessary to avoid syntax errors and ensure it is interpreted correctly.
>
> ```python Bad theme={"theme":"css-variables"}
> STRING = "Invalid character zero-width-space ​"  # [invalid-character-zero-width-space]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> STRING = "Valid character zero-width-space u200B"
> ```

> [accordion] Invalid assignment to '**class**'. Should be a class definition but got a '%s'
>
> Flags incorrect assignments to the '**class**' attribute, which should only be assigned class definitions. This rule helps maintain the integrity of the object model by ensuring '**class**' accurately reflects the object's class structure.
>
> ```python Bad theme={"theme":"css-variables"}
> class Apple:
> pass
>
>
> Apple.__class__ = 1  # [invalid-class-object]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Apple:
> pass
>
>
> class RedDelicious:
> pass
>
>
> Apple.__class__ = RedDelicious
> ```

> [accordion] Extending inherited Enum class \\'%s\\'
>
> Warns against extending an already inherited Enum class. Python's enum classes are designed to be final; extending them can lead to unexpected behavior or errors. This rule ensures that enums are used as intended, providing clear, immutable sets of named values.
>
> ```python Bad theme={"theme":"css-variables"}
> from enum import Enum
>
>
> class Color(Enum):
> ORANGE = 1
> CHERRY = 2
>
>
> class Fruit(Color):  # [invalid-enum-extension]
> APPLE = 3
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from enum import Enum
>
>
> class Color(Enum):
> ORANGE = 1
> CHERRY = 2
>
>
> class Fruit(Enum):
> ORANGE = 1
> CHERRY = 2
> APPLE = 3
> ```

> [accordion] %s does not support %s type argument
>
> Indicates that an environment variable does not support a given type argument, highlighting the importance of ensuring environment variables are correctly parsed and validated to match the expected types used in the application.
>
> ```python Bad theme={"theme":"css-variables"}
> import os
>
> os.getenv(1)  # [invalid-envvar-value]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import os
>
> os.getenv("1")
> ```

> [accordion] Invalid usage of field(), %s
>
> Flags incorrect usage of the field() function, typically seen in data classes. This rule helps ensure that field definitions are correct and conform to the expectations of Python's data model, preventing runtime errors.
>
> ```python Bad theme={"theme":"css-variables"}
> from dataclasses import dataclass, field
>
>
> @dataclass
> class C:
> a: float
> b: float
> c: float
>
> field(init=False)  # [invalid-field-call]
>
> def __post_init__(self):
>     self.c = self.a + self.b
>
>
> print(field(init=False))  # [invalid-field-call]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from dataclasses import dataclass, field, make_dataclass
>
> C = make_dataclass(
> "C",
> [("x", int), "y", ("z", int, field(default=5))],
> namespace={"add_one": lambda self: self.x + 1},
> )
>
>
> @dataclass
> class C:
> a: float
> b: float
> c: float = field(init=False)
>
> def __post_init__(self):
>     self.c = self.a + self.b
> ```

> [accordion] **format** does not return str
>
> Identifies when a custom **format** method does not return a string. Since **format** is used in string formatting operations, returning any other type can cause type errors or unexpected behavior in formatted strings.
>
> ```python Bad theme={"theme":"css-variables"}
> class CustomFormat:
> """__format__ returns <type 'int'>"""
>
> def __format__(self, format_spec):  # [invalid-format-returned]
>     return 1
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class CustomFormat:
> """__format__ returns <type 'str'>"""
>
> def __format__(self, format_spec):
>     return "hello!"
> ```

> [accordion] **getnewargs\_ex** does not return a tuple containing (tuple, dict)
>
> Warns if **getnewargs\_ex** does not return a tuple containing a tuple and a dict. This method is crucial for customizing pickling behavior, and its return values must conform to this structure to ensure objects are pickled and unpickled correctly.
>
> ```python Bad theme={"theme":"css-variables"}
> class CustomGetNewArgsEx:
> """__getnewargs_ex__ returns tuple with incorrect arg length"""
>
> def __getnewargs_ex__(self):  # [invalid-getnewargs-ex-returned]
>     return (tuple(1), dict(x="y"), 1)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class CustomGetNewArgsEx:
> """__getnewargs_ex__ returns <type 'tuple'>"""
>
> def __getnewargs_ex__(self):
>     return ((1,), {"2": 2})
> ```

> [accordion] **getnewargs** does not return a tuple
>
> Flags cases where **getnewargs** does not return a tuple. Similar to **getnewargs\_ex**, this method supports pickling and must return a tuple to function correctly, ensuring objects can be serialized and deserialized properly.
>
> ```python Bad theme={"theme":"css-variables"}
> class CustomGetNewArgs:
> """__getnewargs__ returns an integer"""
>
> def __getnewargs__(self):  # [invalid-getnewargs-returned]
>     return 1
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class CustomGetNewArgs:
> """__getnewargs__ returns <type 'tuple'>"""
>
> def __getnewargs__(self):
>     return (1, 2)
> ```

> [accordion] **hash** does not return int
>
> Indicates that a custom **hash** method does not return an integer. Since hashes are used to uniquely identify objects, especially in collections like sets and dictionaries, returning non-int values can lead to incorrect behavior or errors.
>
> ```python Bad theme={"theme":"css-variables"}
> class CustomHash:
> """__hash__ returns dict"""
>
> def __hash__(self):  # [invalid-hash-returned]
>     return {}
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class CustomHash:
> """__hash__ returns `int`"""
>
> def __hash__(self):
>     return 19
> ```

> [accordion] **index** does not return int
>
> Warns when **index** does not return an integer. The **index** method should return an integer to be used when the object is operated on by built-in functions and operators expecting a numerical index, ensuring correct integration with Python's data model.
>
> ```python Bad theme={"theme":"css-variables"}
> class CustomIndex:
> """__index__ returns a dict"""
>
> def __index__(self):  # [invalid-index-returned]
>     return {"19": "19"}
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class CustomIndex:
> """__index__ returns <type 'int'>"""
>
> def __index__(self):
>     return 19
> ```

> [accordion] **length\_hint** does not return non-negative integer
>
> Identifies when **length\_hint** does not return a non-negative integer. This method is used to provide an estimate of the number of elements in an iterable, and returning incorrect types or values can mislead functions that rely on this hint for optimization.
>
> ```python Bad theme={"theme":"css-variables"}
> class CustomLengthHint:
> """__length_hint__ returns non-int"""
>
> def __length_hint__(self):  # [invalid-length-hint-returned]
>     return 3.0
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class CustomLengthHint:
> """__length_hint__ returns <type 'int'>"""
>
> def __length_hint__(self):
>     return 10
> ```

> [accordion] **len** does not return non-negative integer
>
> Flags incorrect return types from **len**, which must always return a non-negative integer. This ensures that the length of a collection is accurately reported, supporting Python's built-in len() function and the sizing of collections.
>
> ```python Bad theme={"theme":"css-variables"}
> class FruitBasket:
> def __init__(self, fruits):
>     self.fruits = ["Apple", "Banana", "Orange"]
>
> def __len__(self):  # [invalid-length-returned]
>     return -len(self.fruits)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class FruitBasket:
> def __init__(self, fruits):
>     self.fruits = ["Apple", "Banana", "Orange"]
>
> def __len__(self):
>     return len(self.fruits)
> ```

> [accordion] Invalid metaclass %r used
>
> Highlights the use of an invalid metaclass. Metaclasses are used in Python to control the creation of classes, and using an incorrect metaclass can lead to unexpected behavior or errors in class creation and inheritance.
>
> ```python Bad theme={"theme":"css-variables"}
> class Apple(metaclass=int):  # [invalid-metaclass]
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Plant:
> pass
>
>
> class Apple(Plant):
> pass
> ```

> [accordion] **repr** does not return str
>
> Warns if **repr** does not return a string. The **repr** method should provide a clear, unambiguous string representation of an object for debugging and logging, and returning a non-string violates this contract.
>
> ```python Bad theme={"theme":"css-variables"}
> class CustomRepr:
> """__repr__ returns <type 'int'>"""
>
> def __repr__(self):  # [invalid-repr-returned]
>     return 1
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class CustomRepr:
> """__repr__ returns <type 'str'>"""
>
> def __repr__(self):
>     return "apples"
> ```

> [accordion] Sequence index is not an int, slice, or instance with **index**
>
> Indicates that an index used on a sequence is not of a valid type. Valid types include integers, slices, or instances with an **index** method. Ensuring indexes are of the correct type is crucial for the predictable behavior of sequence operations.
>
> ```python Bad theme={"theme":"css-variables"}
> fruits = ["apple", "banana", "orange"]
> print(fruits["apple"])  # [invalid-sequence-index]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> fruits = ["apple", "banana", "orange"]
> print(fruits[0])
> ```

> [accordion] Slice index is not an int, None, or instance with **index**
>
> Flags slice indexes that are not integers, None, or instances with an **index** method. Correct slice indexes are essential for the expected slicing behavior of sequences, supporting flexible and error-free slicing operations.
>
> ```python Bad theme={"theme":"css-variables"}
> LETTERS = ["a", "b", "c", "d"]
>
> FIRST_THREE = LETTERS[:"3"]  # [invalid-slice-index]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> LETTERS = ["a", "b", "c", "d"]
>
> FIRST_THREE = LETTERS[:3]
> ```

> [accordion] Slice step cannot be 0
>
> Identifies slice steps that are set to 0, which is invalid since a step of 0 would result in an undefined slice. This rule ensures that slices are defined with a valid step, avoiding runtime errors and maintaining the integrity of slice operations.
>
> ```python Bad theme={"theme":"css-variables"}
> LETTERS = ["a", "b", "c", "d"]
>
> LETTERS[::0]  # [invalid-slice-step]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> LETTERS = ["a", "b", "c", "d"]
>
> LETTERS[::2]
> ```

> [accordion] Invalid **slots** object
>
> Flags an incorrectly defined **slots** object. The **slots** declaration is used to explicitly declare data members and prevent the creation of **dict** and **weakref** for each instance, optimizing memory usage. Invalid **slots** definitions can lead to runtime errors or unintended behavior.
>
> ```python Bad theme={"theme":"css-variables"}
> class Person:  # [invalid-slots]
> __slots__ = 42
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Person:
> __slots__ = ("name", "age")
> ```

> [accordion] Invalid object %r in **slots**, must contain only non empty strings
>
> Indicates that an object within **slots** is not a valid non-empty string. **slots** should contain names of instance attributes, defined as non-empty strings, to properly allocate space for them. Invalid objects in **slots** can prevent the expected optimization and might cause attribute errors.
>
> ```python Bad theme={"theme":"css-variables"}
> class Person:
> __slots__ = ("name", 3)  # [invalid-slots-object]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Person:
> __slots__ = ("name", "surname")
> ```

> [accordion] Starred assignment target must be in a list or tuple
>
> Warns when a starred expression is used outside of a list or tuple context. Starred expressions are used for unpacking iterables and must be part of a list or tuple assignment, ensuring correct and predictable unpacking behavior.
>
> ```python Bad theme={"theme":"css-variables"}
> *fruit = ["apple", "banana", "orange"]  # [invalid-star-assignment-target]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> fruit = ["apple", "banana", "orange"]
> ```

> [accordion] **str** does not return str
>
> Identifies when a custom **str** method does not return a string. The **str** method should provide a readable string representation of an object, and returning a non-string type can lead to type errors and misunderstandings about the object's representation.
>
> ```python Bad theme={"theme":"css-variables"}
> class CustomStr:
> """__str__ returns int"""
>
> def __str__(self):  # [invalid-str-returned]
>     return 1
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class CustomStr:
> """__str__ returns <type 'str'>"""
>
> def __str__(self):
>     return "oranges"
> ```

> [accordion] Invalid unary operand type
>
> Flags an invalid operand type for a unary operation, such as negation or bitwise not. This rule ensures that unary operations are used with compatible types, preventing runtime type errors and promoting type-safe operations.
>
> ```python Bad theme={"theme":"css-variables"}
> cherries = 10
> eaten_cherries = int
> cherries = -eaten_cherries  # [invalid-unary-operand-type]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> cherries = 10
> eaten_cherries = 2
> cherries -= eaten_cherries
> ```

> [accordion] UTF-16 and UTF-32 aren't backward compatible. Use UTF-8 instead
>
> Advises against using UTF-16 or UTF-32 due to their lack of backward compatibility with ASCII, recommending UTF-8 instead. UTF-8 is universally accepted and provides better compatibility and efficiency, especially for web and internationalized applications.

> [accordion] Logging format string ends in middle of conversion specifier
>
> Warns when a logging format string is truncated, ending in the middle of a conversion specifier. This can lead to incomplete log messages and is usually the result of an accidental omission or typo in the format string.
>
> ```python Bad theme={"theme":"css-variables"}
> import logging
> import sys
>
> logging.warning("Python version: %", sys.version)  # [logging-format-truncated]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import logging
> import sys
>
> logging.warning("Python version: %s", sys.version)
> ```

> [accordion] Not enough arguments for logging format string
>
> Indicates that there are not enough arguments provided to a logging format string, which can result in a runtime error when the logging statement is executed. Ensuring the correct number of arguments for format strings is essential for accurate and error-free logging.
>
> ```python Bad theme={"theme":"css-variables"}
> import logging
>
> try:
> function()
> except Exception as e:
> logging.error("%s error occurred: %s", e)  # [logging-too-few-args]
> raise
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import logging
>
> try:
> function()
> except Exception as e:
> logging.error("%s error occurred: %s", type(e), e)
> raise
> ```

> [accordion] Too many arguments for logging format string
>
> Flags when more arguments are provided to a logging format string than placeholders available in the string. This can lead to unused arguments and might indicate a misunderstanding of the format string's requirements or an error in argument preparation.
>
> ```python Bad theme={"theme":"css-variables"}
> import logging
>
> try:
> function()
> except Exception as e:
> logging.error("Error occurred: %s", type(e), e)  # [logging-too-many-args]
> raise
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import logging
>
> try:
> function()
> except Exception as e:
> logging.error("%s error occurred: %s", type(e), e)
> raise
> ```

> [accordion] Unsupported logging format character %r (%#02x) at index %d
>
> Identifies an unsupported format character in a logging statement. This rule helps ensure that logging format strings are correctly formed, using only supported format specifiers to prevent runtime errors or malformed log messages.
>
> ```python Bad theme={"theme":"css-variables"}
> import logging
>
> logging.info("%s %y !", "Hello", "World")  # [logging-unsupported-format]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import logging
>
> logging.info("%s %s !", "Hello", "World")
> ```

> [accordion] An attribute defined in %s line %s hides this method
>
> Warns when an attribute defined elsewhere hides a method of the same name. This can lead to unexpected behavior, as the attribute will take precedence over the method, potentially causing errors or confusion about the object's interface.
>
> ```python Bad theme={"theme":"css-variables"}
> class Fruit:
> def __init__(self, vitamins):
>     self.vitamins = vitamins
>
> def vitamins(self):  # [method-hidden]
>     pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Fruit:
> def __init__(self, vitamins):
>     self.vitamins = vitamins
>
> def antioxidants(self):
>     pass
> ```

> [accordion] The raise statement is not inside an except clause
>
> Indicates a raise statement used outside of an except clause, which can lead to a RuntimeError since there's no active exception to re-raise. This rule ensures that raise statements are used correctly, within the context of exception handling.
>
> ```python Bad theme={"theme":"css-variables"}
> def validate_positive(x):
> if x <= 0:
>     raise  # [misplaced-bare-raise]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def validate_positive(x):
> if x <= 0:
>     raise ValueError(f"{x} is not positive")
> ```

> [accordion] format function is not called on str
>
> Flags when the format function is used on an object that is not a string. Since format is intended for string formatting, calling it on non-strings is likely an error and can lead to unexpected behavior or type errors.
>
> ```python Bad theme={"theme":"css-variables"}
> print("Value: {}").format("Car")  # [misplaced-format-function]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print("Value: {}".format("Car"))
> ```

> [accordion] Missing key %r in format string dictionary
>
> Identifies when a key referenced in a format string is missing from the format string's dictionary argument. This can lead to a KeyError at runtime, making it important to ensure that all keys used in format strings are provided in the accompanying dictionary.
>
> ```python Bad theme={"theme":"css-variables"}
> # +1: [missing-format-string-key]
> fruit_prices = """
> Apple: %(apple_price)d ¤
> Orange: %(orange_price)d ¤
> """ % {
> "apple_price": 42
> }
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> fruit_prices = """
> Apple: %(apple_price)d ¤
> Orange: %(orange_price)d ¤
> """ % {
> "apple_price": 42,
> "orange_price": 87,
> }
> ```

> [accordion] Missing mandatory keyword argument %r in %s call
>
> Flags a function call missing a mandatory keyword-only argument. This rule ensures that all required arguments are provided in function calls, particularly important for functions that define parameters with the keyword-only syntax, improving code reliability and preventing runtime errors.
>
> ```python Bad theme={"theme":"css-variables"}
> def target(pos, *, keyword):
> return pos + keyword
>
>
> def not_forwarding_kwargs(*args, **kwargs):
> target(*args)  # [missing-kwoa]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def target(pos, *, keyword):
> return pos + keyword
>
>
> def not_forwarding_kwargs(*args, **kwargs):
> target(*args, **kwargs)
> ```

> [accordion] Mixing named and unnamed conversion specifiers in format string
>
> Warns against mixing named and unnamed placeholders within a single format string. This practice can lead to confusion and errors in string formatting, and maintaining consistency in format specifiers enhances readability and predictability of the output.

> [accordion] Iterated dict '%s' is being modified inside for loop body, iterate through a copy of it instead.
>
> Indicates that a dictionary being iterated over in a for loop is also being modified within the loop. Modifying a collection while iterating over it can lead to runtime errors or unpredictable behavior. Iterating over a copy of the dictionary is recommended to avoid such issues.
>
> ```python Bad theme={"theme":"css-variables"}
> fruits = {"apple": 1, "orange": 2, "mango": 3}
>
> i = 0
> for fruit in fruits:
> fruits["apple"] = i  # [modified-iterating-dict]
> i += 1
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> fruits = {"apple": 1, "orange": 2, "mango": 3}
>
> i = 0
> for fruit in fruits.copy():
> fruits["apple"] = i
> i += 1
> ```

> [accordion] Iterated set '%s' is being modified inside for loop body, iterate through a copy of it instead.
>
> Similar to the above, warns when a set being iterated over is modified within the loop. As with dictionaries, this can cause unexpected behavior or errors, and iterating over a copy of the set is advised to maintain correct and predictable iteration behavior.
>
> ```python Bad theme={"theme":"css-variables"}
> fruits = {"apple", "orange", "mango"}
> for fruit in fruits:
> fruits.add(fruit + "yum")  # [modified-iterating-set]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> fruits = {"apple", "orange", "mango"}
> for fruit in fruits.copy():
> fruits.add(fruit + "yum")
> ```

> [accordion] %s %r has no %r member%s
>
> Flags the access of a non-existent member of an object or class, indicating a potential attribute error or a misunderstanding of the object's interface. This rule helps prevent runtime errors by ensuring that only existing members are accessed.
>
> ```python Bad theme={"theme":"css-variables"}
> from pathlib import Path
>
> directories = Path(".").mothers  # [no-member]
>
>
> class Cat:
> def meow(self):
>     print("Meow")
>
>
> Cat().roar()  # [no-member]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from pathlib import Path
>
> directories = Path(".").parents
>
>
> class Cat:
> def meow(self):
>     print("Meow")
>
>
> Cat().meow()
> ```

> [accordion] Method %r has no argument
>
> Indicates a method definition is missing an argument. This can lead to errors when the method is called and is especially critical for methods expected to adhere to a specific signature, such as those defined in interfaces or base classes.
>
> ```python Bad theme={"theme":"css-variables"}
> class Person:
> def print_greeting():  # [no-method-argument]
>     print("hello")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Person:
> def print_greeting(self):
>     print("hello")
> ```

> [accordion] No name %r in module %r
>
> Warns when an attempt is made to import a name from a module, but the name does not exist in that module. This can lead to ImportError at runtime and is often the result of a typo or misunderstanding of the module's API.
>
> ```python Bad theme={"theme":"css-variables"}
> from os import pizza  # [no-name-in-module]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from os import path
> ```

> [accordion] Method %r should have \\'self\\' as first argument
>
> Flags a method that does not include self as its first argument, which is required for instance methods in classes to correctly refer to the object instance upon which they are called. Ensuring self is the first argument is fundamental for the method's access to the instance and its attributes.
>
> ```python Bad theme={"theme":"css-variables"}
> class Fruit:
> def __init__(this, name):  # [no-self-argument]
>     this.name = name
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Fruit:
> def __init__(self, name):
>     self.name = name
> ```

> [accordion] No value for argument %s in %s call
>
> Indicates that a required parameter is missing a value in a function call. This rule ensures that all necessary arguments are provided to functions, preventing TypeError due to missing arguments and improving function call correctness.
>
> ```python Bad theme={"theme":"css-variables"}
> def add(x, y):
> return x + y
>
>
> add(1)  # [no-value-for-parameter]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def add(x, y):
> return x + y
>
>
> add(1, 2)
> ```

> [accordion] **iter** returns non-iterator
>
> Warns if the **iter** method of a class does not return an iterator object. For a class to be iterable, its **iter** method must return an object that implements the **next** method, ensuring compatibility with iteration protocols.
>
> ```python Bad theme={"theme":"css-variables"}
> import random
>
>
> class GenericAstrology:
> def __init__(self, signs, predictions):
>     self.signs = signs
>     self.predictions = predictions
>
> def __iter__(self):  # [non-iterator-returned]
>     self.index = 0
>     self.number_of_prediction = len(self.predictions)
>     return self
>
>
> SIGNS = ["Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra"]
> PREDICTIONS = ["good things", "bad thing", "existential dread"]
> for sign, prediction in GenericAstrology(SIGNS, PREDICTIONS):
> print(f"{sign} : {prediction} today")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import random
>
>
> class GenericAstrology:
> def __init__(self, signs, predictions):
>     self.signs = signs
>     self.predictions = predictions
>
> def __iter__(self):
>     self.index = 0
>     self.number_of_prediction = len(self.predictions)
>     return self
>
> def __next__(self):
>     if self.index == len(self.signs):
>         raise StopIteration
>     self.index += 1
>     prediction_index = random.randint(0, self.number_of_prediction - 1)
>     return self.signs[self.index - 1], self.predictions[prediction_index]
>
>
> SIGNS = ["Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra"]
> PREDICTIONS = ["good things", "bad thing", "existential dread"]
> for sign, prediction in GenericAstrology(SIGNS, PREDICTIONS):
> print(f"{sign} : {prediction} today")
> ```

> [accordion] Use of the non-existent %s operator
>
> Flags the use of an operator that does not exist in Python. This rule helps identify typos or misconceptions about Python's operators, preventing syntax errors or incorrect assumptions about code behavior.
>
> ```python Bad theme={"theme":"css-variables"}
> i = 0
>
> while i <= 10:
> print(i)
> ++i  # [nonexistent-operator]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> i = 0
>
> while i <= 10:
> print(i)
> i += 1
> ```

> [accordion] Name %r is nonlocal and global
>
> Indicates a variable is declared both nonlocal and global, which is contradictory as nonlocal refers to variables in enclosing scopes, excluding the global scope. This rule clarifies scope usage and prevents scope resolution conflicts.
>
> ```python Bad theme={"theme":"css-variables"}
> NUMBER = 42
>
>
> def update_number(number):  # [nonlocal-and-global]
> global NUMBER
> nonlocal NUMBER
> NUMBER = number
> print(f"New global number is: {NUMBER}")
>
>
> update_number(24)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> NUMBER = 42
>
>
> def update_number(number):
> global NUMBER
> NUMBER = number
> print(f"New global number is: {NUMBER}")
>
>
> update_number(24)
> ```

> [accordion] nonlocal name %s found without binding
>
> Warns when a nonlocal statement is used for a name that does not have an existing binding in any enclosing scopes, which can lead to errors since nonlocal is intended to refer to previously defined variables in outer non-global scopes.
>
> ```python Bad theme={"theme":"css-variables"}
> class Fruit:
> def get_color(self):
>     nonlocal colors  # [nonlocal-without-binding]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Fruit:
> colors = ["red", "green"]
>
> def get_color(self):
>     nonlocal colors
> ```

> [accordion] Non-mapping value %s is used in a mapping context
>
> Flags when a value that is not a mapping (e.g., not a dict or similar) is used in a context that expects a mapping, such as in unpacking operations. This rule ensures that values used in mapping contexts correctly support the mapping interface.
>
> ```python Bad theme={"theme":"css-variables"}
> def print_colors(**colors):
> print(colors)
>
>
> print_colors(**list("red", "black"))  # [not-a-mapping]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def print_colors(**colors):
> print(colors)
>
>
> print_colors(**dict(red=1, black=2))
> ```

> [accordion] Non-iterable value %s is used in an iterating context
>
> Indicates a value used in a context that requires iteration, such as a for loop, does not support iteration. This rule is essential for preventing runtime errors by ensuring that only iterable objects are used in iterating contexts.
>
> ```python Bad theme={"theme":"css-variables"}
> for i in 10:  # [not-an-iterable]
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> for i in "10":
> pass
> ```

> [accordion] Async context manager '%s' doesn't implement **aenter** and **aexit**.
>
> Warns that an object meant to be used as an async context manager (with an async with statement) does not implement the required **aenter** and **aexit** methods. Implementing these methods is crucial for the correct operation of async context managers, enabling asynchronous resource management.
>
> ```python Bad theme={"theme":"css-variables"}
> class ContextManager:
> def __enter__(self):
>     pass
>
> def __exit__(self, *exc):
>     pass
>
>
> async def foo():
> async with ContextManager():  # [not-async-context-manager]
>     pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class AsyncContextManager:
> def __aenter__(self):
>     pass
>
> def __aexit__(self, *exc):
>     pass
>
>
> async def foo():
> async with AsyncContextManager():
>     pass
> ```

# Step 2

> [accordion] %s is not callable
>
> Flags an attempt to call an object that is not callable, indicating a type error. This rule is critical for identifying objects being used incorrectly as functions or methods, ensuring that only callable objects are invoked, which helps prevent runtime errors.
>
> ```python Bad theme={"theme":"css-variables"}
> NUMBER = 42
> print(NUMBER())  # [not-callable]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> NUMBER = 42
> print(NUMBER)
> ```

> [accordion] Context manager '%s' doesn't implement **enter** and **exit**.
>
> Indicates that an object expected to function as a context manager does not implement the **enter** and **exit** methods. For an object to manage resources with a 'with' statement, implementing these methods is essential for correct resource acquisition and release.
>
> ```python Bad theme={"theme":"css-variables"}
> class MyContextManager:
> def __enter__(self):
>     pass
>
>
> with MyContextManager() as c:  # [not-context-manager]
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyContextManager:
> def __enter__(self):
>     pass
>
> def __exit__(self, *exc):
>     pass
>
>
> with MyContextManager() as c:
> pass
> ```

> [accordion] %r not properly in loop
>
> Flags the use of break or continue statements outside of a loop, which is a syntactic error. This rule helps ensure that these control flow statements are used correctly within the context of loops to manage loop execution properly.
>
> ```python Bad theme={"theme":"css-variables"}
> def print_even_numbers():
> for i in range(100):
>     if i % 2 == 0:
>         print(i)
> else:
>     continue  # [not-in-loop]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def print_even_numbers():
> for i in range(100):
>     if i % 2:
>         continue
>     print(i)
> ```

> [accordion] NotImplemented raised - should raise NotImplementedError
>
> Warns when NotImplemented is raised instead of NotImplementedError. NotImplemented is a special value used for binary methods to indicate that an operation is not implemented for the given operands, whereas NotImplementedError should be raised when an abstract method or function is not implemented.
>
> ```python Bad theme={"theme":"css-variables"}
> class Worm:
> def bore(self):
>     raise NotImplemented  # [notimplemented-raised]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Worm:
> def bore(self):
>     raise NotImplementedError
> ```

> [accordion] `%s()` got some positional-only arguments passed as keyword arguments: %s
>
> Flags the incorrect passing of positional-only arguments as keyword arguments in function calls. This rule ensures that arguments are passed according to the function signature, respecting positional-only restrictions to prevent TypeError.
>
> ```python Bad theme={"theme":"css-variables"}
> def cube(n, /):
> """Takes in a number n, returns the cube of n"""
> return n**3
>
>
> cube(n=2)  # [positional-only-arguments-expected]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def cube(n, /):
> """Takes in a number n, returns the cube of n"""
> return n**3
>
>
> cube(2)
> ```

> [accordion] Invalid index for iterable length
>
> Indicates a potential error when accessing an index that may be out of bounds for the given iterable. This rule helps identify possible IndexError before runtime by analyzing patterns that could lead to accessing invalid indexes.
>
> ```python Bad theme={"theme":"css-variables"}
> print([1, 2, 3][3])  # [potential-index-error]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print([1, 2, 3][2])
> ```

> [accordion] Raising %s while only classes or instances are allowed
>
> Flags an attempt to raise an object that is neither an exception class nor an instance of one. This rule ensures that only valid exceptions are raised, adhering to Python's error handling model and preventing runtime errors.
>
> ```python Bad theme={"theme":"css-variables"}
> class FasterThanTheSpeedOfLightError(ZeroDivisionError):
> def __init__(self):
>     super().__init__("You can't go faster than the speed of light !")
>
>
> def calculate_speed(distance: float, time: float)  float:
> try:
>     return distance / time
> except ZeroDivisionError as e:
>     raise None  # [raising-bad-type]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class FasterThanTheSpeedOfLightError(ZeroDivisionError):
> def __init__(self):
>     super().__init__("You can't go faster than the speed of light !")
>
>
> def calculate_speed(distance: float, time: float)  float:
> try:
>     return distance / time
> except ZeroDivisionError as e:
>     raise FasterThanTheSpeedOfLightError() from e
> ```

> [accordion] Raising a new style class which doesn't inherit from BaseException
>
> Warns when an attempt is made to raise a class that does not inherit from BaseException, which is required for all exception classes. This rule helps maintain the integrity of the exception handling system by ensuring that only valid exceptions are used.
>
> ```python Bad theme={"theme":"css-variables"}
> raise str  # [raising-non-exception]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> raise Exception("Goodbye world !")
> ```

> [accordion] Argument %r passed by position and keyword in %s call
>
> Indicates that an argument is passed both by position and keyword in the same function call, which can lead to confusion and errors. This rule helps ensure clarity and consistency in function calls by preventing redundant argument specification.

> [accordion] Attempted relative import beyond top-level package
>
> Flags an attempted relative import that goes beyond the top-level package, which is not allowed. This rule helps maintain proper package structure and import semantics, preventing ImportError caused by invalid relative import paths.

> [accordion] Got multiple values for keyword argument %r in function call
>
> Warns when a keyword argument is specified multiple times in a function call, which is a TypeError. This rule ensures that each keyword argument is uniquely specified, preventing ambiguous or conflicting argument values.
>
> ```python Bad theme={"theme":"css-variables"}
> def func(a, b, c):
> return a, b, c
>
>
> func(1, 2, c=3, **{"c": 4})  # [repeated-keyword]
> func(1, 2, **{"c": 3}, **{"c": 4})  # [repeated-keyword]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def func(a, b, c):
> return a, b, c
>
>
> func(1, 2, c=3)
> ```

> [accordion] Return with argument inside generator
>
> Indicates the use of a return statement with an argument in a generator function, which is not allowed. In Python 3, return in a generator can only be used without an argument to signal the generator's termination. This rule helps prevent syntax errors and maintains the correct use of generators.

> [accordion] Explicit return in **init**
>
> Flags the use of an explicit return statement with a value in the **init** method of a class. Since **init** is meant to initialize an instance and not return a value, using return with a value can lead to confusion and is considered incorrect in Python.
>
> ```python Bad theme={"theme":"css-variables"}
> class Sum:
> def __init__(self, a, b):  # [return-in-init]
>     return a + b
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Sum:
> def __init__(self, a, b)  None:
>     self.result = a + b
> ```

> [accordion] Return outside function
>
> Indicates a return statement used outside of a function or method definition, which is a syntax error. This rule helps ensure that return statements are correctly placed within the functional or methodological scope.
>
> ```python Bad theme={"theme":"css-variables"}
> return 42  # [return-outside-function]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def get_the_answer():
> return 42
> ```

> [accordion] singledispatch decorator should not be used with methods, use singledispatchmethod instead.
>
> Warns against using the singledispatch decorator with methods, as it's designed for standalone functions. Python 3.8 introduced singledispatchmethod for methods to support single dispatch based on the type of the first argument in method calls.
>
> ```python Bad theme={"theme":"css-variables"}
> from functools import singledispatch
>
>
> class Board:
> @singledispatch  # [singledispatch-method]
> @classmethod
> def convert_position(cls, position):
>     pass
>
> @convert_position.register  # [singledispatch-method]
> @classmethod
> def _(cls, position: str)  tuple:
>     position_a, position_b = position.split(",")
>     return (int(position_a), int(position_b))
>
> @convert_position.register  # [singledispatch-method]
> @classmethod
> def _(cls, position: tuple)  str:
>     return f"{position[0]},{position[1]}"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from functools import singledispatch
>
>
> class Board:
> @singledispatch
> @staticmethod
> def convert_position(position):
>     pass
>
> @convert_position.register
> @staticmethod
> def _(position: str)  tuple:
>     position_a, position_b = position.split(",")
>     return (int(position_a), int(position_b))
>
> @convert_position.register
> @staticmethod
> def _(position: tuple)  str:
>     return f"{position[0]},{position[1]}"
> ```

> [accordion] singledispatchmethod decorator should not be used with functions, use singledispatch instead.
>
> Indicates the misuse of singledispatchmethod decorator with standalone functions. singledispatchmethod is intended for use with methods, while singledispatch is designed for functions, ensuring that the correct decorator is used for single dispatch functionality.
>
> ```python Bad theme={"theme":"css-variables"}
> from functools import singledispatchmethod
>
>
> class Board:
> @singledispatchmethod  # [singledispatchmethod-function]
> @staticmethod
> def convert_position(position):
>     pass
>
> @convert_position.register  # [singledispatchmethod-function]
> @staticmethod
> def _(position: str)  tuple:
>     position_a, position_b = position.split(",")
>     return (int(position_a), int(position_b))
>
> @convert_position.register  # [singledispatchmethod-function]
> @staticmethod
> def _(position: tuple)  str:
>     return f"{position[0]},{position[1]}"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from functools import singledispatchmethod
>
>
> class Board:
> @singledispatchmethod
> def convert_position(cls, position):
>     pass
>
> @singledispatchmethod
> @classmethod
> def _(cls, position: str)  tuple:
>     position_a, position_b = position.split(",")
>     return (int(position_a), int(position_b))
>
> @singledispatchmethod
> @classmethod
> def _(cls, position: tuple)  str:
>     return f"{position[0]},{position[1]}"
> ```

> [accordion] Can use starred expression only in assignment target
>
> Flags a starred expression used in a context other than as an assignment target, such as in a function call or outside a list/tuple on the right side of an assignment. Starred expressions are only valid when unpacking values in an assignment.
>
> ```python Bad theme={"theme":"css-variables"}
> stars = *["Sirius", "Arcturus", "Vega"]  # [star-needs-assignment-target]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> sirius, *arcturus_and_vega = ["Sirius", "Arcturus", "Vega"]
> ```

> [accordion] Syntax error detected
>
> Indicates a syntax error detected in the code, which will prevent the program from running. This rule is fundamental for identifying areas of the code that are incorrectly written and need correction for proper execution.
>
> ```python Bad theme={"theme":"css-variables"}
> fruit_stock = {
> 'apple': 42,
> 'orange': 21  # [syntax-error]
> 'banana': 12
> }
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> fruit_stock = {"apple": 42, "orange": 21, "banana": 12}
> ```

> [accordion] Not enough arguments for format string
>
> Warns when there are not enough arguments provided to a format string, leading to a runtime error when the string formatting is attempted. Ensuring the correct number of arguments for format strings is crucial for accurate and error-free string formatting.
>
> ```python Bad theme={"theme":"css-variables"}
> print("Today is {0}, so tomorrow will be {1}".format("Monday"))  # [too-few-format-args]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print("Today is {0}, so tomorrow will be {1}".format("Monday", "Tuesday"))
> ```

> [accordion] Too many arguments for format string
>
> Indicates that more arguments are provided to a format string than there are placeholders for those arguments. This can lead to unused arguments and might suggest a misunderstanding of the format string's requirements.
>
> ```python Bad theme={"theme":"css-variables"}
> # +1: [too-many-format-args]
> print("Today is {0}, so tomorrow will be {1}".format("Monday", "Tuesday", "Wednesday"))
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print("Today is {0}, so tomorrow will be {1}".format("Monday", "Tuesday"))
> ```

> [accordion] Too many positional arguments for %s call
>
> Flags a function call that has too many positional arguments provided, exceeding the function's defined parameters. This rule helps ensure function calls are made with the correct number and type of arguments.
>
> ```python Bad theme={"theme":"css-variables"}
> class Fruit:
> def __init__(self, color):
>     self.color = color
>
>
> apple = Fruit("red", "apple", [1, 2, 3])  # [too-many-function-args]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Fruit:
> def __init__(self, color, name):
>     self.color = color
>     self.name = name
>
>
> apple = Fruit("red", "apple")
> ```

> [accordion] More than one starred expression in assignment
>
> Warns when more than one starred expression is used in an assignment, which is not allowed. Starred expressions can unpack iterable values, but only one such unpacking is permitted per assignment to maintain clarity and prevent ambiguity.
>
> ```python Bad theme={"theme":"css-variables"}
> *stars, *constellations = ["Sirius", "Arcturus", "Vega"]  # [too-many-star-expressions]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> *sirius_and_arcturus, vega = ["Sirius", "Arcturus", "Vega"]
> ```

> [accordion] Format string ends in middle of conversion specifier
>
> Indicates that a format string ends unexpectedly in the middle of a conversion specifier, which can lead to incomplete or incorrect string formatting. Ensuring complete and correct format strings is essential for accurate data representation.
>
> ```python Bad theme={"theme":"css-variables"}
> PARG_2 = 1
>
> print("strange format %2" % PARG_2)  # [truncated-format-string]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> PARG_2 = 1
>
> print(f"strange format {PARG_2}")
> ```

> [accordion] Undefined variable name %r in **all**
>
> Flags a name referenced in the **all** variable that has not been defined, which can lead to an ImportError when attempting to import names from the module. This rule ensures that **all** accurately reflects the module's public API.
>
> ```python Bad theme={"theme":"css-variables"}
> __all__ = ["get_fruit_colour"]  # [undefined-all-variable]
>
>
> def get_fruit_color():
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> __all__ = ["get_fruit_color"]
>
>
> def get_fruit_color():
> pass
> ```

> [accordion] Undefined variable %r
>
> Indicates the use of a variable that has not been defined, leading to a NameError at runtime. This rule is crucial for identifying typos or logical errors in variable usage, ensuring that all variables are properly declared and assigned.
>
> ```python Bad theme={"theme":"css-variables"}
> print(number + 2)  # [undefined-variable]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> number = 3
> print(number + 2)
> ```

> [accordion] Unexpected keyword argument %r in %s call
>
> Warns when a function call includes a keyword argument that is not accepted by the function's signature. This rule helps ensure that function calls are compatible with function definitions, preventing TypeError due to unexpected arguments.
>
> ```python Bad theme={"theme":"css-variables"}
> def print_coordinates(x=0, y=0):
> print(f"{x=}, {y=}")
>
>
> print_coordinates(x=1, y=2, z=3)  # [unexpected-keyword-arg]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def print_coordinates(x=0, y=0):
> print(f"{x=}, {y=}")
>
>
> print_coordinates(x=1, y=2)
> ```

> [accordion] The special method %r expects %s param(s), %d %s given
>
> Indicates that a special method (like **len** or **getitem**) is defined with an unexpected number of parameters, which can lead to incorrect behavior or errors when the method is called by Python runtime. Ensuring special methods have the correct signature is vital for adhering to Python's data model and expected object behaviors.
>
> ```python Bad theme={"theme":"css-variables"}
> class ContextManager:
> def __enter__(self, context):  # [unexpected-special-method-signature]
>     pass
>
> def __exit__(self, type):  # [unexpected-special-method-signature]
>     pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class ContextManager:
> def __enter__(self):
>     pass
>
> def __exit__(self, type, value, traceback):
>     pass
> ```

> [accordion] '%s' is unhashable and can't be used as a %s in a %s
>
> Flags an attempt to use an unhashable object (like a list) as a member of a hash-based collection (like a set or dictionary key). This rule is important for ensuring data integrity in collections that rely on the hashability of their elements to function correctly.
>
> ```python Bad theme={"theme":"css-variables"}
> # Print the number of apples:
> print({"apple": 42}[["apple"]])  # [unhashable-member]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> # Print the number of apples:
> print({"apple": 42}["apple"])
> ```

> [accordion] Attempting to unpack a non-sequence%s
>
> Warns when there's an attempt to unpack a non-sequence type, which is not iterable. This rule prevents runtime errors by ensuring that only iterable objects are unpacked, adhering to Python's requirement for unpacking operations.
>
> ```python Bad theme={"theme":"css-variables"}
> a, b, c = 1  # [unpacking-non-sequence]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> a, b, c = 1, 2, 3
> ```

> [accordion] Unrecognized inline option
>
> Indicates the use of an inline option (typically in a comment) that pylint does not recognize. This helps maintain the clarity and effectiveness of inline directives, ensuring they are correctly interpreted by pylint.
>
> ```python Bad theme={"theme":"css-variables"}
> # +1: [unrecognized-inline-option]
> # pylint:applesoranges=1
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> # pylint: enable=too-many-public-methods
> ```

> [accordion] Unrecognized option in configuration file
>
> Flags an option in a pylint configuration file that is not recognized by pylint. This rule helps ensure that configuration files are correctly written and that all specified options are valid and effective.

> [accordion] Value '%s' is unsubscriptable
>
> Warns when an attempt is made to subscript (index or slice) an object that does not support subscripting. This rule is crucial for preventing TypeError by ensuring that subscript operations are only performed on objects that support them.
>
> ```python Bad theme={"theme":"css-variables"}
> class Fruit:
> pass
>
>
> Fruit()[1]  # [unsubscriptable-object]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Fruit:
> def __init__(self):
>     self.colors = ["red", "orange", "yellow"]
>
> def __getitem__(self, idx):
>     return self.colors[idx]
>
>
> Fruit()[1]
> ```

> [accordion] %r does not support item assignment
>
> Indicates that an object does not support item assignment, typically flagged when attempting to modify an immutable object. This rule helps prevent runtime errors by ensuring that objects being modified support item assignment.
>
> ```python Bad theme={"theme":"css-variables"}
> def pick_fruits(fruits):
> for fruit in fruits:
>     print(fruit)
>
>
> pick_fruits(["apple"])[0] = "orange"  # [unsupported-assignment-operation]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def pick_fruits(fruits):
> for fruit in fruits:
>     print(fruit)
>
> return []
>
>
> pick_fruits(["apple"])[0] = "orange"
> ```

> [accordion] Unsupported binary operation
>
> Flags a binary operation (like addition or multiplication) between types that do not support it. This rule ensures type compatibility in operations, preventing TypeError and maintaining logical correctness.
>
> ```python Bad theme={"theme":"css-variables"}
> drink = "water" | None  # [unsupported-binary-operation]
> result = [] | None  # [unsupported-binary-operation]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> masked = 0b111111 & 0b001100
> result = 0xAEFF | 0x0B99
> ```

> [accordion] %r does not support item deletion
>
> Warns when an attempt is made to delete an item from an object that does not support item deletion. This rule is important for ensuring that only mutable and properly equipped objects are targeted for item deletion.
>
> ```python Bad theme={"theme":"css-variables"}
> FRUITS = ("apple", "orange", "berry")
>
> del FRUITS[0]  # [unsupported-delete-operation]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> FRUITS = ["apple", "orange", "berry"]
>
> del FRUITS[0]
> ```

> [accordion] Value '%s' doesn't support membership test
>
> Indicates an attempt to perform a membership test (using in or not in) on an object that does not support it. This rule helps avoid TypeError and ensures that membership tests are only used with objects that implement the necessary protocols.
>
> ```python Bad theme={"theme":"css-variables"}
> class Fruit:
> pass
>
>
> apple = "apple" in Fruit()  # [unsupported-membership-test]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Fruit:
> FRUITS = ["apple", "orange"]
>
> def __contains__(self, name):
>     return name in self.FRUITS
>
>
> apple = "apple" in Fruit()
> ```

> [accordion] Using variable %r before assignment
>
> Flags a variable being used before it has been assigned a value, which can lead to UnboundLocalError. This rule is fundamental for variable usage correctness, ensuring variables are defined before use.
>
> ```python Bad theme={"theme":"css-variables"}
> print(hello)  # [used-before-assignment]
> hello = "Hello World !"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> hello = "Hello World !"
> print(hello)
> ```

> [accordion] Name %r is used prior to global declaration
>
> Warns when a name is used before it is declared as global within a function. This rule ensures that the global statement is used correctly, clarifying the scope and binding of variables used across different scopes.
>
> ```python Bad theme={"theme":"css-variables"}
> TOMATO = "black cherry"
>
>
> def update_tomato():
> print(TOMATO)  # [used-prior-global-declaration]
> global TOMATO
> TOMATO = "cherry tomato"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> TOMATO = "black cherry"
>
>
> def update_tomato():
> global TOMATO
> TOMATO = "moneymaker"
> ```

> [accordion] Yield inside async function
>
> Indicates the use of yield inside an asynchronous function, which is not allowed. Since Python 3.5, async functions should use await instead, and this rule helps ensure correct asynchronous function behavior.
>
> ```python Bad theme={"theme":"css-variables"}
> async def foo():
> yield from [1, 2, 3]  # [yield-inside-async-function]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> async def foo():
> def _inner_foo():
>     yield from [1, 2, 3]
>
>
> async def foo():
> yield 42
> ```

> [accordion] Yield outside function
>
> Flags a yield statement used outside of a function, which is a syntax error. Yield is only valid within generator functions, and this rule ensures the correct context for yielding values in a lazy evaluation pattern.
>
> ```python Bad theme={"theme":"css-variables"}
> for i in range(10):
> yield i  # [yield-outside-function]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def one_to_ten():
> for i in range(10):
>     yield i
> ```

> [accordion] Improper context manager
>
> Indicates improper implementation or use of a context manager, which may not correctly implement **enter** and **exit** methods. Proper context manager implementation is crucial for managing resources efficiently and safely.

> [accordion] Incorrect exception context
>
> Warns about incorrect use or handling of exception context, which may lead to loss of information or misleading error handling. This rule ensures that exceptions are managed correctly, preserving context where necessary.

> [accordion] Bad value in option
>
> Flags an invalid value provided for a pylint option, either in a configuration file or inline comment. This rule helps ensure that pylint options are configured with valid values, maintaining the tool's effectiveness and configuration integrity.

> [accordion] Possible missing member
>
> Indicates a potential issue where a member access may fail due to the member possibly not existing. This rule helps identify possible runtime errors early, especially in dynamic or complex codebases.

> [accordion] Non-iterator returned in old style
>
> Flags a situation where an object's iteration method does not return an iterator, in the context of older Python versions or compatibility layers. Ensuring that iterables return proper iterators is essential for compatibility and correct iteration behavior.

> [accordion] Unbalanced tuple unpacking
>
> Flags cases of unbalanced tuple unpacking, where the number of variables on the left side of the assignment does not match the number of values in the tuple. This rule ensures that tuple unpacking assignments are correctly balanced to prevent ValueError.

> [accordion] Unhashable key in dict
>
> Warns when an attempt is made to use an unhashable object (like a list) as a dictionary key. Dictionary keys must be immutable and hashable to ensure data integrity and support efficient lookup.

> [accordion] Method %r is abstract in class %r but is not overridden in child class %r
>
> Indicates that an abstract method defined in a parent class is not overridden in a subclass. This rule helps ensure that subclasses implement all abstract methods, adhering to the interface defined by their abstract base classes.

> [accordion] Anomalous backslash in string: '%s'. String constant might be missing an r prefix.
>
> Flags the presence of backslashes in a string that do not escape any characters, suggesting that the string might require an 'r' prefix to be interpreted as a raw string or corrected to escape characters properly.

> [accordion] Anomalous Unicode escape in byte string: '%s'. String constant might be missing an r or u prefix.
>
> Warns about unusual Unicode escape sequences in byte strings, suggesting that the string may need an 'r' prefix for a raw string or a 'u' prefix for a Unicode string to correctly interpret the escape sequences.
>
> ```python Bad theme={"theme":"css-variables"}
> print(b"\u%b" % b"0394")  # [anomalous-unicode-escape-in-string]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print(b"\u%b" % b"0394")
> ```

> [accordion] %s %s %r method
>
> Indicates that the arguments of a method override differ from those of the method in the superclass. This rule ensures consistency in method signatures across class hierarchies, preserving interface compatibility.

> [accordion] Positional arguments appear to be out of order
>
> Flags when positional arguments in a function or method call appear to be out of their expected order, which can lead to incorrect behavior or errors due to the incorrect assignment of values to parameters.
>
> ```python Bad theme={"theme":"css-variables"}
> def function_3_args(first_argument, second_argument, third_argument):
> """Three arguments function"""
> return first_argument, second_argument, third_argument
>
>
> def args_out_of_order():
> first_argument = 1
> second_argument = 2
> third_argument = 3
>
> function_3_args(  # [arguments-out-of-order]
>     first_argument, third_argument, second_argument
> )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def function_3_args(first_argument, second_argument, third_argument):
> """Three arguments function"""
> return first_argument, second_argument, third_argument
>
>
> def args_out_of_order():
> first_argument = 1
> second_argument = 2
> third_argument = 3
>
> function_3_args(first_argument, second_argument, third_argument)
> ```

> [accordion] %s %s %r method
>
> Warns when a method in a subclass renames arguments of a method from the superclass. While not inherently incorrect, this can lead to confusion and errors in code that expects the superclass's argument names.
>
> ```python Bad theme={"theme":"css-variables"}
> class Fruit:
> def brew(self, ingredient_name: str):
>     print(f"Brewing a {type(self)} with {ingredient_name}")
>
>
> class Apple(Fruit): ...
>
>
> class Orange(Fruit):
> def brew(self, flavor: str):  # [arguments-renamed]
>     print(f"Brewing an orange with {flavor}")
>
>
> for fruit, ingredient_name in [[Orange(), "thyme"], [Apple(), "cinnamon"]]:
> fruit.brew(ingredient_name=ingredient_name)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Fruit:
> def brew(self, ingredient_name: str):
>     print(f"Brewing a {type(self)} with {ingredient_name}")
>
>
> class Apple(Fruit): ...
>
>
> class Orange(Fruit):
> def brew(self, ingredient_name: str):
>     print(f"Brewing an orange with {ingredient_name}")
>
>
> for fruit, ingredient_name in [[Orange(), "thyme"], [Apple(), "cinnamon"]]:
> fruit.brew(ingredient_name=ingredient_name)
> ```

> [accordion] Assert statement has a string literal as its first argument. The assert will %s fail.
>
> Indicates an assert statement where the condition is a string literal, which is always true, suggesting the assert may not function as intended and might be missing actual conditions to test.
>
> ```python Bad theme={"theme":"css-variables"}
> def test_division():
> a = 9 / 3
> assert "No ZeroDivisionError were raised"  # [assert-on-string-literal]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def test_division():
> a = 9 / 3
> assert a == 3
> ```

> [accordion] Assert called on a populated tuple. Did you mean 'assert x,y'?
>
> Flags an assert statement applied to a tuple, which is always true if the tuple is not empty. This might indicate a misunderstanding of how assert works or a typo, such as missing a comma between conditions.
>
> ```python Bad theme={"theme":"css-variables"}
> assert (1, None)  # [assert-on-tuple]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x, y = (1, None)
> assert x
> assert y
> ```

> [accordion] Attribute %r defined outside **init**
>
> Warns when an instance attribute is defined outside of the **init** method, which can lead to attributes being undefined in some instances or contribute to a less cohesive class design.
>
> ```python Bad theme={"theme":"css-variables"}
> class Student:
> def register(self):
>     self.is_registered = True  # [attribute-defined-outside-init]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Student:
> def __init__(self):
>     self.is_registered = False
>
> def register(self):
>     self.is_registered = True
> ```

> [accordion] Bad usage of builtin function
>
> Indicates improper use of a Python builtin function, either due to misunderstanding its purpose or using it in a context where a more appropriate alternative exists, leading to potential inefficiencies or errors.
>
> ```python Bad theme={"theme":"css-variables"}
> numbers = list(map(lambda x: 2 * x, [1, 2, 3]))  # [bad-builtin]
> print(numbers)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> numbers = [2 * x for x in [1, 2, 3]]
> print(numbers)
> ```

> [accordion] Suspicious %s-part chained comparison using semantically incompatible operators (%s)
>
> Flags suspicious chained comparisons that use semantically incompatible operators, which might indicate a logic error or misunderstanding of comparison chaining in Python.

> [accordion] Bad magic method name
>
> Indicates the use of an incorrectly named magic (dunder) method, which may not be recognized by Python's data model. Correctly naming magic methods is crucial for them to be called automatically by Python's runtime environment.
>
> ```python Bad theme={"theme":"css-variables"}
> class Apples:
> def _init_(self):  # [bad-dunder-name]
>     pass
>
> def __hello__(self):  # [bad-dunder-name]
>     print("hello")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Apples:
> def __init__(self):
>     pass
>
> def hello(self):
>     print("hello")
> ```

> [accordion] Invalid format string
>
> Indicates an invalid format string is used in a formatting operation. This rule helps identify syntax errors or typos in format strings, ensuring that string formatting operations are correctly specified and can execute without errors.
>
> ```python Bad theme={"theme":"css-variables"}
> print("{a[0] + a[1]}".format(a=[0, 1]))  # [bad-format-string]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print("{a[0]} + {a[1]}".format(a=[0, 1]))
> ```

> [accordion] Format string dictionary key should be a string, not %s
>
> Warns when a format string dictionary uses a non-string key. Format strings that are populated from dictionaries should use strings as keys to match placeholders in the format string, ensuring correct substitution and preventing KeyError.
>
> ```python Bad theme={"theme":"css-variables"}
> print("%(one)d" % {"one": 1, 2: 2})  # [bad-format-string-key]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print("%(one)d, %(two)d" % {"one": 1, "two": 2})
> ```

> [accordion] Bad indentation. Found %s %s, expected %s
>
> Flags incorrect indentation levels in the code, highlighting deviations from the expected indentation. Proper indentation is crucial in Python for defining code blocks and maintaining readability and consistency in code structure.
>
> ```python Bad theme={"theme":"css-variables"}
> if input():
> print('yes')  # [bad-indentation]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> if input():
> print("yes")
> ```

> [accordion] \\'%s\\' is not a valid mode for open.
>
> Indicates that an invalid mode argument was passed to the open function. Validating open modes ensures that files are opened in an appropriate manner for the intended operation, preventing runtime errors.
>
> ```python Bad theme={"theme":"css-variables"}
> def open_and_get_content(file_path):
> with open(file_path, "rwx") as file:  # [bad-open-mode]
>     return file.read()
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def open_and_get_content(file_path):
> with open(file_path, "r") as file:
>     return file.read()
> ```

> [accordion] Static method with %r as first argument
>
> Flags a static method defined with an inappropriate first argument (e.g., self or cls). Static methods should not take a class or instance reference as their first argument, distinguishing them from class and instance methods.
>
> ```python Bad theme={"theme":"css-variables"}
> class Wolf:
> @staticmethod
> def eat(self):  # [bad-staticmethod-argument]
>     pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Wolf:
> @staticmethod
> def eat(sheep):
>     pass
> ```

> [accordion] threading.Thread needs the target function
>
> Warns when a threading.Thread object is instantiated without specifying the target function. Specifying the target is crucial for the Thread to know which function to execute in the new thread.
>
> ```python Bad theme={"theme":"css-variables"}
> import threading
>
>
> def thread_target(n):
> print(n**2)
>
>
> thread = threading.Thread(lambda: None)  # [bad-thread-instantiation]
> thread.start()
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import threading
>
>
> def thread_target(n):
> print(n**2)
>
>
> thread = threading.Thread(target=thread_target, args=(10,))
> thread.start()
> ```

> [accordion] No exception type(s) specified
>
> Flags the use of an except clause without specifying any exception types. This can catch unexpected exceptions including system interrupts, making debugging harder. It's recommended to catch specific exceptions to handle known error conditions.
>
> ```python Bad theme={"theme":"css-variables"}
> try:
> import platform_specific_module
> except:  # [bare-except]
> platform_specific_module = None
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> try:
> import platform_specific_module
> except ImportError:
> platform_specific_module = None
> ```

> [accordion] Exception to catch is the result of a binary \\'%s\\' operation
>
> Indicates an attempt to catch an exception using the result of a binary operation, which is likely a mistake. This rule helps ensure that exception handling is specified correctly, catching actual exception classes or instances.
>
> ```python Bad theme={"theme":"css-variables"}
> try:
> 1 / 0
> except ZeroDivisionError or ValueError:  # [binary-op-exception]
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> try:
> 1 / 0
> except (ZeroDivisionError, ValueError):
> pass
> ```

> [accordion] Using datetime.time in a boolean context.
>
> Warns when a datetime.time object is used in a boolean context, which can be misleading since datetime.time objects are always truthy. This rule encourages explicit checks against datetime properties for clarity.
>
> ```python Bad theme={"theme":"css-variables"}
> import datetime
>
> if datetime.time():  # [boolean-datetime]
> print("It is time.")
>
>
> if datetime.datetime.now().time():  # [boolean-datetime]
> print("Now or never.")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import datetime
>
> time_now_utc = datetime.datetime.now(tz=datetime.UTC).time()
>
> if time_now_utc > datetime.time(6, 0):
> print("Daytime!")
>
> if time_now_utc < datetime.time(6, 0):
> print("Nighttime!")
> ```

> [accordion] Catching too general exception %s
>
> Flags the catching of a general exception class, which can obscure the cause of an error. Narrowing down the caught exceptions to more specific types can aid in error diagnosis and handling.
>
> ```python Bad theme={"theme":"css-variables"}
> try:
> import platform_specific_module
> except Exception:  # [broad-exception-caught]
> platform_specific_module = None
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> try:
> import platform_specific_module
> except ImportError:
> platform_specific_module = None
> ```

> [accordion] Raising too general exception: %s
>
> Indicates raising a very general exception type, which can make error handling and debugging more difficult. Using more specific exceptions helps convey more information about the error condition.
>
> ```python Bad theme={"theme":"css-variables"}
> def small_apple(apple, length):
> if len(apple) < length:
>     raise Exception("Apple is too small!")  # [broad-exception-raised]
> print(f"{apple} is proper size.")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def small_apple(apple, length):
> if len(apple) < length:
>     raise ValueError("Apple is too small!")
> print(f"{apple} is proper size.")
> ```

> [accordion] Cell variable %s defined in loop
>
> Warns about a loop variable being used in a closure, leading to late binding and possibly unexpected behavior. This rule suggests using default arguments or other strategies to ensure the correct value is captured.

> [accordion] Comparing against a callable, did you omit the parenthesis?
>
> Flags a comparison operation where one operand is a callable function or method without being called (missing parentheses). This typically indicates a logic error where the function's return value was intended for comparison.
>
> ```python Bad theme={"theme":"css-variables"}
> def function_returning_a_fruit()  str:
> return "orange"
>
>
> def is_an_orange(fruit: str = "apple"):
> # apple == <function function_returning_a_fruit at 0x7f343ff0a1f0>
> return fruit == function_returning_a_fruit  # [comparison-with-callable]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def function_returning_a_fruit()  str:
> return "orange"
>
>
> def is_an_orange(fruit: str = "apple"):
> # apple == orange
> return fruit == function_returning_a_fruit()
> ```

> [accordion] Following \\'as\\' with another context manager looks like a tuple.
>
> Indicates a with statement that might be confusing due to following an "as" with another context manager without using parentheses, which can appear as if a tuple is being created.
>
> ```python Bad theme={"theme":"css-variables"}
> with open("file.txt", "w") as fh1, fh2:  # [confusing-with-statement]
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> with open("file.txt", "w", encoding="utf8") as fh1:
> with open("file.txt", "w", encoding="utf8") as fh2:
>     pass
> ```

> [accordion] Consider using ternary expression
>
> Suggests using a ternary conditional expression for simpler conditional assignments or return statements, enhancing readability and conciseness of the code.
>
> ```python Bad theme={"theme":"css-variables"}
> x, y = input(), input()
> if x >= y:  # [consider-ternary-expression]
> maximum = x
> else:
> maximum = y
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x, y = input(), input()
> maximum = x if x >= y else y
> ```

> [accordion] Dangerous default value %s as argument
>
> Warns when mutable objects are used as default values in function or method definitions. Since default argument values are evaluated only once at function definition time, using mutable defaults can lead to unexpected behavior across multiple calls.
>
> ```python Bad theme={"theme":"css-variables"}
> def whats_on_the_telly(penguin=[]):  # [dangerous-default-value]
> penguin.append("property of the zoo")
> return penguin
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def whats_on_the_telly(penguin=None):
> if penguin is None:
>     penguin = []
> penguin.append("property of the zoo")
> return penguin
> ```

> [accordion] Using deprecated argument %s of method %s()
>
> Flags the use of a deprecated argument in a method call. Using deprecated features can lead to compatibility issues as they may be removed in future versions, impacting the maintainability and future-proofing of the code.
>
> ```python Bad theme={"theme":"css-variables"}
> int(x=1)  # [deprecated-argument]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> int(1)
> ```

> [accordion] Using deprecated class %s of module %s
>
> Indicates the use of a class that has been marked as deprecated. Relying on deprecated classes reduces the code's longevity and may necessitate future refactoring, affecting maintainability.
>
> ```python Bad theme={"theme":"css-variables"}
> from collections import Iterable  # [deprecated-class]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from collections.abc import Iterable
> ```

> [accordion] Using deprecated decorator %s()
>
> Warns about the use of a decorator that is deprecated. Decorators affect the execution of the functions they decorate, and using deprecated ones can lead to deprecated behavior patterns and hinder performance optimizations.
>
> ```python Bad theme={"theme":"css-variables"}
> import abc
>
>
> class Animal:
> @abc.abstractclassmethod  # [deprecated-decorator]
> def breath(cls):
>     pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import abc
>
>
> class Animal:
> @abc.classmethod
> @abc.abstractmethod
> def breath(cls):
>     pass
> ```

> [accordion] Using deprecated method %s()
>
> Highlights the invocation of a method that has been deprecated. Deprecated methods are candidates for removal in future releases, which can negatively impact the code's reliability and necessitate revisions for compatibility.
>
> ```python Bad theme={"theme":"css-variables"}
> import logging
>
> logging.warn("I'm coming, world !")  # [deprecated-method]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import logging
>
> logging.warning("I'm coming, world !")
> ```

> [accordion] Deprecated module %r
>
> Flags the import or use of a deprecated module. Depending on deprecated modules can lead to future compatibility issues, potentially increasing the effort required for updates and maintenance.
>
> ```python Bad theme={"theme":"css-variables"}
> import distutils  # [deprecated-module]
>
> import whatever_you_want  # [deprecated-module]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import setuptools
> import whatever_replacement_you_want
> ```

> [accordion] Deprecated typing alias used
>
> Indicates the use of a typing alias that has been deprecated. Keeping up with current typing practices is important for readability and leveraging the full capabilities of Python's type hinting.
>
> ```python Bad theme={"theme":"css-variables"}
> import typing
>
> item_to_number_of_item: typing.Dict[str, int]  # [deprecated-typing-alias]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> item_to_number_of_item: dict[str, int]
> ```

> [accordion] Parameter documentation differs
>
> Warns when the actual parameters of a function differ from those documented in its docstring. Accurate documentation is key for readability and maintainability, helping developers understand function usage and expectations.
>
> ```python Bad theme={"theme":"css-variables"}
> def add(x, y):  # [differing-param-doc]
> """Add two numbers.
>
> :param int x: x value.
> :param int z: z value.
> """
>
> return x + y
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def add(x, y):
> """Add two numbers.
>
> :param int x: x value.
> :param int y: y value.
> """
>
> return x + y
> ```

> [accordion] Type documentation differs
>
> Indicates a discrepancy between documented types and actual types in function parameters or return values. Consistent and accurate type documentation enhances readability and supports type-checking tools.
>
> ```python Bad theme={"theme":"css-variables"}
> def add(x: int, y: int):  # [differing-type-doc]
> """Add two numbers.
>
> :param int xy: x value.
> :param str y: y value.
> """
>
> return x + y
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def add(x, y):
> """Add two numbers.
>
> :param int x: x value.
> :param int y: y value.
> """
>
> return x + y
> ```

> [accordion] Catching previously caught exception type %s
>
> Flags duplicate exception types in consecutive except blocks. Consolidating exception handling for the same exception type can improve readability and maintainability by centralizing response logic.
>
> ```python Bad theme={"theme":"css-variables"}
> try:
> 1 / 0
> except ZeroDivisionError:
> pass
> except ZeroDivisionError:  # [duplicate-except]
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> try:
> 1 / 0
> except ZeroDivisionError:
> pass
> ```

> [accordion] Duplicate key %r in dictionary
>
> Warns about duplicate keys in a dictionary literal, which can lead to overlooked bugs as the latter value silently overrides the former, impacting data integrity and readability.
>
> ```python Bad theme={"theme":"css-variables"}
> test_score = {"Mathematics": 85, "Biology": 90, "Mathematics": 75}  # [duplicate-key]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> test_score = {"Mathematics": 85, "Biology": 90, "History": 75}
> ```

> [accordion] Duplicate string formatting argument %r, consider passing as named argument
>
> Highlights the use of duplicate arguments in string formatting, suggesting the use of named arguments for clarity and to prevent errors in formatting expressions.
>
> ```python Bad theme={"theme":"css-variables"}
> # pylint: disable=missing-docstring, consider-using-f-string
>
> SEE = "see 👀"
> SEA = "sea 🌊"
>
> # +1: [duplicate-string-formatting-argument,duplicate-string-formatting-argument]
> CONST = """
> A sailor went to {}, {}, {}
> To {} what he could {}, {}, {}
> But all that he could {}, {}, {}
> Was the bottom of the deep blue {}, {}, {}!
> """.format(
> SEA,
> SEA,
> SEA,
> SEE,
> SEE,
> SEE,
> SEE,
> SEE,
> SEE,
> SEE,
> SEA,
> SEA,
> SEA,
> )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> # pylint: disable=missing-docstring, consider-using-f-string
>
> SEE = "see 👀"
> SEA = "sea 🌊"
>
> CONST = """
> A sailor went to {sea}, {sea}, {sea}
> To {see} what he could {see}, {see}, {see}
> But all that he could {see}, {see}, {see}
> Was the bottom of the deep blue {sea}, {sea}, {sea}!
> """.format(
> sea=SEA, see=SEE
> )
> ```

> [accordion] Duplicate value %r in set
>
> Indicates duplicate values in a set literal, which is unnecessary as sets automatically enforce uniqueness. Removing duplicates can improve the clarity of the intended elements in the set.
>
> ```python Bad theme={"theme":"css-variables"}
> incorrect_set = {"value1", 23, 5, "value1"}  # [duplicate-value]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> correct_set = {"value1", 23, 5}
> ```

> [accordion] **eq** implemented without **hash**
>
> Flags an **eq** method implemented without a corresponding **hash** method, which can lead to incorrect behavior when objects are used in hash-based collections, impacting correctness and performance.
>
> ```python Bad theme={"theme":"css-variables"}
> class Fruit:  # [eq-without-hash]
> def __init__(self)  None:
>     self.name = "apple"
>
> def __eq__(self, other: object)  bool:
>     return isinstance(other, Fruit) and other.name == self.name
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Fruit:
> def __init__(self)  None:
>     self.name = "apple"
>
> def __eq__(self, other: object)  bool:
>     return isinstance(other, Fruit) and other.name == self.name
>
> def __hash__(self)  int:
>     return hash(self.name)
> ```

> [accordion] Use of eval
>
> Warns against the use of eval, which can execute arbitrary code and introduce security vulnerabilities. Avoiding eval can greatly enhance the security and performance of the application.
>
> ```python Bad theme={"theme":"css-variables"}
> eval("[1, 2, 3]")  # [eval-used]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from ast import literal_eval
>
> literal_eval("[1, 2, 3]")
> ```

> [accordion] Use of exec
>
> Similar to eval, flags the use of exec for executing Python code dynamically, which poses security risks and can make the code harder to read, debug, and maintain.
>
> ```python Bad theme={"theme":"css-variables"}
> username = "Ada"
> code_to_execute = f"""input('Enter code to be executed please, {username}: ')"""
> program = exec(code_to_execute)  # [exec-used]
> exec(program)  # [exec-used]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def get_user_code(name):
> return input(f"Enter code to be executed please, {name}: ")
>
>
> username = "Ada"
> allowed_globals = {"__builtins__": None}
> allowed_locals = {"print": print}
> # pylint: disable-next=exec-used
> exec(get_user_code(username), allowed_globals, allowed_locals)
> ```

> [accordion] Expression \\'%s\\' is assigned to nothing
>
> Indicates an expression that has no effect because its result is not assigned or used, potentially indicating a mistake or unnecessary code that can hinder readability.
>
> ```python Bad theme={"theme":"css-variables"}
> str(42) == "42"  # [expression-not-assigned]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> are_equal: bool = str(42) == "42"
> ```

> [accordion] Using an f-string that does not have any interpolated variables
>
> Flags an f-string that does not perform any interpolation, suggesting that a simpler string literal could be used instead, improving clarity and performance by avoiding unnecessary parsing.
>
> ```python Bad theme={"theme":"css-variables"}
> x = 1
> y = 2
> print(f"x + y = x + y")  # [f-string-without-interpolation]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = 1
> y = 2
> print(f"{x} + {y} = {x + y}")
> ```

> [accordion] FIXME comment detected
>
> Highlights FIXME comments, which indicate areas of the code that are acknowledged by the developer as needing improvement or correction.

> [accordion] Leaving functions creating breakpoints in production code is not recommended
>
> Warns about the presence of debugging statements, like breakpoints, left in the code. These statements can interrupt the flow or expose sensitive information in production environments, highlighting the need for clean, debug-statement-free code for performance and security.
>
> ```python Bad theme={"theme":"css-variables"}
> import pdb
>
>
> def find_the_treasure(clues):
> for clue in clues:
>     pdb.set_trace()  # [forgotten-debug-statement]
>     if "treasure" in clue:
>         return True
> return False
>
>
> treasure_hunt = [
> "Dead Man's Chest",
> "X marks the spot",
> "The treasure is buried near the palm tree",
> ]
> find_the_treasure(treasure_hunt)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def find_the_treasure(clues):
> for clue in clues:
>     if "treasure" in clue:
>         return True
> return False
>
>
> treasure_hunt = [
> "Dead Man's Chest",
> "X marks the spot",
> "The treasure is buried near the palm tree",
> ]
> find_the_treasure(treasure_hunt)
> ```

# Step 3

> [accordion] Format string contains both automatic field numbering and manual field specification
>
> Indicates a format string that inconsistently mixes automatic field numbering and manual field specification. Consistency in format string specifications enhances readability and maintainability by avoiding confusion about argument binding.

> [accordion] Using formatting for a string that does not have any interpolated variables
>
> Flags the use of a format operation on a string that does not include any variables for interpolation. Simplifying to a regular string can improve performance by avoiding unnecessary formatting operations.
>
> ```python Bad theme={"theme":"css-variables"}
> print("number".format(1))  # [format-string-without-interpolation]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print("number: {}".format(1))
> ```

> [accordion] Using the global statement at the module level
>
> Highlights the unnecessary use of the global statement at the module level, where variables are already global. This rule promotes cleaner code by avoiding redundant or confusing global declarations.
>
> ```python Bad theme={"theme":"css-variables"}
> price = 25
> global price  # [global-at-module-level]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> price = 25
> ```

> [accordion] Using the global statement
>
> Warns against the use of the global statement, which can lead to code that is harder to understand and maintain by making the local-global variable distinction less clear, affecting readability and maintainability.
>
> ```python Bad theme={"theme":"css-variables"}
> var = 1
>
>
> def foo():
> global var  # [global-statement]
> var = 10
> print(var)
>
>
> foo()
> print(var)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> var = 1
>
>
> def foo():
> print(var)
> return 10
>
>
> var = foo()
> print(var)
> ```

> [accordion] Using global for %r but no assignment is done
>
> Indicates the use of a global statement for a variable without assigning it a value, which can lead to confusion about the variable's intent and scope, impacting the clarity and correctness of the code.
>
> ```python Bad theme={"theme":"css-variables"}
> TOMATO = "black cherry"
>
>
> def update_tomato():
> global TOMATO  # [global-variable-not-assigned]
> print(TOMATO)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> TOMATO = "black cherry"
>
>
> def update_tomato():
> global TOMATO
> TOMATO = "moneymaker"
> ```

> [accordion] Global variable %r undefined at the module level
>
> Flags the reference to a global variable that is not defined at the module level, potentially leading to NameError at runtime and highlighting issues with variable scope and definition.
>
> ```python Bad theme={"theme":"css-variables"}
> def update_tomato():
> global TOMATO  # [global-variable-undefined]
> TOMATO = "moneymaker"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> TOMATO = "black cherry"
>
>
> def update_tomato():
> global TOMATO
> TOMATO = "moneymaker"
> ```

> [accordion] Flag member %(overlap)s shares bit positions with %(sources)s
>
> Indicates that a flag in an enumeration shares bit positions with another, which can lead to ambiguous or unexpected behavior when checking flags, emphasizing the importance of clear, non-overlapping flag definitions for maintainability.
>
> ```python Bad theme={"theme":"css-variables"}
> from enum import IntFlag
>
>
> class FilePermissions(IntFlag):
> READ = 1
> WRITE = 2
> EXECUTE = 3  # [implicit-flag-alias]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from enum import IntFlag
>
>
> class FilePermissions(IntFlag):
> READ = 1
> WRITE = 2
> EXECUTE = 4
> ```

> [accordion] Implicit string concatenation found in %s
>
> Warns about strings that are implicitly concatenated in code, which can make the strings harder to read and maintain. Explicit concatenation (using +) or formatting is recommended for clarity.

> [accordion] Module import itself
>
> Flags a module that imports itself, which is generally unnecessary and can lead to confusion or cyclic dependencies, detracting from code clarity and structure.

> [accordion] Quote delimiter %s is inconsistent with the rest of the file
>
> Indicates inconsistency in the use of quote delimiters within a file, suggesting sticking to a single style for string literals to enhance readability and maintain a consistent code style.
>
> ```python Bad theme={"theme":"css-variables"}
> import datetime
>
> print('Current year: ', datetime.date.today().strftime("%Y")) # [inconsistent-quotes]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import datetime
>
> print("Current year: ", datetime.date.today().strftime("%Y"))
> ```

> [accordion] %s default type is %s. Expected str or None.
>
> Warns when an environment variable default value is not a string or None, emphasizing the need for environment variables to be parsed or used in a type-safe manner, enhancing code robustness.
>
> ```python Bad theme={"theme":"css-variables"}
> import os
>
> env = os.getenv("SECRET_KEY", 1)  # [invalid-envvar-default]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import os
>
> env = os.getenv("SECRET_KEY", "1")
> ```

> [accordion] Using invalid lookup key %r in format specifier %r
>
> Flags the use of an invalid key in a format string specifier, which can lead to KeyError or ValueError during string formatting, underscoring the importance of accurate and valid format specifiers for data representation.
>
> ```python Bad theme={"theme":"css-variables"}
> not_enough_fruits = ["apple"]
> print('The second fruit is a {fruits[1]}'.format(fruits=not_enough_fruits))  # [invalid-format-index]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> enough_fruits = ["apple", "banana"]
> print("The second fruit is a {fruits[1]}".format(fruits=enough_fruits))
> ```

> [accordion] Method %r was expected to be %r, found it instead as %r
>
> Indicates a method override that does not match the expected signature of the method it overrides. Ensuring method signatures match across class hierarchies is crucial for maintaining consistent interfaces and behaviors, enhancing both readability and maintainability.
>
> ```python Bad theme={"theme":"css-variables"}
> class Fruit:
> async def bore(self, insect):
>     insect.eat(self)
>
>
> class Apple(Fruit):
> def bore(self, insect):  # [invalid-overridden-method]
>     insect.eat(self)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Fruit:
> async def bore(self, insect):
>     insect.eat(self)
>
>
> class Apple(Fruit):
> async def bore(self, insect):
>     insect.eat(self)
> ```

> [accordion] Second argument of isinstance is not a type
>
> Flags the use of isinstance where the second argument is not a valid type or a tuple of valid types. Correct use of isinstance is important for dynamic type checks to be reliable and not cause runtime errors.
>
> ```python Bad theme={"theme":"css-variables"}
> isinstance("apples and oranges", hex)  # [isinstance-second-argument-not-valid-type]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> isinstance("apples and oranges", str)
> ```

> [accordion] Keyword argument before variable positional arguments list in the definition of %s function
>
> Warns when a keyword argument is defined before a variable positional argument (\*args) in a function definition. This affects the readability and usability of the function, as positional arguments should logically precede keyword arguments.
>
> ```python Bad theme={"theme":"css-variables"}
> def func(x=None, *args):  # [keyword-arg-before-vararg]
> return [x, *args]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def func(*args, x=None):
> return [*args, x]
> ```

> [accordion] %r will be included in %r since a positional-only parameter with this name already exists
>
> Indicates a keyword argument in a function definition that matches the name of a preceding positional-only parameter, which can lead to confusion and errors in argument passing, undermining the clarity of the function's interface.
>
> ```python Bad theme={"theme":"css-variables"}
> def print_name(name="Sarah", /, **kwds):
> print(name)
>
>
> print_name(name="Jacob")  # [kwarg-superseded-by-positional-arg]
> # Will print "Sarah"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def print_name(name="Sarah", /, **kwds):
> print(name)
>
>
> print_name("Jacob")
> # Will print "Jacob"
> ```

> [accordion] Use %s formatting in logging functions
>
> Recommends using % formatting or {} formatting (with format method) in logging functions rather than string interpolation or f-strings, to defer the formatting overhead until it's determined that the log message will actually be emitted.
>
> ```python Bad theme={"theme":"css-variables"}
> import logging
> import sys
>
> # +1: [logging-format-interpolation]
> logging.error("Python version: {}".format(sys.version))
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import logging
> import sys
>
> logging.error("Python version: %s", sys.version)
> ```

> [accordion] Use %s formatting in logging functions
>
> Similar to the above, warns against the use of f-strings in logging functions, advocating for % or {} formatting for performance reasons and to ensure log messages are only formatted if they will be logged.
>
> ```python Bad theme={"theme":"css-variables"}
> import logging
> import sys
>
> logging.error(f"Python version: {sys.version}")  # [logging-fstring-interpolation]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import logging
> import sys
>
> logging.error("Python version: %s", sys.version)
> ```

> [accordion] Use %s formatting in logging functions
>
> Flags logging calls that do not use lazy % formatting, which can lead to unnecessary computation and memory usage even when the log level means the message will not be logged, affecting performance.
>
> ```python Bad theme={"theme":"css-variables"}
> import logging
>
> try:
> function()
> except Exception as e:
> logging.error("Error occurred: %s" % e)  # [logging-not-lazy]
> raise
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import logging
>
> try:
> function()
> except Exception as e:
> logging.error("Error occurred: %s", e)
> raise
> ```

> [accordion] %s statement in finally block may swallow exception
>
> Warns that an exception may be swallowed if a break, return, or continue statement is used in a finally block, potentially obscuring errors and complicating debugging and error handling.
>
> ```python Bad theme={"theme":"css-variables"}
> class FasterThanTheSpeedOfLightError(ZeroDivisionError):
> def __init__(self):
>     super().__init__("You can't go faster than the speed of light !")
>
>
> def calculate_speed(distance: float, time: float)  float:
> try:
>     return distance / time
> except ZeroDivisionError as e:
>     raise FasterThanTheSpeedOfLightError() from e
> finally:
>     return 299792458  # [lost-exception]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class FasterThanTheSpeedOfLightError(ZeroDivisionError):
> def __init__(self):
>     super().__init__("You can't go faster than the speed of light !")
>
>
> def calculate_speed(distance: float, time: float)  float:
> try:
>     return distance / time
> except ZeroDivisionError as e:
>     raise FasterThanTheSpeedOfLightError() from e
> ```

> [accordion] 'lru\_cache(maxsize=None)' or 'cache' will keep all method args alive indefinitely, including 'self'
>
> Highlights the use of lru\_cache with maxsize=None or the use of cache, which can lead to keeping arguments and self references alive indefinitely, potentially causing memory bloat and affecting application performance.
>
> ```python Bad theme={"theme":"css-variables"}
> import functools
>
>
> class Fibonnaci:
> def __init__(self):
>     self.result = []
>
> @functools.lru_cache(maxsize=None)  # [method-cache-max-size-none]
> def fibonacci(self, n):
>     if n in {0, 1}:
>         self.result.append(n)
>     self.result.append(self.fibonacci(n - 1) + self.fibonacci(n - 2))
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import functools
>
>
> @functools.cache
> def cached_fibonacci(n):
> if n in {0, 1}:
>     return n
> return cached_fibonacci(n - 1) + cached_fibonacci(n - 2)
>
>
> class Fibonnaci:
> def __init__(self):
>     self.result = []
>
> def fibonacci(self, n):
>     self.result.append(cached_fibonacci(n))
> ```

> [accordion] **future** import is not the first non docstring statement
>
> Indicates that a **future** import does not appear at the top of the file, immediately after any docstrings. **future** imports must be placed correctly to affect the syntax of the Python file as expected.
>
> ```python Bad theme={"theme":"css-variables"}
> import sys
>
> from __future__ import print_function  # [misplaced-future]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from __future__ import print_function
>
> import sys
> ```

> [accordion] Missing documentation for some parameters
>
> Flags the absence of documentation for one or more parameters in a function or method, which can hinder readability and maintainability by leaving users and maintainers without clear guidance on function usage.
>
> ```python Bad theme={"theme":"css-variables"}
> def puppies(head, tail):  # [missing-any-param-doc]
> """Print puppy's details."""
> print(head, tail)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def puppies(head: str, tail: str):
> """Print puppy's details.
>
> :param head: description of the head of the dog
> :param tail: description of the tail of the dog
> """
> print(head, tail)
> ```

> [accordion] Missing keyword argument %r for format string
>
> Warns when a keyword argument expected by a format string is missing, which can lead to a KeyError during string formatting. Ensuring all format string arguments are provided enhances the robustness and reliability of string operations.
>
> ```python Bad theme={"theme":"css-variables"}
> print("My name is {first} {last}".format(first="John"))  # [missing-format-argument-key]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print("My name is {first} {last}".format(first="John", last="Wick"))
> ```

> [accordion] Missing format attribute %r in format specifier %r
>
> Indicates that a format string refers to an attribute that does not exist in the given format specifier, which can lead to AttributeError at runtime. Ensuring all format attributes are correct enhances code reliability and readability.
>
> ```python Bad theme={"theme":"css-variables"}
> print("{0.real}".format("1"))  # [missing-format-attribute]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print("{0.real}".format(1))
> ```

> [accordion] Missing parameter documentation
>
> Flags the absence of documentation for one or more parameters in a function or method's docstring. Comprehensive parameter documentation is crucial for readability and maintainability, providing clear usage instructions to users and maintainers.
>
> ```python Bad theme={"theme":"css-variables"}
> def integer_sum(a: int, b):  # [missing-param-doc]
> """Returns sum of two integers
> :param a: first integer
> """
> return a + b
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def integer_sum(a: int, b: int):
> """Returns sum of two integers
> :param a: first integer
> :param b: second integer
> """
> return a + b
> ```

> [accordion] Using a conditional statement with potentially wrong function or method call due to missing parentheses
>
> Warns about the potential misuse of a function or method call within a conditional statement due to missing parentheses, which may result in the function call not being executed as intended. Adding parentheses can clarify the intention and ensure correct execution.
>
> ```python Bad theme={"theme":"css-variables"}
> import random
>
>
> def is_it_a_good_day():
> return random.choice([True, False])
>
>
> if is_it_a_good_day:  # [missing-parentheses-for-call-in-test]
> print("Today is a good day!")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import random
>
>
> def is_it_a_good_day():
> return random.choice([True, False])
>
>
> if is_it_a_good_day():
> print("Today is a good day!")
> ```

> [accordion] Missing documentation about raises
>
> Indicates missing documentation for exceptions that a function or method may raise. Documenting potential exceptions helps users handle errors appropriately, improving code robustness and maintainability.
>
> ```python Bad theme={"theme":"css-variables"}
> def integer_sum(a: int, b: int):  # [missing-raises-doc]
> """Returns sum of two integers
> :param a: first integer
> :param b: second integer
> """
> if not (isinstance(a, int) and isinstance(b, int)):
>     raise ValueError("Function supports only integer parameters.")
> return a + b
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def integer_sum(a: int, b: int):
> """Returns sum of two integers
> :param a: first integer
> :param b: second integer
> :raises ValueError: One of the parameters is not an integer.
> """
> if not (isinstance(a, int) and isinstance(b, int)):
>     raise ValueError("Function supports only integer parameters.")
> return a + b
> ```

> [accordion] Missing return documentation
>
> Flags missing documentation for the return value of a function or method. Return value documentation is important for understanding the purpose and usage of a function, enhancing code readability.
>
> ```python Bad theme={"theme":"css-variables"}
> def integer_sum(a: int, b: int):  # [missing-return-doc]
> """Returns sum of two integers
> :param a: first integer
> :param b: second integer
> """
> return a + b
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def integer_sum(a: int, b: int)  int:
> """Returns sum of two integers
> :param a: first integer
> :param b: second integer
> :return: sum of parameters a and b
> """
> return a + b
> ```

> [accordion] Missing return type documentation
>
> Highlights the absence of documentation for the return type of a function or method. Specifying return types helps with type checking and clarifies the function's contract, improving code readability and safety.
>
> ```python Bad theme={"theme":"css-variables"}
> def integer_sum(a: int, b: int):  # [missing-return-type-doc]
> """Returns sum of two integers
> :param a: first integer
> :param b: second integer
> :return: sum of parameters a and b
> """
> return a + b
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def integer_sum(a: int, b: int)  int:
> """Returns sum of two integers
> :param a: first integer
> :param b: second integer
> :return: sum of parameters a and b
> """
> return a + b
> ```

> [accordion] Missing timeout argument for method '%s' can cause your program to hang indefinitely
>
> Warns about the absence of a timeout argument in potentially blocking operations, which could lead to indefinite hanging. Specifying timeouts is essential for improving the reliability and performance of code by preventing deadlock situations.
>
> ```python Bad theme={"theme":"css-variables"}
> import requests
>
> requests.post("http://localhost")  # [missing-timeout]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import requests
>
> requests.post("http://localhost", timeout=10)
> ```

> [accordion] Missing type documentation
>
> Indicates missing type documentation for parameters or return values. Type documentation is vital for type safety, readability, and leveraging static analysis tools to catch type-related errors.
>
> ```python Bad theme={"theme":"css-variables"}
> def integer_sum(a: int, b):  # [missing-type-doc]
> """Returns sum of two integers
> :param a: first integer
> :param b: second integer
> """
> return a + b
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def integer_sum(a: int, b: int):
> """Returns sum of two integers
> :param a: first integer
> :param b: second integer
> """
> return a + b
> ```

> [accordion] Missing yield documentation
>
> Flags missing documentation for the yield values of a generator function. Yield documentation is crucial for understanding the generator's output, enhancing readability and usability.
>
> ```python Bad theme={"theme":"css-variables"}
> def even_number_under(n: int):  # [missing-yield-doc]
> """Prints even numbers smaller than n.
> Args:
>     n: Upper limit of even numbers.
> """
> for i in range(n):
>     if i % 2 == 1:
>         continue
>     yield i
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from typing import Iterator
>
>
> def even_number_under(n: int)  Iterator[int]:
> """Prints even numbers smaller than n.
> Args:
>     n: Upper limit of even numbers.
>
> Yields:
>     even numbers
> """
> for i in range(n):
>     if i % 2 == 1:
>         continue
>     yield i
> ```

> [accordion] Missing yield type documentation
>
> Highlights the absence of documentation for the type of values yielded by a generator function. Yield type documentation improves code clarity and assists in type checking and static analysis.
>
> ```python Bad theme={"theme":"css-variables"}
> def even_number_under(n: int):  # [missing-yield-type-doc]
> """Prints even numbers smaller than n.
> Args:
>     n: Upper limit of even numbers.
>
> Yields:
>     even numbers
> """
> for i in range(n):
>     if i % 2 == 1:
>         continue
>     yield i
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from typing import Iterator
>
>
> def even_number_under(n: int)  Iterator[int]:
> """Prints even numbers smaller than n.
> Args:
>     n: Upper limit of even numbers.
>
> Yields:
>     even numbers
> """
> for i in range(n):
>     if i % 2 == 1:
>         continue
>     yield i
> ```

> [accordion] Iterated list '%s' is being modified inside for loop body, consider iterating through a copy of it instead.
>
> Warns that a list being iterated over is also being modified within the loop, which can lead to unexpected behavior. Iterating over a copy of the list is recommended to prevent modification while iterating, ensuring code correctness and predictability.
>
> ```python Bad theme={"theme":"css-variables"}
> fruits = ["apple", "orange", "mango"]
> for fruit in fruits:
> fruits.append("pineapple")  # [modified-iterating-list]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> fruits = ["apple", "orange", "mango"]
> for fruit in fruits.copy():
> fruits.append("pineapple")
> ```

> [accordion] Multiple constructor documentation
>
> Indicates that multiple constructors in a class have documentation, which can be confusing and lead to unclear class usage. Streamlining documentation to clearly present constructor overloads enhances readability and maintainability.
>
> ```python Bad theme={"theme":"css-variables"}
> class Point:  # [multiple-constructor-doc]
> """Represents a point in the xy-coordinate plane.
>
> :param x: coordinate
> :param y: coordinate
> """
>
> def __init__(self, x, y):
>     """Represents a point in the xy-coordinate plane.
>
>     :param x: coordinate
>     :param y: coordinate
>     """
>     self.x = x
>     self.y = y
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Point:
> def __init__(self, x, y):
>     """Represents a point in the xy-coordinate plane.
>
>     :param x: x coordinate
>     :param y: y coordinate
>     """
>     self.x = x
>     self.y = y
> ```

> [accordion] Named expression used without context
>
> Flags the use of a named expression (walrus operator :=) without a clear context, which may lead to confusion or misuse. Using named expressions with clear intent improves code clarity and reduces potential for errors.
>
> ```python Bad theme={"theme":"css-variables"}
> (a := 42)  # [named-expr-without-context]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> if a := 42:
> print("Success")
> ```

> [accordion] Comparison %s should be %s
>
> Warns against direct comparison with NaN (Not a Number), as NaN is not equal to anything, including itself. Recommends using math.isnan() or similar for clarity and correctness.
>
> ```python Bad theme={"theme":"css-variables"}
> import numpy as np
>
>
> def both_nan(x, y)  bool:
> return x == np.NaN and y == float("nan")  # [nan-comparison, nan-comparison]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import numpy as np
>
>
> def both_nan(x, y)  bool:
> return np.isnan(x) and np.isnan(y)
> ```

> [accordion] Do not use nested call of '%s'; it's possible to do '%s' instead
>
> Advises against the nested use of min or max functions, suggesting a single call with multiple arguments instead. This enhances performance by reducing function calls and improves readability by simplifying expressions.
>
> ```python Bad theme={"theme":"css-variables"}
> print(min(1, min(2, 3)))  # [nested-min-max]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print(min(1, 2, 3))
> ```

> [accordion] %s name \\'%s\\' contains a non-ASCII character.
>
> Indicates that a file name contains non-ASCII characters, which might cause issues with tools or environments that do not support such characters, potentially affecting portability and accessibility of the code.

> [accordion] **init** method from a non direct base class %r is called
>
> Warns when an **init** method from a class that is not a direct parent (base class) is called. This could lead to unexpected behavior due to improper initialization chains, highlighting the importance of maintaining a clear and correct inheritance hierarchy.
>
> ```python Bad theme={"theme":"css-variables"}
> class Animal:
> def __init__(self):
>     self.is_multicellular = True
>
>
> class Vertebrate(Animal):
> def __init__(self):
>     super().__init__()
>     self.has_vertebrae = True
>
>
> class Cat(Vertebrate):
> def __init__(self):
>     Animal.__init__(self)  # [non-parent-init-called]
>     self.is_adorable = True
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Animal:
> def __init__(self):
>     self.is_multicellular = True
>
>
> class Vertebrate(Animal):
> def __init__(self):
>     super().__init__()
>     self.has_vertebrae = True
>
>
> class Cat(Vertebrate):
> def __init__(self):
>     super().__init__()
>     self.is_adorable = True
> ```

> [accordion] Non-string value assigned to **name**
>
> Flags the assignment of a non-string value to the **name** attribute, which should always be a string. This ensures compatibility and prevents potential issues with reflection or serialization that rely on **name** being a string.
>
> ```python Bad theme={"theme":"css-variables"}
> class Fruit:
> pass
>
>
> Fruit.__name__ = 1  # [non-str-assignment-to-dunder-name]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Fruit:
> pass
>
>
> Fruit.__name__ = "FRUIT"
> ```

> [accordion] Overlapping exception clauses
>
> Indicates except blocks in a try-except statement that catch exceptions of types that are subclasses of previously caught exceptions, leading to unreachable except blocks and potentially masking exceptions.

> [accordion] Method %r overrides a method decorated with typing.final which is defined in class %r
>
> Flags the overriding of a method marked with typing.final, indicating that the method was intended to be the final override and not further extended, ensuring adherence to the intended design and preventing unintended behavior.
>
> ```python Bad theme={"theme":"css-variables"}
> from typing import final
>
>
> class Animal:
> @final
> def can_breathe(self):
>     return True
>
>
> class Cat(Animal):
> def can_breathe(self):  # [overridden-final-method]
>     pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from typing import final
>
>
> class Animal:
> @final
> def can_breathe(self):
>     return True
>
>
> class Cat(Animal):
> def can_purr(self):
>     return True
> ```

> [accordion] Exception statement has no effect
>
> Highlights an exception statement (raise or except) that has no effect, possibly due to being placed in an unreachable code path or not altering program flow as expected, leading to potential confusion and code cleanliness issues.
>
> ```python Bad theme={"theme":"css-variables"}
> Exception("This exception is a statement.")  # [pointless-exception-statement]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> raise Exception("This will raise.")
> ```

> [accordion] Statement seems to have no effect
>
> Warns about statements that have no effect, such as expressions on their own that neither call functions nor assign values, indicating potential errors or unnecessary code clutter that can hinder readability and maintainability.
>
> ```python Bad theme={"theme":"css-variables"}
> [1, 2, 3]  # [pointless-statement]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> NUMBERS = [1, 2, 3]
>
> print(NUMBERS)
> ```

> [accordion] String statement has no effect
>
> Indicates a string literal placed in the code without being used as a comment or assigned to a variable, suggesting a possible misplaced docstring or dead code that does not contribute to functionality or documentation.
>
> ```python Bad theme={"theme":"css-variables"}
> """This is a docstring which describes the module"""
>
> """This is not a docstring"""  # [pointless-string-statement]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> """This is a docstring which describes the module"""
>
> # This is comment which describes a particular part of the module.
> ```

> [accordion] Possibly unused variable %r
>
> Flags a variable that might not be used after being assigned, suggesting potential unnecessary code or the need for further review to ensure the code's efficiency and cleanliness.
>
> ```python Bad theme={"theme":"css-variables"}
> def choose_fruits(fruits):
> print(fruits)
> color = "red"  # [possibly-unused-variable]
> return locals()
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def choose_fruits(fruits):
> current_locals = locals()
> print(fruits)
> color = "red"
> print(color)
> return current_locals
> ```

> [accordion] Prefer importing %r instead of %r
>
> Recommends using a preferred module over another, possibly due to improvements, deprecations, or performance considerations, guiding developers towards better practices and more maintainable, performant code bases.
>
> ```python Bad theme={"theme":"css-variables"}
> import urllib  # [preferred-module]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import requests
> ```

> [accordion] Access to a protected member %s of a client class
>
> Warns about access to a protected member (prefixed with an underscore) from outside its class or subclass, suggesting potential encapsulation violations and urging respect for intended privacy levels for maintainability and safety.
>
> ```python Bad theme={"theme":"css-variables"}
> class Worm:
> def __swallow(self):
>     pass
>
>
> jim = Worm()
> jim.__swallow()  # [protected-access]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Worm:
> def __swallow(self):
>     pass
>
> def eat(self):
>     return self.__swallow()
>
>
> jim = Worm()
> jim.eat()
> ```

> [accordion] Consider explicitly re-raising using %s'%s from %s'
>
> Suggests explicitly using the raise ... from ... syntax when re-raising exceptions to maintain the exception chain, which aids in debugging by preserving the original traceback information.
>
> ```python Bad theme={"theme":"css-variables"}
> try:
> 1 / 0
> except ZeroDivisionError as e:
> raise ValueError("Rectangle Area cannot be zero")  # [raise-missing-from]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> try:
> 1 / 0
> except ZeroDivisionError as e:
> raise ValueError("Rectangle Area cannot be zero") from e
> ```

> [accordion] Exception arguments suggest string formatting might be intended
>
> Indicates raising an exception with a tuple that seems intended for string formatting, potentially leading to a TypeError or misleading exception messages, emphasizing the importance of clear and correctly formatted error reporting.
>
> ```python Bad theme={"theme":"css-variables"}
> raise RuntimeError("This looks wrong %s %s", ("a", "b"))  # [raising-format-tuple]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> raise RuntimeError("This looks wrong %s %s" % ("a", "b"))
> ```

> [accordion] Redeclared variable %r in assignment
>
> Flags the redeclaration of a name in the same scope, which can lead to confusion and errors by masking previous values, affecting code clarity and predictability.
>
> ```python Bad theme={"theme":"css-variables"}
> FIRST, FIRST = (1, 2)  # [redeclared-assigned-name]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> FIRST, SECOND = (1, 2)
> ```

> [accordion] Redefining built-in %r
>
> Warns against redefining Python built-in names, which can lead to unexpected behavior and compatibility issues, highlighting the importance of maintaining namespace integrity for readability and safety.
>
> ```python Bad theme={"theme":"css-variables"}
> def map():  # [redefined-builtin]
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def map_iterable():
> pass
> ```

> [accordion] Redefinition of loop variable
>
> Indicates the redefinition of a loop variable inside the loop body, potentially leading to confusion or unintended behavior by altering the loop variable in ways that affect loop iteration or clarity.
>
> ```python Bad theme={"theme":"css-variables"}
> def normalize_names(names):
> for name in names:
>     name = name.lower()  # [redefined-loop-name]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def normalize_names(names):
> for name in names:
>     lowercased_name = name.lower()
> ```

> [accordion] Redefining name %r from outer scope (line %s)
>
> Flags the redefinition of a name from an outer scope within a local scope, which can lead to confusion and errors by masking the original value, affecting readability and potentially leading to bugs due to unexpected values.
>
> ```python Bad theme={"theme":"css-variables"}
> count = 10
>
>
> def count_it(count):  # [redefined-outer-name]
> for i in range(count):
>     print(i)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> count = 10
>
>
> def count_it(limit):
> for i in range(limit):
>     print(i)
> ```

> [accordion] Redefined slots %r in subclass
>
> Indicates that slots have been redefined in a subclass, which can lead to inefficiencies and unexpected behavior by altering the memory model intended by the parent class's slots definition.
>
> ```python Bad theme={"theme":"css-variables"}
> class Base:
> __slots__ = ("a", "b")
>
>
> class Subclass(Base):
> __slots__ = ("a", "d")  # [redefined-slots-in-subclass]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Base:
> __slots__ = ("a", "b")
>
>
> class Subclass(Base):
> __slots__ = ("d",)
> ```

> [accordion] Redundant returns documentation
>
> Warns about unnecessary returns documentation in docstrings when the function does not return any value, helping to keep documentation concise and relevant to the function's actual behavior.
>
> ```python Bad theme={"theme":"css-variables"}
> def print_fruits(fruits):  # [redundant-returns-doc]
> """Print list of fruits
>
> Returns
> -------
>     str
> """
> print(fruits)
> return None
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def print_fruits(fruits):
> """Print list of fruits
>
> Returns
> -------
>     str
> """
> print(fruits)
> return ",".join(fruits)
> ```

> [accordion] The u prefix for strings is no longer necessary in Python >=3.0
>
> Highlights the unnecessary use of the 'u' string prefix in Python 3, where all strings are Unicode by default. Removing redundant prefixes improves code clarity and modernizes the codebase for current Python versions.
>
> ```python Bad theme={"theme":"css-variables"}
> def print_fruit():
> print(u"Apple")  # [redundant-u-string-prefix]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def print_fruit():
> print("Apple")
> ```

> [accordion] Redundant use of %s with constant value %r
>
> Flags the use of unittest assertions on constant values, which are either always true or always false, indicating a potential misunderstanding of what needs to be tested or a redundant test condition.
>
> ```python Bad theme={"theme":"css-variables"}
> import unittest
>
>
> class DummyTestCase(unittest.TestCase):
> def test_dummy(self):
>     self.assertTrue("foo")  # [redundant-unittest-assert]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import unittest
>
>
> class DummyTestCase(unittest.TestCase):
> def test_dummy(self):
>     actual = "test_result"
>     self.assertEqual(actual, "expected")
> ```

> [accordion] Redundant yields documentation
>
> Indicates unnecessary documentation for yield values in a generator's docstring when the generator does not yield any value, promoting accuracy and relevance in documentation.
>
> ```python Bad theme={"theme":"css-variables"}
> def give_fruits(fruits):  # [redundant-yields-doc]
> """Something about fruits
>
> Yields
> -------
>     list
>         fruits
> """
> return fruits
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def give_fruits(fruits):
> """Something about fruits
>
> Yields
> -------
>     str
>         fruit
> """
> for fruit in fruits:
>     yield fruit
> ```

> [accordion] Reimport %r (imported line %s)
>
> Warns about a module being imported more than once, which is unnecessary and can lead to confusion about which import the code is actually using, impacting code readability and cleanliness.
>
> ```python Bad theme={"theme":"css-variables"}
> import re
> import re  # [reimported]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import re
> ```

> [accordion] 'return' shadowed by the 'finally' clause.
>
> Flags the use of a return statement within a finally block, which can lead to the suppression of any exception raised in the try or except blocks and obscure the control flow, potentially leading to hidden bugs.
>
> ```python Bad theme={"theme":"css-variables"}
> def second_favorite():
> fruits = ["kiwi", "pineapple"]
> try:
>     return fruits[1]
> finally:
>     # because of this `return` statement, this function will always return "kiwi"
>     return fruits[0]  # [return-in-finally]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def second_favorite():
> fruits = ["kiwi", "pineapple"]
> try:
>     return fruits[1]
> except KeyError:
>     ...
>
> return fruits[0]
> ```

> [accordion] Assigning the same variable %r to itself
>
> Indicates a variable is being assigned to itself, which is redundant and has no effect, suggesting a potential error in the code or an unnecessary operation that can be removed for clarity.
>
> ```python Bad theme={"theme":"css-variables"}
> year = 2000
> year = year  # [self-assigning-variable]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> year = 2000
> ```

> [accordion] Invalid assignment to %s in method
>
> Flags an invalid assignment to self or cls within a method, which could indicate a misunderstanding of how instance and class attributes should be used or modified.
>
> ```python Bad theme={"theme":"css-variables"}
> class Fruit:
> @classmethod
> def list_fruits(cls):
>     cls = "apple"  # [self-cls-assignment]
>
> def print_color(self, *colors):
>     self = "red"  # [self-cls-assignment]
>     color = colors[1]
>     print(color)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Fruit:
> @classmethod
> def list_fruits(cls):
>     fruit = "apple"
>     print(fruit)
>
> def print_color(self, *colors):
>     color = colors[1]
>     print(color)
> ```

> [accordion] Shadowed %r (imported line %s)
>
> Highlights an import statement that is shadowed by another import or definition later in the code, which can lead to confusion about which module or variable is being referred to, affecting maintainability.
>
> ```python Bad theme={"theme":"css-variables"}
> from pathlib import Path
>
> import FastAPI.Path as Path  # [shadowed-import]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from pathlib import Path
>
> import FastAPI.Path as FastApiPath
> ```

> [accordion] Using copy.copy(os.environ). Use os.environ.copy() instead.
>
> Advises against using copy.copy(os.environ) due to os.environ's unique behavior and suggests using os.environ.copy() for a more predictable and safe copying of the environment variables.
>
> ```python Bad theme={"theme":"css-variables"}
> import copy
> import os
>
> copied_env = copy.copy(os.environ)  # [shallow-copy-environ]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import os
>
> copied_env = os.environ.copy()
> ```

> [accordion] Signature differs from %s %r method
>
> Indicates that a method's signature differs from that of a method it overrides or implements from an interface or superclass, which can lead to incorrect behavior or interface contract violations.
>
> ```python Bad theme={"theme":"css-variables"}
> class Animal:
> def run(self, distance=0):
>     print(f"Ran {distance} km!")
>
>
> class Dog(Animal):
> def run(self, distance):  # [signature-differs]
>     super(Animal, self).run(distance)
>     print("Fetched that stick, wuff !")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Animal:
> def run(self, distance=0):
>     print(f"Ran {distance} km!")
>
>
> class Dog(Animal):
> def run(self, distance=0):
>     super(Animal, self).run(distance)
>     print("Fetched that stick, wuff !")
> ```

> [accordion] Class %r is a subclass of a class decorated with typing.final: %r
>
> Flags the subclassing of a class marked with typing.final, which is intended to prevent subclassing to maintain a strict class hierarchy, ensuring adherence to design intentions and preventing unintended inheritance.
>
> ```python Bad theme={"theme":"css-variables"}
> from typing import final
>
>
> @final
> class PlatypusData:
> """General Platypus data."""
>
> average_length = 46
> average_body_temperature = 32
>
>
> class FluorescentPlaytipus(PlatypusData):  # [subclassed-final-class]
> """Playtipus with fluorescent fur."""
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from typing import final
>
>
> @final
> class PlatypusData:
> """General Platypus data."""
>
> average_length = 46
> average_body_temperature = 32
>
>
> def print_average_length_platypus():
> output = f"The average length of a platypus is: {PlatypusData.average_length}cm"
> print(output)
> ```

> [accordion] Using preexec\_fn keyword which may be unsafe in the presence of threads
>
> Warns about the use of preexec\_fn in subprocess.Popen, which can be dangerous in multi-threaded environments, suggesting alternatives that are safer in the presence of threads.
>
> ```python Bad theme={"theme":"css-variables"}
> import subprocess
>
>
> def foo():
> pass
>
>
> subprocess.Popen(preexec_fn=foo)  # [subprocess-popen-preexec-fn]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import subprocess
>
> subprocess.Popen()
> ```

> [accordion] 'subprocess.run' used without explicitly defining the value for 'check'.
>
> Indicates the use of subprocess.run without explicitly setting the 'check' argument, which is important for error handling by raising an exception if the command returns a non-zero exit status, ensuring reliable execution of subprocesses.
>
> ```python Bad theme={"theme":"css-variables"}
> import subprocess
>
> proc = subprocess.run(["ls"])  # [subprocess-run-check]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import subprocess
>
> proc = subprocess.run(["ls"], check=False)
> ```

> [accordion] **init** method from base class %r is not called
>
> Flags instances where a class's **init** method does not call the **init** method of its base class using super(), potentially leading to incomplete initialization and unpredictable behavior, undermining the integrity of class inheritance.
>
> ```python Bad theme={"theme":"css-variables"}
> class Fruit:
> def __init__(self, name="fruit"):
>     self.name = name
>     print("Creating a {self.name}")
>
>
> class Apple(Fruit):
> def __init__(self):  # [super-init-not-called]
>     print("Creating an apple")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Fruit:
> def __init__(self, name="fruit"):
>     self.name = name
>     print("Creating a {self.name}")
>
>
> class Apple(Fruit):
> def __init__(self):
>     super().__init__("apple")
> ```

> [accordion] Super call without brackets
>
> Warns when a super call is made without parentheses, which is a syntax error in Python 3. Correct use of super() is crucial for accessing methods from the parent class correctly and ensuring proper class behavior.
>
> ```python Bad theme={"theme":"css-variables"}
> class Soup:
> @staticmethod
> def temp():
>     print("Soup is hot!")
>
>
> class TomatoSoup(Soup):
> @staticmethod
> def temp():
>     super.temp()  # [super-without-brackets]
>     print("But tomato soup is even hotter!")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Soup:
> @staticmethod
> def temp():
>     print("Soup is hot!")
>
>
> class TomatoSoup(Soup):
> @staticmethod
> def temp():
>     super().temp()
>     print("But tomato soup is even hotter!")
> ```

> [accordion] Too many try statements
>
> Indicates excessive use of try statements within a function or method, which can complicate the control flow and make the code harder to read and maintain. Simplifying error handling can enhance readability and error tracking.
>
> ```python Bad theme={"theme":"css-variables"}
> FRUITS = {"apple": 1, "orange": 10}
>
>
> def pick_fruit(name):
> try:  # [too-many-try-statements]
>     count = FRUITS[name]
>     count += 1
>     print(f"Got fruit count {count}")
> except KeyError:
>     return
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> FRUITS = {"apple": 1, "orange": 10}
>
>
> def pick_fruit(name):
> try:
>     count = FRUITS[name]
> except KeyError:
>     return
>
> count += 1
> print(f"Got fruit count {count}")
> ```

> [accordion] The except handler raises immediately
>
> Flags an except block that immediately re-raises the caught exception without any additional handling, which could be unnecessary and may obscure the origin of the exception, potentially complicating debugging.

> [accordion] Possible unbalanced dict unpacking with %s: left side has %d label%s, right side has %d value%s
>
> Warns about potential mismatches in the number of keys and values when unpacking dictionaries, which could lead to ValueError and indicates a logical error in the expected structure of the dictionary.
>
> ```python Bad theme={"theme":"css-variables"}
> FRUITS = {"apple": 2, "orange": 3, "mellon": 10}
>
> for fruit, price in FRUITS.values():  # [unbalanced-dict-unpacking]
> print(fruit)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> FRUITS = {"apple": 2, "orange": 3, "mellon": 10}
>
> for fruit, price in FRUITS.items():
> print(fruit)
> ```

> [accordion] Possible unbalanced tuple unpacking with sequence %s: left side has %d label%s, right side has %d value%s
>
> Indicates potential mismatches in the number of elements when unpacking tuples, leading to ValueError. Ensuring balanced unpacking is essential for correct assignment and data handling.
>
> ```python Bad theme={"theme":"css-variables"}
> fruits = ("orange", "apple", "strawberry", "peer")
> orange, apple, strawberry = fruits  # [unbalanced-tuple-unpacking]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> fruits = ("orange", "apple", "strawberry", "peer")
> orange, apple, *remaining_fruits = fruits
> ```

> [accordion] Using possibly undefined loop variable %r
>
> Flags the use of a loop variable that may be undefined outside of the loop, potentially leading to NameError and indicating a reliance on the loop for variable definition, which can be error-prone.
>
> ```python Bad theme={"theme":"css-variables"}
> def find_even_number(numbers):
> for x in numbers:
>     if x % 2 == 0:
>         break
> return x  # [undefined-loop-variable]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def find_even_number(numbers):
> for x in numbers:
>     if x % 2:
>         return x
> return None
> ```

> [accordion] Unknown option value in configuration
>
> Indicates the use of an unrecognized value for an option in a configuration file, which could lead to misconfiguration or ignored settings, affecting the tool's or application's behavior.
>
> ```python Bad theme={"theme":"css-variables"}
> # pylint: disable=missnig-docstring  # [unknown-option-value]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> # pylint: disable=missing-docstring
> ```

# step 4

> [accordion] Unnecessary ellipsis constant
>
> Warns about the use of the ellipsis literal (...) in contexts where it has no effect, suggesting the removal of redundant code for clarity and to avoid confusion.
>
> ```python Bad theme={"theme":"css-variables"}
> def my_function():
> """My docstring"""
> ...  # [unnecessary-ellipsis]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def my_function():
> """My docstring"""
> ```

> [accordion] Lambda may not be necessary
>
> Flags the use of lambda functions where a direct function or method reference could be used instead, potentially simplifying the code and improving readability by removing unnecessary lambda wrappers.

> [accordion] Unnecessary pass statement
>
> Indicates the presence of a pass statement that serves no purpose, which can be removed to clean up the code and enhance readability by eliminating redundant placeholders.
>
> ```python Bad theme={"theme":"css-variables"}
> class DataEntryError(Exception):
> """This exception is raised when a user has provided incorrect data."""
>
> pass  # [unnecessary-pass]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class DataEntryError(Exception):
> """This exception is raised when a user has provided incorrect data."""
> ```

> [accordion] Unnecessary semicolon
>
> Flags the use of unnecessary semicolons at the end of statements, a practice not required in Python, which can improve code cleanliness and adhere to Pythonic style guidelines.
>
> ```python Bad theme={"theme":"css-variables"}
> print("Hello World!");  # [unnecessary-semicolon]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print("Hello World!")
> ```

> [accordion] Unreachable code
>
> Warns about code that is logically unreachable due to the control flow, such as statements after a return or raise, highlighting potential errors or unnecessary code segments.
>
> ```python Bad theme={"theme":"css-variables"}
> def say_hello():
> return True
> print("Hello World!, Outside function.")  # [unreachable]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def say_hello():
> print("Hello World!, Inside function.")
> return True
> ```

> [accordion] Using open without explicitly specifying an encoding
>
> Indicates the use of open without specifying an encoding, which can lead to inconsistencies and unexpected behavior when dealing with text files across different environments and platforms.
>
> ```python Bad theme={"theme":"css-variables"}
> def foo(file_path):
> with open(file_path) as file:  # [unspecified-encoding]
>     contents = file.read()
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def foo(file_path):
> with open(file_path, encoding="utf-8") as file:
>     contents = file.read()
> ```

> [accordion] Unused argument %r
>
> Flags arguments of functions or methods that are never used, suggesting potential simplification of the function signature or a review to ensure that all arguments are necessary and used appropriately.
>
> ```python Bad theme={"theme":"css-variables"}
> def print_point(x, y):  # [unused-argument]
> print(f"Point is located at {x},{x}")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def print_point(x, y):
> print(f"Point is located at {x},{y}")
> ```

> [accordion] Unused format argument %r
>
> Warns about arguments provided to a format string that are not used in the formatting, which can indicate errors in the string or redundant arguments that can be removed for clarity.

> [accordion] Unused key %r in format string dictionary
>
> Flags keys provided in a format string dictionary that are not used in the string's placeholders, indicating potential errors in the string or redundant data, which can be removed to enhance clarity and reduce confusion.
>
> ```python Bad theme={"theme":"css-variables"}
> "The quick %(color)s fox jumps over the lazy dog." % {
> "color": "brown",
> "action": "hops",
> }
> # -4: [unused-format-string-key]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> "The quick %(color)s fox %(action)s over the lazy dog." % {
> "color": "brown",
> "action": "hops",
> }
> ```

> [accordion] Unused %s
>
> Indicates import statements that bring modules or specific symbols into the namespace but are never used. Removing unused imports can clean up the code, reduce memory footprint, and decrease load times.
>
> ```python Bad theme={"theme":"css-variables"}
> from logging import getLogger
> from pathlib import Path  # [unused-import]
>
> LOGGER = getLogger(__name__)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from logging import getLogger
>
> LOGGER = getLogger(__name__)
> ```

> [accordion] Unused private member `%s.%s`
>
> Warns about private members of a class (typically prefixed with an underscore) that are defined but not used within the class, suggesting potential for simplifying the class by removing unnecessary members.
>
> ```python Bad theme={"theme":"css-variables"}
> class Fruit:
> FRUITS = {"apple": "red", "orange": "orange"}
>
> def __print_color(self):  # [unused-private-member]
>     pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Fruit:
> FRUITS = {"apple": "red", "orange": "orange"}
>
> def __print_color(self, name, color):
>     print(f"{name}: {color}")
>
> def print(self):
>     for fruit, color in self.FRUITS.items():
>         self.__print_color(fruit, color)
> ```

> [accordion] Unused variable %r
>
> Flags variables that are assigned but never used thereafter, which can indicate either leftover code from refactoring, placeholders for future code, or simply unnecessary variable assignments that can be removed for cleanliness.
>
> ```python Bad theme={"theme":"css-variables"}
> def print_fruits():
> fruit1 = "orange"
> fruit2 = "apple"  # [unused-variable]
> print(fruit1)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def print_fruits():
> fruit1 = "orange"
> fruit2 = "apple"
> print(fruit1, fruit2)
> ```

> [accordion] Unused import(s) %s from wildcard import of %s
>
> Indicates that specific symbols imported via a wildcard import (from module import \*) are not used, which can lead to namespace pollution and potentially obscure the origin of various symbols, reducing code readability.
>
> ```python Bad theme={"theme":"css-variables"}
> from abc import *  # [unused-wildcard-import]
>
>
> class Animal(ABC): ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from abc import ABC
>
>
> class Animal(ABC): ...
> ```

> [accordion] Else clause on loop without a break statement, remove the else and de-indent all the code inside it
>
> Flags an else block following a loop that does not contain a break statement. Since the else part only executes if the loop completes normally, without encountering a break, an else without a break is redundant and can be removed for simplicity.
>
> ```python Bad theme={"theme":"css-variables"}
> def find_even_number(numbers):
> for x in numbers:
>     if x % 2 == 0:
>         return x
> else:  # [useless-else-on-loop]
>     print("Did not find an even number")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def find_even_number(numbers):
> for x in numbers:
>     if x % 2 == 0:
>         return x
> print("Did not find an even number")
> ```

> [accordion] Useless parameter documentation
>
> Highlights parameter documentation in docstrings for parameters that either don't exist or are otherwise unnecessary, suggesting that documentation should be concise and relevant to the implemented functionality.
>
> ```python Bad theme={"theme":"css-variables"}
> def say_hello(_new: str)  str:  # [useless-param-doc]
> """say hello!
>
> :param _new:
> :return: comment
> """
> return "hello"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def say_hello(_new: str)  str:
> """say hello!
>
> :return: comment
> """
> return "hello"
> ```

> [accordion] Useless parent or super() delegation in method %r
>
> Indicates a method that simply calls the same method on super() without any additional logic, which could be unnecessary and may be removed unless explicitly required for interface consistency or future extension points.
>
> ```python Bad theme={"theme":"css-variables"}
> class Animal:
> def eat(self, food):
>     print(f"Eating {food}")
>
>
> class Human(Animal):
> def eat(self, food):  # [useless-parent-delegation]
>     super(Human, self).eat(food)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Animal:
> def eat(self, food):
>     print(f"Eating {food}")
>
>
> class Human(Animal):
> """There is no need to override 'eat' it has the same signature as the implementation in Animal."""
> ```

> [accordion] Useless type documentation
>
> Warns about type documentation that is redundant or not useful, perhaps due to the use of type hints or other clear type indications in the code, advocating for maintaining only meaningful and helpful documentation.
>
> ```python Bad theme={"theme":"css-variables"}
> def print_fruit(fruit, _):  # [useless-type-doc]
> """docstring ...
>
> Args:
>     fruit (str): A fruit.
>     _ (float): Another argument.
> """
> print(fruit)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def print_fruit(fruit):
> """docstring ...
>
> Args:
>     fruit (str): A fruit.
> """
> print(fruit)
> ```

> [accordion] '%s()' directly created in 'with' has no effect
>
> Indicates a context manager (often a lock) used in a with statement that does not affect the enclosed code block, suggesting a review of the lock's necessity or the correctness of its usage within the context.
>
> ```python Bad theme={"theme":"css-variables"}
> import threading
>
> with threading.Lock():  # [useless-with-lock]
> print("Make your bed.")
> with threading.Lock():  # [useless-with-lock]
> print("Sleep in it")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import threading
>
> lock = threading.Lock()
> with lock:
> print("Make your bed.")
> with lock:
> print("Sleep in it.")
> ```

> [accordion] Using a conditional statement with a constant value
>
> Flags the use of constant values in conditional statements, which results in branches that are either always executed or never reached, pointing to potential logic errors or unnecessary code segments.
>
> ```python Bad theme={"theme":"css-variables"}
> if 0:  # [using-constant-test]
> print("This code is never executed.")
> if 1:  # [using-constant-test]
> print("This code is always executed.")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print("This code is always executed.")
> ```

> [accordion] F-strings are not supported by all versions included in the py-version setting
>
> Warns about the use of f-strings in codebases that aim to support Python versions older than 3.6, where f-strings are not available, affecting compatibility and potentially leading to syntax errors in those versions.
>
> ```python Bad theme={"theme":"css-variables"}
> f"python {3.5} is past end of life"  # [using-f-string-in-unsupported-version]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> "python {} is past end of life".format(3.5)
> ```

> [accordion] typing.final is not supported by all versions included in the py-version setting
>
> Indicates the use of the typing.final decorator in projects that must be compatible with Python versions that do not support this feature, potentially leading to runtime errors or ignored annotations in those versions.
>
> ```python Bad theme={"theme":"css-variables"}
> from typing import final
>
>
> @final  # [using-final-decorator-in-unsupported-version]
> class Playtypus(Animal):
> @final  # [using-final-decorator-in-unsupported-version]
> def lay_egg(self): ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Playtypus(Animal):
> def lay_egg(self): ...
> ```

> [accordion] While used unnecessarily
>
> Flags the use of a while loop that could be unnecessary or replaced with a more suitable control flow construct, indicating that the use of while may not be the most efficient or readable approach.
>
> ```python Bad theme={"theme":"css-variables"}
> import requests
>
>
> def fetch_data():
> i = 1
> while i < 6:  # [while-used]
>     print(f"Attempt {i}...")
>     try:
>         return requests.get("https://example.com/data")
>     except requests.exceptions.RequestException:
>         pass
>     i += 1
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import requests
>
>
> def fetch_data():
> for i in range(1, 6):
>     print(f"Attempt {i}...")
>     try:
>         return requests.get("https://example.com/data")
>     except requests.exceptions.RequestException:
>         pass
> ```

> [accordion] Wildcard import %s
>
> Warns against the use of wildcard imports, which can obscure the source of variables and functions, complicate dependency tracking, and potentially lead to conflicts in the namespace, reducing code readability and maintainability.
>
> ```python Bad theme={"theme":"css-variables"}
> from abc import *  # [wildcard-import]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> # Either import module or
> # only import required objects from module.
> import abc
> from abc import ABC, abstractmethod
> ```

> [accordion] Invalid exception operation. %s
>
> Flags invalid operations performed with exceptions, such as attempting to concatenate strings with exception objects directly, highlighting the importance of correct exception handling and manipulation for clear error reporting and code reliability.
>
> ```python Bad theme={"theme":"css-variables"}
> try:
> 1 / 0
> except ValueError + TypeError:  # [wrong-exception-operation]
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> try:
> 1 / 0
> except (ValueError, TypeError):
> pass
> ```

> [accordion] Broad except clause used
>
> Warns against the use of a broad except clause (except Exception: or except:) that catches all exceptions. This practice can obscure specific errors and complicate debugging. Narrowing down the caught exceptions can improve error handling specificity and maintainability.

> [accordion] Cache with max size None
>
> Indicates the use of a cache (like functools.lru\_cache) without specifying a max size, potentially leading to unbounded memory usage. Specifying a max size can improve performance and prevent resource exhaustion.

> [accordion] Implicit string concatenation in sequence
>
> Flags cases of implicit string concatenation within sequences like lists or tuples, which can be error-prone and reduce readability. Explicit concatenation or joining is recommended for clarity.

> [accordion] LRU cache decorating method
>
> Warns about the use of an LRU (Least Recently Used) cache decorator on a method, which can lead to unexpected behavior if not used correctly, especially concerning self argument handling and cache key generation.

> [accordion] Assignment from None in old Python version
>
> Indicates assignment from None in older versions of Python, where this pattern may have different implications or be part of now-deprecated practices, suggesting a review for compatibility and modern Python practices.

> [accordion] Deprecated argument in old Python version
>
> Flags the use of arguments that are deprecated in older versions of Python, emphasizing the need to update code to use current, supported arguments for functions and methods.

> [accordion] Deprecated class in old Python version
>
> Warns about the use of classes that are deprecated in older Python versions, suggesting the need for updates or alternatives to maintain compatibility with current Python standards and practices.

> [accordion] Deprecated decorator in old Python version
>
> Indicates the use of decorators that are deprecated in older versions of Python, highlighting the importance of keeping code up-to-date with current Python idioms and best practices.

> [accordion] Deprecated method in old Python version
>
> Flags methods that are deprecated in older versions of Python, underscoring the need to adapt code to use supported methods and practices in contemporary Python development.

> [accordion] Deprecated module in old Python version
>
> Warns about the reliance on modules that are deprecated in older Python versions, suggesting a transition to current modules and libraries for better compatibility and feature support.

> [accordion] Empty docstring in old Python version
>
> Indicates the presence of empty docstrings in older versions of Python, where comprehensive documentation might have been overlooked or neglected, emphasizing the value of complete and informative documentation.

> [accordion] Missing parameter documentation in old Python version
>
> Flags missing documentation for parameters in functions or methods in older Python versions, stressing the importance of complete docstrings for clarity, usability, and maintainability of code.

> [accordion] Missing returns documentation in old Python version
>
> Highlights missing documentation for return values in older versions of Python, indicating a gap in docstrings that can affect the understandability and correctness of code documentation.

> [accordion] Missing type documentation in old Python version
>
> Indicates missing type documentation in older versions of Python, where specifying parameter and return types can improve readability, type checking, and overall code quality.

> [accordion] Missing yields documentation in old Python version
>
> Warns about missing documentation for yielded values in generator functions in older versions of Python, emphasizing the need for comprehensive docstrings to inform users of the function's behavior and output.

> [accordion] Non-iterator returned in old Python version
>
> Flags an issue in older versions of Python where a function expected to return an iterator instead returns a non-iterator object. Ensuring that iterators conform to the expected protocol is crucial for compatibility with iteration mechanisms, enhancing code robustness and preventing runtime errors during iteration processes.

> [accordion] Type check is unidiomatic in old Python version
>
> Indicates the use of type checking methods that are considered unidiomatic in older Python versions, suggesting a transition towards more Pythonic practices like using isinstance() for type checking. Adopting idiomatic type checks can improve code readability and compatibility with Python's dynamic and polymorphic nature.

> [accordion] Unpacking a non-sequence in old Python version
>
> Warns about attempts to unpack non-sequences in older versions of Python, which can lead to errors. This highlights the importance of ensuring that objects being unpacked support the sequence protocol, maintaining code correctness and preventing runtime exceptions.

> [accordion] Useless delegation to super method
>
> Indicates a method that simply calls the same method on its superclass using super() without any modification to arguments or behavior. Such direct delegation can often be unnecessary, suggesting a review of the method's utility and potentially simplifying the class hierarchy.

> [accordion] Class method %s should have %s as first argument
>
> Flags a class method where the first argument is not conventionally named 'cls', which is a best practice for readability and clarity in indicating that the method is bound to the class and not an instance.
>
> ```python Bad theme={"theme":"css-variables"}
> class Klass:
> @classmethod
> def get_instance(self):  # [bad-classmethod-argument]
>     return self()
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Klass:
> @classmethod
> def get_instance(cls):
>     return cls()
> ```

> [accordion] Inconsistent docstring quotes
>
> Warns about inconsistency in the quotes used for docstrings within the same project or module, recommending a consistent style for quotes to enhance readability and maintain coding style consistency.
>
> ```python Bad theme={"theme":"css-variables"}
> def foo():  # [bad-docstring-quotes]
> "Docstring."
> return
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def foo():
> """Docstring."""
> return
> ```

> [accordion] PEP8 recommends UTF-8 as encoding for Python files
>
> Indicates that a Python file does not use UTF-8 encoding, which is recommended by PEP 8 for compatibility and to support international characters. Ensuring UTF-8 encoding can improve the portability and usability of code across different platforms and locales.

> [accordion] Metaclass class method %s should have %s as first argument
>
> Flags a class method within a metaclass where the first argument is not named 'cls', emphasizing the importance of adhering to conventional naming for clarity in the special context of metaclasses.
>
> ```python Bad theme={"theme":"css-variables"}
> class Meta(type):
> @classmethod
> def foo(some):  # [bad-mcs-classmethod-argument]
>     pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Meta(type):
> @classmethod
> def foo(mcs):
>     pass
> ```

> [accordion] Metaclass method %s should have %s as first argument
>
> Highlights a method within a metaclass where the first argument does not follow the convention (e.g., not named 'cls' or 'self'), which can lead to confusion about the method's context and binding, particularly in the nuanced area of metaclass design.
>
> ```python Bad theme={"theme":"css-variables"}
> class Meta(type):
> def func(some):  # [bad-mcs-method-argument]
>     pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Meta(type):
> def func(cls):
>     pass
> ```

> [accordion] Consider iterating the dictionary directly instead of calling .keys()
>
> Suggests iterating directly over a dictionary to access keys instead of calling .keys(), which is unnecessary and less efficient. Direct iteration is more Pythonic and improves code readability and performance.
>
> ```python Bad theme={"theme":"css-variables"}
> FRUITS = {"apple": 1, "pear": 5, "peach": 10}
>
>
> for fruit in FRUITS.keys():  # [consider-iterating-dictionary]
> print(fruit)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> FRUITS = {"apple": 1, "pear": 5, "peach": 10}
>
>
> for fruit in FRUITS:
> print(fruit)
> ```

> [accordion] Consider using 'any' or 'all'
>
> Recommends using the 'any' or 'all' functions for concise and idiomatic testing of conditionals across iterables, enhancing code readability and potentially improving performance by utilizing built-in optimizations.
>
> ```python Bad theme={"theme":"css-variables"}
> def all_even(items):
> """Return True if the list contains all even numbers"""
> for item in items:  # [consider-using-any-or-all]
> if not item % 2 == 0:
>     return False
> return True
>
> def any_even(items):
> """Return True if the list contains any even numbers"""
> for item in items:  # [consider-using-any-or-all]
>     if item % 2 == 0:
>         return True
> return False
>
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def all_even(items):
> """Return True if the list contains all even numbers"""
> return all(item % 2 == 0 for item in items)
>
> def any_even(items):
> """Return True if the list contains any even numbers"""
> return any(item % 2 == 0 for item in items)
>
> ```

> [accordion] Consider iterating with .items()
>
> Advises iterating over a dictionary using .items() when both keys and values are needed, which is more efficient and clearer than accessing keys and values separately, improving code readability and performance.
>
> ```python Bad theme={"theme":"css-variables"}
> ORCHESTRA = {
> "violin": "strings",
> "oboe": "woodwind",
> "tuba": "brass",
> "gong": "percussion",
> }
>
>
> for instrument in ORCHESTRA:  # [consider-using-dict-items]
> print(f"{instrument}: {ORCHESTRA[instrument]}")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ORCHESTRA = {
> "violin": "strings",
> "oboe": "woodwind",
> "tuba": "brass",
> "gong": "percussion",
> }
>
>
> for instrument, section in ORCHESTRA.items():
> print(f"{instrument}: {section}")
> ```

> [accordion] Consider using enumerate instead of iterating with range and len
>
> Suggests using enumerate for iterating over sequences when both the index and value are needed, instead of using range and len. This approach is more Pythonic, enhancing readability and simplicity by directly providing the index and value during iteration.
>
> ```python Bad theme={"theme":"css-variables"}
> seasons = ["Spring", "Summer", "Fall", "Winter"]
>
> for i in range(len(seasons)):  # [consider-using-enumerate]
> print(i, seasons[i])
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> seasons = ["Spring", "Summer", "Fall", "Winter"]
>
> for i, season in enumerate(seasons):
> print(i, season)
> ```

> [accordion] Formatting a regular string which could be an f-string
>
> Suggests the use of f-strings for string formatting to enhance readability and performance. F-strings, introduced in Python 3.6, offer a more readable and concise syntax for embedding expressions inside string literals compared to traditional formatting methods.
>
> ```python Bad theme={"theme":"css-variables"}
> from string import Template
>
> menu = ("eggs", "spam", 42.4)
>
> old_order = "%s and %s: %.2f ¤" % menu  # [consider-using-f-string]
> beginner_order = menu[0] + " and " + menu[1] + ": " + str(menu[2]) + " ¤"
> joined_order = " and ".join(menu[:2])
> # +1: [consider-using-f-string]
> format_order = "{} and {}: {:0.2f} ¤".format(menu[0], menu[1], menu[2])
> # +1: [consider-using-f-string]
> named_format_order = "{eggs} and {spam}: {price:0.2f} ¤".format(
> eggs=menu[0], spam=menu[1], price=menu[2]
> )
> template_order = Template("$eggs and $spam: $price ¤").substitute(
> eggs=menu[0], spam=menu[1], price=menu[2]
> )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> menu = ("eggs", "spam", 42.4)
>
> f_string_order = f"{menu[0]} and {menu[1]}: {menu[2]:0.2f} ¤"
> ```

> [accordion] Mutation during dictionary initialization
>
> Warns about mutations (changes) being made to a dictionary during its initialization phase. Such mutations can lead to confusing code and potential errors, emphasizing the need for clear and predictable dictionary initialization practices.
>
> ```python Bad theme={"theme":"css-variables"}
> fruit_prices = {}  # [dict-init-mutate]
> fruit_prices["apple"] = 1
> fruit_prices["banana"] = 10
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> fruit_prices = {"apple": 1, "banana": 10}
> ```

> [accordion] Disallowed name \\'%s\\'
>
> Flags the use of a name that has been marked as disallowed or inappropriate in the context of the project, potentially due to naming conventions or to avoid shadowing built-in functions or keywords, enhancing code clarity and avoiding confusion.
>
> ```python Bad theme={"theme":"css-variables"}
> def foo():  # [disallowed-name]
> print("apples")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def print_fruit():
> print("apples")
> ```

> [accordion] First line of docstring is empty
>
> Indicates that the first line of a docstring is empty, contrary to the convention that the first line should provide a concise summary of the object's purpose, affecting documentation quality and readability.
>
> ```python Bad theme={"theme":"css-variables"}
> def foo():  # [docstring-first-line-empty]
> """
>
> Lorem Ipsum is simply dummy text of the printing and typesetting
> industry.
>
> Lorem Ipsum has been the industry's standard dummy text ever since the
> 1500s, when an unknown printer took a galley of type and scrambled it
> to make a type specimen book
> """
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def foo():
> """Lorem Ipsum is simply dummy text of the printing and typesetting
> industry.
>
> Lorem Ipsum has been the industry's standard dummy text ever since the
> 1500s, when an unknown printer took a galley of type and scrambled it
> to make a type specimen book
> """
> ```

> [accordion] Empty %s docstring
>
> Flags the presence of an empty docstring, suggesting that documentation is either missing or incomplete, which can hinder understandability and maintainability by leaving the purpose and usage of code elements undocumented.
>
> ```python Bad theme={"theme":"css-variables"}
> def foo():  # [empty-docstring]
> """"""
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def foo():
> """A dummy description."""
> ```

> [accordion] Import outside toplevel (%s)
>
> Warns about imports that are not at the top level of the module but nested within functions or conditionals, which can lead to performance issues and reduce the clarity of module dependencies.
>
> ```python Bad theme={"theme":"css-variables"}
> def print_python_version():
> import sys  # [import-outside-toplevel]
>
> print(sys.version_info)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import sys
>
>
> def print_python_version():
> print(sys.version_info)
> ```

> [accordion] Private name imported
>
> Indicates that a name intended to be private (typically prefixed with an underscore) is being imported, potentially violating encapsulation principles and leading to tighter coupling between components.
>
> ```python Bad theme={"theme":"css-variables"}
> from argparse import _AttributeHolder, _SubParsersAction  # [import-private-name]
>
> attr_holder = _AttributeHolder()
>
>
> def add_sub_parser(sub_parsers: _SubParsersAction):
> sub_parsers.add_parser("my_subparser")
> # ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> """Private import can be used as type annotations."""
>
> from argparse import _SubParsersAction
>
>
> def add_sub_parser(sub_parsers: _SubParsersAction):
> sub_parsers.add_parser("my_subparser")
> # ...
> ```

> [accordion] Invalid characters %r in a docstring
>
> Flags the use of invalid or non-standard characters in a docstring, which could affect the readability of the documentation or cause issues with documentation generation tools.

> [accordion] %s name \\'%s\\' doesn't conform to %s
>
> Indicates that a name (variable, function, class, etc.) does not conform to the naming conventions specified for the project, affecting code consistency, readability, and maintainability.
>
> ```python Bad theme={"theme":"css-variables"}
> class cat:  # [invalid-name]
> def Meow(self, NUMBER_OF_MEOW):  # [invalid-name, invalid-name]
>     print("Meow" * NUMBER_OF_MEOW)
>     return NUMBER_OF_MEOW
>
>
> Cat = cat().Meow(42)  # [invalid-name]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Cat:
> def meow(self, number_of_meow):
>     print("Meow" * number_of_meow)
>     return number_of_meow
>
>
> CAT = Cat().meow(42)
> ```

> [accordion] Line too long (%s/%s)
>
> Warns that a line of code exceeds the recommended length, affecting readability by making the code harder to read without horizontal scrolling or line wrapping, contrary to PEP 8 recommendations.
>
> ```python Bad theme={"theme":"css-variables"}
> # +1: [line-too-long]
> FRUIT = ["apricot", "blackcurrant", "cantaloupe", "dragon fruit", "elderberry", "fig", "grapefruit", ]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> FRUIT = [
> "apricot",
> "blackcurrant",
> "cantaloupe",
> "dragon fruit",
> "elderberry",
> "fig",
> "grapefruit",
> ]
> ```

> [accordion] Comparison constant misplaced
>
> Suggests that the constant in a comparison should be placed on the right-hand side, following conventional readability practices and making the code easier to understand at a glance.
>
> ```python Bad theme={"theme":"css-variables"}
> def compare_apples(apples=20):
> for i in range(10):
>     if 5 <= i:  # [misplaced-comparison-constant]
>         pass
>     if 1 == i:  # [misplaced-comparison-constant]
>         pass
>     if 20 < len(apples):  # [misplaced-comparison-constant]
>         pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def compare_apples(apples=20):
> for i in range(10):
>     if i >= 5:
>         pass
>     if i == 1:
>         pass
>     if len(apples) > 20:
>         pass
> ```

> [accordion] Missing class docstring
>
> Flags a class without a docstring, suggesting that documentation is missing that would explain the class's purpose, usage, and behavior, which is vital for maintainability and usability.
>
> ```python Bad theme={"theme":"css-variables"}
> class Person:  # [missing-class-docstring]
> def __init__(self, first_name, last_name):
>     self.first_name = first_name
>     self.last_name = last_name
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Person:
> """Class representing a person"""
>
> def __init__(self, first_name, last_name):
>     self.first_name = first_name
>     self.last_name = last_name
> ```

> [accordion] Final newline missing
>
> Indicates that the final newline is missing from a file, which is a common convention for text files and can help with processing files in Unix-like environments, enhancing compatibility and adherence to standards.

> [accordion] Missing function or method docstring
>
> Flags a function or method without a docstring, highlighting the absence of essential documentation that describes what the function does, its parameters, and its return value, affecting code clarity and maintainability.
>
> ```python Bad theme={"theme":"css-variables"}
> import sys
>
>
> def print_python_version():  # [missing-function-docstring]
> print(sys.version)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import sys
>
>
> def print_python_version():
> """Function printing python version."""
> print(sys.version)
> ```

> [accordion] Missing module docstring
>
> Indicates the absence of a module-level docstring, which should introduce the module and summarize its purpose and contents, affecting the understandability and discoverability of the module's functionality.
>
> ```python Bad theme={"theme":"css-variables"}
> import sys  # [missing-module-docstring]
>
>
> def print_python_version():
> print(sys.version)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> """Module providing a function printing python version."""
>
> import sys
>
>
> def print_python_version():
> print(sys.version)
> ```

> [accordion] Mixed line endings LF and CRLF
>
> Warns about the presence of mixed line endings (LF and CRLF) within a file, which can lead to inconsistencies and issues in version control systems, emphasizing the need for uniform line endings.

> [accordion] Multiple imports on one line (%s)
>
> Flags a line that imports multiple modules or symbols, suggesting splitting imports into separate lines for better readability and adherence to PEP 8's import formatting guidelines.
>
> ```python Bad theme={"theme":"css-variables"}
> import os, sys  # [multiple-imports]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import os
> import sys
> ```

> [accordion] More than one statement on a single line
>
> Indicates that more than one statement is present on a single line, which can hinder readability and maintainability by compacting too much logic into a small space, contrary to PEP 8's recommendations.
>
> ```python Bad theme={"theme":"css-variables"}
> fruits = ["apple", "orange", "mango"]
>
> if "apple" in fruits: pass  # [multiple-statements]
> else:
> print("no apples!")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> fruits = ["apple", "orange", "mango"]
>
> if "apple" in fruits:
> pass
> else:
> print("no apples!")
> ```

> [accordion] %s name \\'%s\\' contains a non-ASCII character, use an ASCII-only alias for import.
>
> Warns when a module name contains non-ASCII characters and suggests using an ASCII-only alias for importing. This practice enhances code portability and avoids issues in environments with limited Unicode support, ensuring broader compatibility.
>
> ```python Bad theme={"theme":"css-variables"}
> from os.path import join as łos  # [non-ascii-module-import]
>
> foo = łos("a", "b")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from os.path import join as os_join
>
> foo = os_join("a", "b")
> ```

> [accordion] %s name \\'%s\\' contains a non-ASCII character, consider renaming it.
>
> Indicates the use of non-ASCII characters in a name (variable, function, class, etc.), recommending renaming to ASCII-only characters for improved code readability and compatibility across diverse execution environments.
>
> ```python Bad theme={"theme":"css-variables"}
> ápple_count = 4444  # [non-ascii-name]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> apple_count = 4444
> ```

> [accordion] Class **slots** should be a non-string iterable
>
> Flags the definition of **slots** in a class as a single string rather than as an iterable of strings, which can lead to a misunderstanding of **slots** behavior, affecting memory optimization intentions by creating only one slot with the entire string.
>
> ```python Bad theme={"theme":"css-variables"}
> class Fruit:  # [single-string-used-for-slots]
> __slots__ = "name"
>
> def __init__(self, name):
>     self.name = name
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Fruit:
> __slots__ = ("name",)
>
> def __init__(self, name):
>     self.name = name
> ```

> [accordion] Comparison %s should be %s
>
> Advises against comparing singleton objects (like None) using == or !=. Recommends using 'is' or 'is not' for clarity and performance, as these operators check for object identity, which is more appropriate for singletons.
>
> ```python Bad theme={"theme":"css-variables"}
> game_won = True
> if game_won == True:  # [singleton-comparison]
> print("Game won !")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> game_won = True
> if game_won:
> print("Game won !")
> ```

> [accordion] Unnecessary parens after %r keyword
>
> Highlights the unnecessary use of parentheses after certain keywords (e.g., return, yield), where the syntax does not require them. Removing superfluous parentheses can improve code readability and stylistic consistency.

> [accordion] Too many lines in module (%s/%s)
>
> Indicates that a module exceeds the recommended maximum line count, suggesting potential refactoring or modularization to enhance maintainability, readability, and ease of navigation within the codebase.

> [accordion] Trailing newlines
>
> Flags extra newline characters at the end of a file, recommending a single newline to adhere to conventions and maintain consistency across files, aiding in cleaner version control diffs and file concatenation behaviors.
>
> ```python Bad theme={"theme":"css-variables"}
> print("apple")
> # The file ends with 2 lines that are empty # +1: [trailing-newlines]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print("apple")
> ```

> [accordion] Trailing whitespace
>
> Warns about whitespace characters (spaces, tabs) at the end of lines, which can introduce unnecessary noise in version control diffs and may affect the cleanliness of the codebase.
>
> ```python Bad theme={"theme":"css-variables"}
> print("Hello")  # [trailing-whitespace]   
> #                                       ^^^ trailing whitespaces
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print("Hello")
> ```

> [accordion] TypeVar cannot be both covariant and contravariant
>
> Indicates a TypeVar defined with both covariant and contravariant flags, which is not allowed as a type variable cannot be both. This rule ensures correct usage of type variance in generics, improving type checking accuracy.
>
> ```python Bad theme={"theme":"css-variables"}
> from typing import TypeVar
>
> T = TypeVar("T", covariant=True, contravariant=True)  # [typevar-double-variance]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from typing import TypeVar
>
> T_co = TypeVar("T_co", covariant=True)
> T_contra = TypeVar("T_contra", contravariant=True)
> ```

> [accordion] Type variable name does not reflect variance%s
>
> Flags a TypeVar whose name does not reflect its declared variance (covariant or contravariant), suggesting naming conventions that make the variance explicit, enhancing code readability and type safety.
>
> ```python Bad theme={"theme":"css-variables"}
> from typing import TypeVar
>
> T_co = TypeVar("T_co")  # [typevar-name-incorrect-variance]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from typing import TypeVar
>
> T = TypeVar("T")
> ```

> [accordion] TypeVar name \\'%s\\' does not match assigned variable name \\'%s\\'
>
> Indicates a mismatch between the name of a TypeVar and the variable it's assigned to, emphasizing the importance of consistency in type variable naming for clarity and maintainability in type annotations.
>
> ```python Bad theme={"theme":"css-variables"}
> from typing import TypeVar
>
> X = TypeVar("T")  # [typevar-name-mismatch]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from typing import TypeVar
>
> T = TypeVar("T")
> ```

> [accordion] Unexpected line ending format. There is '%s' while it should be '%s'.
>
> Warns about a file using a different line ending format than expected (e.g., CRLF instead of LF), recommending consistency to avoid issues in cross-platform development environments and version control systems.
>
> ```python Bad theme={"theme":"css-variables"}
> print("I'm drinking tea!")  # CRLF (
> ) # [unexpected-line-ending-format]
> print("I'm drinking water!")  # CRLF (
> ) # [unexpected-line-ending-format]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print("I'm drinking tea!")  # LF (
> )
> print("I'm drinking water!")  # LF (
> )
> ```

> [accordion] Imports from package %s are not grouped
>
> Indicates imports from the same package that are not grouped together, recommending organizing imports by package to improve readability, simplify dependency tracking, and adhere to PEP 8's import organization guidelines.
>
> ```python Bad theme={"theme":"css-variables"}
> import logging
> import os
> import sys
> import logging.config  # [ungrouped-imports]
> from logging.handlers import WatchedFileHandler
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import logging
> import logging.config
> import os
> import sys
> from logging.handlers import FileHandler
> ```

> [accordion] Use isinstance() rather than type() for a typecheck.
>
> Advises using isinstance() for type checks instead of type(), as isinstance() supports inheritance and is considered more Pythonic. This approach allows for more flexible and reliable type checking, especially in the presence of inheritance hierarchies.
>
> ```python Bad theme={"theme":"css-variables"}
> test_score = {"Biology": 95, "History": 80}
> if type(test_score) is dict:  # [unidiomatic-typecheck]
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> test_score = {"Biology": 95, "History": 80}
> if isinstance(test_score, dict):
> pass
> ```

> [accordion] Lambda expression called directly. Execute the expression inline instead.
>
> Points out that a lambda function is being called directly at the point of definition, suggesting that the lambda's body could be executed directly instead, simplifying the code by removing the unnecessary lambda wrapper.
>
> ```python Bad theme={"theme":"css-variables"}
> y = (lambda x: x**2 + 2 * x + 1)(a)  # [unnecessary-direct-lambda-call]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> y = a**2 + 2 * a + 1
> ```

> [accordion] Unnecessarily calls dunder method %s. %s.
>
> Indicates a direct call to a double-underscore method (dunder method) like **str**(), recommending the use of the corresponding built-in function (str()) instead. This practice enhances readability and adheres to Pythonic conventions.
>
> ```python Bad theme={"theme":"css-variables"}
> three = (3.0).__str__()  # [unnecessary-dunder-call]
> twelve = "1".__add__("2")  # [unnecessary-dunder-call]
>
>
> def is_bigger_than_two(x):
> return x.__gt__(2)  # [unnecessary-dunder-call]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> three = str(3.0)
> twelve = "1" + "2"
>
>
> def is_bigger_than_two(x):
> return x > 2
> ```

> [accordion] Lambda expression assigned to a variable. Define a function using the \\'def\\' keyword instead.
>
> Warns against assigning a lambda function to a variable, suggesting the definition of a regular function with def for clarity and simplicity. Regular functions are more straightforward and can be named, improving code readability.
>
> ```python Bad theme={"theme":"css-variables"}
> foo = lambda x: x**2 + 2 * x + 1  # [unnecessary-lambda-assignment]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def foo(x):
> return x**2 + 2 * x + 1
> ```

> [accordion] Consider changing \\'%s\\' to \\'%s\\'
>
> Suggests rephrasing expressions that use unnecessary negation to their positive counterparts, enhancing readability and reducing cognitive load by simplifying conditional logic.

> [accordion] \\'%s\\' can be simplified to \\'%s\\', if it is strictly a sequence, as an empty %s is falsey
>
> Recommends relying on the implicit boolean value of sequences instead of explicit comparison with their length or empty literals, simplifying conditions and leveraging Python's truthy and falsey evaluation.
>
> ```python Bad theme={"theme":"css-variables"}
> z = []
>
> if z != []:  # [use-implicit-booleaness-not-comparison]
> print("z is not an empty sequence")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> z = []
>
> if z:
> print("z is not an empty sequence")
> ```

> [accordion] \\'%s\\' can be simplified to \\'%s\\', if it is striclty a string, as an empty string is falsey
>
> Similar to the above, advises using the implicit boolean value of strings for conditions, avoiding explicit empty string comparisons, and thus simplifying the code by utilizing Python's evaluation of empty strings as falsey.
>
> ```python Bad theme={"theme":"css-variables"}
> def important_string_manipulation(x: str, y: str)  None:
> if x == "":  # [use-implicit-booleaness-not-comparison-to-string]
>     print("x is an empty string")
>
> if y != "":  # [use-implicit-booleaness-not-comparison-to-string]
>     print("y is not an empty string")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def important_string_manipulation(x: str, y: str)  None:
> if not x:
>     print("x is an empty string")
>
> if y:
>     print("y is not an empty string")
> ```

> [accordion] \\'%s\\' can be simplified to \\'%s\\', if it is strictly an int, as 0 is falsey
>
> Recommends using the implicit boolean value of integers instead of comparing them directly to zero, streamlining conditionals by taking advantage of the fact that 0 is falsey in Python.
>
> ```python Bad theme={"theme":"css-variables"}
> def important_math(x: int, y: int)  None:
> if x == 0:  # [use-implicit-booleaness-not-comparison-to-zero]
>     print("x is equal to zero")
>
> if y != 0:  # [use-implicit-booleaness-not-comparison-to-zero]
>     print("y is not equal to zero")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def important_math(x: int, y: int)  None:
> if not x:
>     print("x is equal to zero")
>
> if y:
>     print("y is not equal to zero")
> ```

> [accordion] Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty
>
> Advises against using len(SEQUENCE) in conditions to check if a sequence is empty, recommending direct evaluation of the sequence in conditional statements for simplicity and Pythonic style.
>
> ```python Bad theme={"theme":"css-variables"}
> fruits = ["orange", "apple"]
>
> if len(fruits):  # [use-implicit-booleaness-not-len]
> print(fruits)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> fruits = ["orange", "apple"]
>
> if fruits:
> print(fruits)
> ```

> [accordion] Use %s instead
>
> Suggests using the maxsplit argument in string splitting functions to limit the number of splits, improving efficiency and clarity by directly specifying split behavior instead of manual post-split processing.
>
> ```python Bad theme={"theme":"css-variables"}
> url = "www.example.com"
> suffix = url.split(".")[-1]  # [use-maxsplit-arg]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> url = "www.example.com"
> suffix = url.rsplit(".", maxsplit=1)[-1]
> ```

> [accordion] Use a sequence type when iterating over values
>
> Encourages the use of sequence types (like lists or tuples) for iteration, ensuring that the code iterates over a collection of items in a clear and predictable manner, enhancing readability and maintainability.

> [accordion] Import alias does not rename original package
>
> Flags import aliases that do not change the name of the imported module, suggesting the removal of the alias to avoid unnecessary indirection and to use the original module name directly for clarity.
>
> ```python Bad theme={"theme":"css-variables"}
> import pandas as pandas  # [useless-import-alias]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import pandas as pd
> ```

> [accordion] %s should be placed before %s
>
> Highlights incorrect ordering of import statements, recommending adherence to PEP 8 guidelines, which suggest organizing imports in a particular order (standard library, third-party, local) to improve readability and maintainability.
>
> ```python Bad theme={"theme":"css-variables"}
> import os
> from . import utils
> import pylint  # [wrong-import-order]
> import sys  # [wrong-import-order]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import os
> import sys
>
> import pylint
>
> from . import utils
> ```

> [accordion] Import \\'%s\\' should be placed at the top of the module
>
> Warns that an import statement is not placed at the top of the module as recommended by PEP 8, suggesting that all imports should be grouped at the beginning of a file to clarify module dependencies and enhance code organization.
>
> ```python Bad theme={"theme":"css-variables"}
> import os
>
> home = os.environ["HOME"]
>
> import sys  # [wrong-import-position]
>
> print(f"Home directory is {home}", file=sys.stderr)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import os
> import sys
>
> home = os.environ["HOME"]
> print(f"Home directory is {home}", file=sys.stderr)
> ```

> [accordion] Wrong spelling of a word '%s' in a comment:
>
> Indicates a potential spelling error in a comment, underscoring the importance of clear and correctly spelled comments to maintain professionalism and readability in code documentation.
>
> ```python Bad theme={"theme":"css-variables"}
> # There's a mistkae in this string  # [wrong-spelling-in-comment]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> # There's no mistake in this string
> ```

> [accordion] Wrong spelling of a word '%s' in a docstring:
>
> Similar to the above, flags possible spelling mistakes within docstrings, emphasizing the need for accurate and well-written documentation to ensure clarity and usefulness for other developers and users.
>
> ```python Bad theme={"theme":"css-variables"}
> """There's a mistkae in this string"""  # [wrong-spelling-in-docstring]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> """There's no mistake in this string"""
> ```

> [accordion] Blacklisted name used
>
> Flags the use of names that are considered inappropriate or not descriptive, encouraging the use of meaningful identifiers that clearly convey the purpose and function of variables, functions, and classes.

> [accordion] Comparison to empty string
>
> Advises against explicitly comparing strings to empty strings and recommends using the truthiness of strings to check for emptiness, following Pythonic practices for clarity and brevity.

> [accordion] Comparison to zero
>
> Similar to comparing to empty strings, recommends against explicit comparison to zero, suggesting the use of the inherent truthiness or falseness of numbers in conditions for simplicity and readability.

> [accordion] Using len as condition
>
> Warns against using len(SEQUENCE) in conditions to check for emptiness, recommending direct evaluation of the sequence itself, which is more idiomatic and concise in Python.

> [accordion] Missing docstring in public module/function/class
>
> Indicates the absence of a docstring in a public module, function, or class, highlighting the need for documentation to explain the purpose, usage, and behavior of code components for better maintainability and usability.

> [accordion] Misplaced comparison constant in old Python version
>
> Flags the unconventional placement of a comparison constant in conditions within older Python versions, advocating for consistency with modern Python practices for clearer and more intuitive comparisons.

> [accordion] Non-ASCII name in old Python version
>
> Warns about the use of non-ASCII characters in identifiers in older Python versions, suggesting the use of ASCII characters for compatibility and adherence to conventional naming practices.

> [accordion] Unneeded not operator
>
> Indicates the use of an unnecessary not operator in conditions, suggesting simplification of the logic for clarity and to avoid double negatives, which can complicate understanding of the condition's intent.

> [accordion] Simplify chained comparison between the operands
>
> Recommends simplifying chained comparisons between operands to enhance readability and maintain the code's logical flow more straightforwardly, adhering to Python's ability to naturally handle such comparisons.
>
> ```python Bad theme={"theme":"css-variables"}
> a = int(input())
> b = int(input())
> c = int(input())
> if a < b and b < c:  # [chained-comparison]
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> a = int(input())
> b = int(input())
> c = int(input())
> if a < b < c:
> pass
> ```

> [accordion] Comparison between constants: '%s %s %s' has a constant value
>
> Flags the comparison of constants, which results in a constant value, suggesting a review of the logic as such comparisons may indicate redundant or unneeded code that does not impact program flow.
>
> ```python Bad theme={"theme":"css-variables"}
> def is_the_answer()  bool:
> return 42 == 42  # [comparison-of-constants]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def is_the_answer(meaning_of_life: int)  bool:
> return meaning_of_life == 42
> ```

> [accordion] Redundant comparison - %s
>
> Indicates a variable or expression is compared with itself, a redundant operation that always yields a constant result, suggesting a potential logical error or unnecessary code segment.
>
> ```python Bad theme={"theme":"css-variables"}
> def is_an_orange(fruit):
> an_orange = "orange"
> return fruit == fruit  # [comparison-with-itself]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def is_an_orange(fruit):
> an_orange = "orange"
> return an_orange == fruit
> ```

> [accordion] Boolean condition '%s' will always evaluate to '%s'
>
> Warns that a boolean condition always evaluates to the same value (true or false), indicating a potentially redundant or misleading condition that does not contribute to dynamic decision-making in code.
>
> ```python Bad theme={"theme":"css-variables"}
> def is_a_fruit(fruit):
> return bool(fruit in {"apple", "orange"} or True)  # [condition-evals-to-constant]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def is_a_fruit(fruit):
> return fruit in {"apple", "orange"}
> ```

> [accordion] Consecutive elif with same condition
>
> Flags instances where consecutive elif statements in a conditional chain check the same condition, which is redundant and potentially confusing, suggesting consolidation or clarification of the logic to improve readability and maintainability.
>
> ```python Bad theme={"theme":"css-variables"}
> def myfunc(shall_continue: bool, shall_exit: bool):
> if shall_continue:
>     if input("Are you sure?") == "y":
>         print("Moving on.")
> elif shall_exit:  # [confusing-consecutive-elif]
>     print("Exiting.")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> # Option 1: add explicit 'else'
> def myfunc(shall_continue: bool, shall_exit: bool):
> if shall_continue:
>     if input("Are you sure?") == "y":
>         print("Moving on.")
>     else:
>         pass
> elif shall_exit:
>     print("Exiting.")
>
>
> # Option 2: extract function
> def user_confirmation():
> if input("Are you sure?") == "y":
>     print("Moving on.")
>
>
> def myfunc2(shall_continue: bool, shall_exit: bool):
> if shall_continue:
>     user_confirmation()
> elif shall_exit:
>     print("Exiting.")
> ```

> [accordion] Consider alternative union syntax
>
> In Python 3.10 and later, suggests using the new union syntax (X | Y) instead of typing.Union\[X, Y], enhancing readability and conciseness of type annotations by leveraging the latest language features.
>
> ```python Bad theme={"theme":"css-variables"}
> from typing import Union
>
> cats: Union[int, str]  # [consider-alternative-union-syntax]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> cats: int | str
> ```

> [accordion] Consider merging these isinstance calls to isinstance(%s, (%s))
>
> Recommends combining multiple isinstance() checks into a single call with a tuple of types, simplifying the code and improving performance by reducing the number of function calls.
>
> ```python Bad theme={"theme":"css-variables"}
> from typing import Any
>
>
> def is_number(value: Any)  bool:
> # +1: [consider-merging-isinstance]
> return isinstance(value, int) or isinstance(value, float)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from typing import Any
>
>
> def is_number(value: Any)  bool:
> return isinstance(value, (int, float))
> ```

> [accordion] Consider refactoring into while condition
>
> Suggests refactoring a loop that contains a conditional break statement at its beginning into a while loop with the condition, improving clarity by directly incorporating the loop's termination condition into its structure.
>
> ```python Bad theme={"theme":"css-variables"}
> fruit_basket = ["apple", "orange", "banana", "cherry", "guava"]
>
> while True:  # [consider-refactoring-into-while-condition]
> if len(fruit_basket) == 0:
>     break
> fruit = fruit_basket.pop()
> print(f"We removed {fruit} from the basket")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> fruit_basket = ["apple", "orange", "banana", "cherry", "guava"]
>
> while len(fruit_basket) != 0:
> fruit = fruit_basket.pop()
> print(f"We removed {fruit} from the basket")
> ```

> [accordion] Consider using tuple unpacking for swapping variables
>
> Advises using tuple unpacking for swapping the values of two variables, a more Pythonic and clearer approach than using a temporary variable, demonstrating Python's elegant syntax for common operations.
>
> ```python Bad theme={"theme":"css-variables"}
> a = 1
> b = 2
>
> temp = a  # [consider-swap-variables]
> a = b
> b = temp
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> a = 1
> b = 2
>
> a, b = b, a
> ```

> [accordion] Consider using alias
>
> Suggests using a more commonly accepted alias for a module or object to improve readability and consistency with community standards or conventions, enhancing code understandability.
>
> ```python Bad theme={"theme":"css-variables"}
> import typing
>
> cats: typing.Dict[str, int]  # [consider-using-alias]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import typing
>
> cats: typing.cast(dict[str, int], "string")
> ```

> [accordion] Consider using assignment expression
>
> Recommends using the assignment expression (:=) introduced in Python 3.8 for assignments within expressions, which can make the code more concise and reduce repetition by capturing a condition's result inline.
>
> ```python Bad theme={"theme":"css-variables"}
> apples = 2
>
> if apples:  # [consider-using-assignment-expr]
> print("God apples!")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> if apples := 2:
> print("God apples!")
> ```

> [accordion] Consider using augmented assignment
>
> Advises using augmented assignment operators (+=, -=, \*=, etc.) when possible, simplifying expressions and potentially improving performance by modifying variables in place where applicable.
>
> ```python Bad theme={"theme":"css-variables"}
> x = 1
> x = x + 1  # [consider-using-augmented-assign]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = 1
> x += 1
> ```

# step 6

> [accordion] Consider using a dictionary comprehension
>
> Recommends using dictionary comprehensions for constructing dictionaries from iterables, a concise and readable approach that leverages Python's expressive syntax for collections.
>
> ```python Bad theme={"theme":"css-variables"}
> NUMBERS = [1, 2, 3]
>
> # +1: [consider-using-dict-comprehension]
> DOUBLED_NUMBERS = dict([(number, number * 2) for number in NUMBERS])
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> NUMBERS = [1, 2, 3]
>
> DOUBLED_NUMBERS = {number: number * 2 for number in NUMBERS}
> ```

> [accordion] Use 'from %s import %s' instead
>
> Suggests using direct imports (from module import symbol) instead of importing the entire module, which can make the code clearer by specifying exactly which symbols are needed from a module.
>
> ```python Bad theme={"theme":"css-variables"}
> import os.path as path  # [consider-using-from-import]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from os import path
> ```

> [accordion] Consider using a generator instead '%s(%s)'
>
> Recommends using a generator expression instead of a list comprehension or similar construct when the resulting list is only iterated over, improving memory efficiency by generating items on the fly.
>
> ```python Bad theme={"theme":"css-variables"}
> list([0 for y in list(range(10))])  # [consider-using-generator]
> tuple([0 for y in list(range(10))])  # [consider-using-generator]
> sum([y**2 for y in list(range(10))])  # [consider-using-generator]
> max([y**2 for y in list(range(10))])  # [consider-using-generator]
> min([y**2 for y in list(range(10))])  # [consider-using-generator]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> list(0 for y in list(range(10)))
> tuple(0 for y in list(range(10)))
> sum(y**2 for y in list(range(10)))
> max(y**2 for y in list(range(10)))
> min(y**2 for y in list(range(10)))
> ```

> [accordion] Consider using dict.get for getting values from a dict if a key is present or a default if not
>
> Advises using the get method of dictionaries to retrieve values, providing a way to specify a default value if the key is not found, simplifying code and avoiding KeyError exceptions.
>
> ```python Bad theme={"theme":"css-variables"}
> knights = {"Gallahad": "the pure", "Robin": "the brave"}
>
> if "Gallahad" in knights:  # [consider-using-get]
> DESCRIPTION = knights["Gallahad"]
> else:
> DESCRIPTION = ""
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> knights = {"Gallahad": "the pure", "Robin": "the brave"}
>
> description = knights.get("Gallahad", "")
> ```

> [accordion] Consider merging these comparisons with 'in' by using '%s %sin (%s)'. Use a set instead if elements are hashable.
>
> Suggests simplifying multiple comparison operations with a sequence of values by using the in operator, enhancing code readability and conciseness, especially when the sequence elements are hashable and a set can be used for efficiency..
>
> ```python Bad theme={"theme":"css-variables"}
> def fruit_is_round(fruit):
> # +1: [consider-using-in]
> return fruit == "apple" or fruit == "orange" or fruit == "melon"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def fruit_is_round(fruit):
> return fruit in {"apple", "orange", "melon"}
> ```

> [accordion] Consider using str.join(sequence) for concatenating strings from an iterable
>
> Recommends using str.join(sequence) for concatenating strings from an iterable, which is more efficient and idiomatic than concatenating strings in a loop, especially for larger sequences or when building output from multiple strings.
>
> ```python Bad theme={"theme":"css-variables"}
> def fruits_to_string(fruits):
> formatted_fruit = ""
> for fruit in fruits:
>     formatted_fruit += fruit  # [consider-using-join]
> return formatted_fruit
>
>
> print(fruits_to_string(["apple", "pear", "peach"]))
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print("".join(["apple", "pear", "peach"]))
> ```

> [accordion] Consider using '%s' instead of unnecessary if block
>
> Recommends using the 'max' builtin function for obtaining the maximum value instead of using an if-else block, simplifying the code and leveraging Python's built-in functions for cleaner and more efficient expressions.
>
> ```python Bad theme={"theme":"css-variables"}
> def get_max(value1, value2):
> if value1 < value2:  # [consider-using-max-builtin]
>     value1 = value2
> return value1
>
>
> print(get_max(1, 2))
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print(max(1, 2))
> ```

> [accordion] Consider using '%s' instead of unnecessary if block
>
> Similar to the above, suggests using the 'min' builtin function to find the minimum value rather than an if-else block, improving code readability and efficiency by utilizing Python's concise and expressive built-in capabilities.
>
> ```python Bad theme={"theme":"css-variables"}
> def get_min(value1, value2):
> if value1 > value2:  # [consider-using-min-builtin]
>     value1 = value2
> return value1
>
>
> print(get_min(1, 2))
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print(min(1, 2))
> ```

> [accordion] Consider using namedtuple or dataclass
>
> Advises the use of namedtuple or dataclass for collections of data that require more structure and readability than a simple tuple or dictionary, enhancing code readability and maintainability with minimal boilerplate.
>
> ```python Bad theme={"theme":"css-variables"}
> FELIDAES = {  # [consider-using-namedtuple-or-dataclass]
> "The queen's cymric, fragile furry friend": {
>     "tail_length_cm": 1,
>     "paws": 4,
>     "eyes": 2,
>     "Elizabethan collar": 1,
> },
> "Rackat the red, terror of the sea": {
>     "tail_length_cm": 13,
>     "paws": 3,
>     "eyes": 1,
>     "Red Hat": 1,
> },
> }
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from typing import NamedTuple
>
>
> class FelidaeCharacteristics(NamedTuple):
> tail_length_cm: int
> paws: int
> eyes: int
> hat: str | None
>
>
> FELIDAES = {
> "The queen's cymric, fragile furry friend": FelidaeCharacteristics(
>     tail_length_cm=1, paws=4, eyes=2, hat="Elizabethan collar"
> ),
> "Rackat the red, terror of the sea": FelidaeCharacteristics(
>     tail_length_cm=21, paws=3, eyes=1, hat="Red Hat"
> ),
> }
> ```

> [accordion] Consider using a set comprehension
>
> Recommends using set comprehensions for creating sets from iterables, a concise and expressive feature that improves code readability and succinctness while leveraging Python's powerful comprehension syntax.
>
> ```python Bad theme={"theme":"css-variables"}
> NUMBERS = [1, 2, 2, 3, 4, 4]
>
> # +1: [consider-using-set-comprehension]
> UNIQUE_EVEN_NUMBERS = set([number for number in NUMBERS if number % 2 == 0])
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> NUMBERS = [1, 2, 2, 3, 4, 4]
>
> UNIQUE_EVEN_NUMBERS = {number for number in NUMBERS if number % 2 == 0}
> ```

> [accordion] Consider using 'sys.exit' instead
>
> Suggests using 'sys.exit' to exit a script when needed, providing a clear and explicit exit point that can convey exit status information to the operating system, enhancing script robustness and control flow clarity.
>
> ```python Bad theme={"theme":"css-variables"}
> if __name__ == "__main__":
> user = input("Enter user name: ")
> print(f"Hello, {user}")
> exit(0)  # [consider-using-sys-exit]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import sys
>
> if __name__ == "__main__":
> user = input("Enter user name: ")
> print(f"Hello, {user}")
> sys.exit(0)
> ```

> [accordion] Consider using ternary (%s)
>
> Encourages the use of ternary operators for concise conditional assignments or return statements, improving code compactness and readability by reducing the need for more verbose if-else structures.
>
> ```python Bad theme={"theme":"css-variables"}
> x, y = 1, 2
> maximum = x >= y and x or y  # [consider-using-ternary]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x, y = 1, 2
> maximum = x if x >= y else y
> ```

> [accordion] Consider using tuple
>
> Recommends using tuples for fixed collections of items, highlighting tuples' immutability and potential performance benefits for use cases where the collection's size and content will not change.
>
> ```python Bad theme={"theme":"css-variables"}
> for i in [1, 2, 3]:  # [consider-using-tuple]
> print(i)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> for i in (1, 2, 3):
> print(i)
> ```

> [accordion] Consider using 'with' for resource-allocating operations
>
> Advises the use of the 'with' statement for managing resource allocation and deallocation, especially for file operations or similar resource-intensive processes, to ensure resources are properly managed and released, reducing the risk of leaks.

> [accordion] Cyclic import (%s)
>
> Flags instances of cyclic imports, where two or more modules import each other directly or indirectly, potentially leading to import errors or unexpected behavior, suggesting reorganization to eliminate the cyclic dependency.

> [accordion] Similar lines in %s files
>
> Warns about similar code blocks across different files, suggesting potential for refactoring into shared functions or modules to reduce redundancy and improve maintainability by adhering to the DRY (Don't Repeat Yourself) principle.

> [accordion] Else if used instead of elif
>
> Highlights an else block immediately followed by an if statement, suggesting the use of elif for clarity and to consolidate conditional branches into a more readable and concise structure.
>
> ```python Bad theme={"theme":"css-variables"}
> if input():
> pass
> else:
> if len(input()) >= 10:  # [else-if-used]
>     pass
> else:
>     pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> if input():
> pass
> elif len(input()) >= 10:
> pass
> else:
> pass
> ```

> [accordion] Empty comment detected
>
> Flags comments that contain no text, which can clutter the code without providing value, suggesting removal or addition of meaningful commentary to improve code documentation and readability.
>
> ```python Bad theme={"theme":"css-variables"}
> # +1:[empty-comment]
> #
>
> # +1:[empty-comment]
> x = 0  #
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> # comment
>
> x = 0  # comment
> ```

> [accordion] Either all return statements in a function should return an expression, or none of them should.
>
> Indicates a function where some return statements return a value while others do not, leading to potential confusion about the function's expected behavior and return type, recommending consistency across return statements.
>
> ```python Bad theme={"theme":"css-variables"}
> def get_the_answer(value: str)  str | None:  # [inconsistent-return-statements]
> if value:
>     return value
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def get_the_answer(value: str)  str | None:
> if value:
>     return value
> return None
> ```

> [accordion] In '%s', use '%s' when comparing constant literals not '%s' ('%s')
>
> Advises against comparing literals in a manner that could be simplified or made more direct, enhancing code clarity and efficiency by using straightforward comparisons, especially for boolean or None checks.
>
> ```python Bad theme={"theme":"css-variables"}
> def is_an_orange(fruit):
> return fruit is "orange"  # [literal-comparison]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def is_an_orange(fruit):
> return fruit == "orange"
> ```

> [accordion] Magic value comparison
>
> Flags comparisons against 'magic' values, which are hard-coded numbers or strings that may not have clear meaning. Refactoring to use named constants instead of magic values improves code readability, maintainability, and reduces the risk of errors by providing context for these values.
>
> ```python Bad theme={"theme":"css-variables"}
> import random
>
> measurement = random.randint(0, 200)
> above_threshold = False
> i = 0
> while i < 5:  # [magic-value-comparison]
> above_threshold = measurement > 100  # [magic-value-comparison]
> if above_threshold:
>     break
> measurement = random.randint(0, 200)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import random
>
> MAX_NUM_OF_ITERATIONS = 5
> THRESHOLD_VAL = 100
> MIN_MEASUREMENT_VAL = 0
> MAX_MEASUREMENT_VAL = 200
>
> measurement = random.randint(MIN_MEASUREMENT_VAL, MAX_MEASUREMENT_VAL)
> above_threshold = False
> i = 0
> while i < MAX_NUM_OF_ITERATIONS:
> above_threshold = measurement > THRESHOLD_VAL
> if above_threshold:
>     break
> measurement = random.randint(MIN_MEASUREMENT_VAL, MAX_MEASUREMENT_VAL)
> ```

> [accordion] Consider using a decorator instead of calling classmethod
>
> Indicates the manual conversion of a method to a class method using the classmethod() function instead of the @classmethod decorator. Using the decorator enhances readability, clearly signaling the method's intended usage at a glance and adhering to Pythonic conventions.
>
> ```python Bad theme={"theme":"css-variables"}
> class Fruit:
> COLORS = []
>
> def __init__(self, color):
>     self.color = color
>
> def pick_colors(cls, *args):
>     """classmethod to pick fruit colors"""
>     cls.COLORS = args
>
> pick_colors = classmethod(pick_colors)  # [no-classmethod-decorator]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Fruit:
> COLORS = []
>
> def __init__(self, color):
>     self.color = color
>
> @classmethod
> def pick_colors(cls, *args):
>     """classmethod to pick fruit colors"""
>     cls.COLORS = args
> ```

> [accordion] Unnecessary \\'%s\\' after \\'break\\', %s
>
> Highlights unnecessary 'else' blocks following a 'break' in loops. Removing these 'else' blocks simplifies the control flow, making the code easier to read and understand by reducing unnecessary nesting and highlighting the primary path through the code.
>
> ```python Bad theme={"theme":"css-variables"}
> def next_seven_elements(iterator):
> for i, item in enumerate(iterator):
>     if i == 7:  # [no-else-break]
>         break
>     else:
>         yield item
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def next_seven_elements(iterator):
> for i, item in enumerate(iterator):
>     if i == 7:
>         break
>     yield item
> ```

> [accordion] Unnecessary \\'%s\\' after \\'continue\\', %s
>
> Flags redundant 'else' blocks after a 'continue' statement in loops. Since 'continue' already skips to the next iteration, the 'else' is superfluous and removing it can streamline the loop structure, enhancing code clarity.
>
> ```python Bad theme={"theme":"css-variables"}
> def even_number_under(n: int):
> for i in range(n):
>     if i % 2 == 1:  # [no-else-continue]
>         continue
>     else:
>         yield i
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def even_number_under(n: int):
> for i in range(n):
>     if i % 2 == 1:
>         continue
>     yield i
> ```

> [accordion] Unnecessary \\'%s\\' after \\'raise\\', %s
>
> Points out unnecessary 'else' blocks that follow a 'raise' statement. Since 'raise' exits the block, the 'else' is not needed. Simplifying by removing these blocks can make exception-raising logic clearer and more direct.
>
> ```python Bad theme={"theme":"css-variables"}
> def integer_sum(a: int, b: int)  int:
> if not (isinstance(a, int) and isinstance(b, int)):  # [no-else-raise]
>     raise ValueError("Function supports only integer parameters.")
> else:
>     return a + b
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def integer_sum(a: int, b: int)  int:
> if not (isinstance(a, int) and isinstance(b, int)):
>     raise ValueError("Function supports only integer parameters.")
> return a + b
> ```

> [accordion] Unnecessary \\'%s\\' after \\'return\\', %s
>
> Warns against 'else' blocks that come after a 'return' statement in functions. Since 'return' exits the function, the 'else' serves no purpose and removing it can make the function's return logic simpler and more readable.
>
> ```python Bad theme={"theme":"css-variables"}
> def compare_numbers(a: int, b: int)  int:
> if a == b:  # [no-else-return]
>     return 0
> elif a < b:
>     return -1
> else:
>     return 1
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def compare_numbers(a: int, b: int)  int:
> if a == b:
>     return 0
> if a < b:
>     return -1
> return 1
> ```

> [accordion] Method could be a function (no self-use)
>
> Identifies instance methods that do not use the instance (self), suggesting they could be static methods. Converting these methods improves code organization by correctly categorizing methods that don't rely on instance state, potentially leading to better performance and reduced memory usage.

> [accordion] Consider using a decorator instead of calling staticmethod
>
> Similar to the classmethod decorator issue, this rule indicates the use of the staticmethod() function instead of the @staticmethod decorator. Using the decorator is more Pythonic and improves the readability by clearly indicating the method's static nature.
>
> ```python Bad theme={"theme":"css-variables"}
> class Worm:
> def bore(self):
>     pass
>
> bore = staticmethod(bore)  # [no-staticmethod-decorator]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Worm:
> @staticmethod
> def bore(self):
>     pass
> ```

> [accordion] Prefer typing.NamedTuple
>
> Suggests using typing.NamedTuple for more readable, maintainable, and concise type annotations. This approach leverages the type hinting system in Python, making code more self-documenting and type checks more powerful.
>
> ```python Bad theme={"theme":"css-variables"}
> from collections import namedtuple
>
> Philosophy = namedtuple(  # [prefer-typing-namedtuple]
> "Philosophy", ("goodness", "truth", "beauty")
> )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from typing import NamedTuple
>
>
> class Philosophy(NamedTuple):
> goodness: str
> truth: bool
> beauty: float
> ```

> [accordion] Cannot have defined parameters for properties
>
> Flags the attempt to define properties with parameters, which is not supported. Properties should be simple and parameter-free to maintain the clarity of the API and ensure they are used correctly.
>
> ```python Bad theme={"theme":"css-variables"}
> class Worm:
> @property
> def bore(self, depth):  # [property-with-parameters]
>     pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Worm:
> @property
> def bore(self):
>     """Property accessed with '.bore'."""
>     pass
>
> def bore_with_depth(depth):
>     """Function called with .bore_with_depth(depth)."""
>     pass
> ```

> [accordion] Redefining argument with the local name %r
>
> Indicates that a function argument is redefined within the function's body, which can lead to confusion and errors. Keeping argument names unique within a function's scope enhances clarity and prevents unintended shadowing.
>
> ```python Bad theme={"theme":"css-variables"}
> def show(host_id=10.11):
> # +1: [redefined-argument-from-local]
> for host_id, host in [[12.13, "Venus"], [14.15, "Mars"]]:
>     print(host_id, host)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> 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)
> ```

> [accordion] Redefined variable type
>
> Warns about changing the type of a variable within the same scope, which can lead to confusion and bugs. Maintaining consistent variable types aids readability and predictability.
>
> ```python Bad theme={"theme":"css-variables"}
> x = 1
> x = "2"  # [redefined-variable-type]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = 1
> x = 2
> ```

> [accordion] Redundant type hint for argument
>
> Highlights type hints that are unnecessary or redundant, suggesting simplification. Removing redundant type hints keeps the codebase clean and focused on meaningful annotations, enhancing readability.
>
> ```python Bad theme={"theme":"css-variables"}
> from typing import Union
>
> sweet_count: Union[int, str, int] = 42  # [redundant-typehint-argument]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from typing import Union
>
> sweet_count: Union[str, int] = 42
> ```

> [accordion] Boolean condition \\'%s\\' may be simplified to \\'%s\\'
>
> Flags complex boolean conditions that can be simplified, recommending more concise expressions. Simplifying conditions improves readability, making the code easier to follow and potentially enhancing performance by reducing complexity.
>
> ```python Bad theme={"theme":"css-variables"}
> def has_apples(apples)  bool:
> return bool(apples or False)  # [simplifiable-condition]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def has_apples(apples)  bool:
> return bool(apples)
> ```

> [accordion] The if expression can be replaced with %s
>
> Identifies 'if' expressions that can be simplified, enhancing code readability and maintainability by reducing unnecessary complexity and making the code more concise.
>
> ```python Bad theme={"theme":"css-variables"}
> FLYING_THINGS = ["bird", "plane", "superman", "this example"]
>
>
> def is_flying_thing(an_object):
> return True if an_object in FLYING_THINGS else False  # [simplifiable-if-expression]
>
>
> def is_not_flying_thing(an_object):
> return False if an_object in FLYING_THINGS else True  # [simplifiable-if-expression]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> FLYING_THINGS = ["bird", "plane", "superman", "this example"]
>
>
> def is_flying_thing(an_object):
> return an_object in FLYING_THINGS
>
>
> def is_not_flying_thing(an_object):
> return an_object not in FLYING_THINGS
> ```

> [accordion] The if statement can be replaced with %s
>
> Flags 'if' statements that can be streamlined into more concise expressions, improving readability and efficiency by eliminating redundant logic structures.
>
> ```python Bad theme={"theme":"css-variables"}
> FLYING_THINGS = ["bird", "plane", "superman", "this example"]
>
>
> def is_flying_animal(an_object):
> # +1: [simplifiable-if-statement]
> if isinstance(an_object, Animal) and an_object in FLYING_THINGS:
>     is_flying = True
> else:
>     is_flying = False
> return is_flying
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> FLYING_THINGS = ["bird", "plane", "superman", "this example"]
>
>
> def is_flying_animal(an_object):
> is_flying = isinstance(an_object, Animal) and an_object.name in FLYING_THINGS
> return is_flying
> ```

> [accordion] Boolean expression may be simplified to %s
>
> Points out complex boolean expressions that can be simplified, making the code easier to understand and maintain by clarifying logical operations and conditions.
>
> ```python Bad theme={"theme":"css-variables"}
> def has_oranges(oranges, apples=None)  bool:
> return apples and False or oranges  # [simplify-boolean-expression]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def has_oranges(oranges, apples=None)  bool:
> return oranges
> ```

> [accordion] Do not raise StopIteration in generator, use return statement instead
>
> Advises against raising StopIteration in a generator, recommending a return statement instead. This change enhances clarity and conforms to best practices in Python 3, preventing potential runtime errors.

> [accordion] Consider using Python 3 style super() without arguments
>
> Suggests using the argument-less super() call available in Python 3, which simplifies inheritance by automatically determining the context, improving code readability and reducing boilerplate.
>
> ```python Bad theme={"theme":"css-variables"}
> class Fruit:
> pass
>
>
> class Orange(Fruit):
> def __init__(self):
>     super(Orange, self).__init__()  # [super-with-arguments]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Fruit:
> pass
>
>
> class Orange(Fruit):
> def __init__(self):
>     super().__init__()
> ```

> [accordion] Code too complex
>
> Indicates code with high complexity, suggesting refactoring to simplify logic and improve maintainability. Simplifying complex code can enhance readability, make it easier to test, and reduce the likelihood of bugs.
>
> ```python Bad theme={"theme":"css-variables"}
> def fifty_percent_off(whole):
> return (float(whole)) * 50 / 100
>
>
> def calculate_sum_and_display_price_of_fruits(*fruits):  # [too-complex]
> # McCabe rating is 13 here (by default 10)
> shopping_list = []
>
> if "apple" in fruits:
>     v = fifty_percent_off(1.1)
>     shopping_list.append(v)
> if "pear" in fruits:
>     shopping_list.append(0.8)
> if "banana" in fruits:
>     shopping_list.append(1.2)
> if "mango" in fruits:
>     shopping_list.append(3.5)
> if "peach" in fruits:
>     shopping_list.append(0.5)
> if "melon" in fruits:
>     shopping_list.append(4.9)
> if "orange" in fruits:
>     shopping_list.append(2.0)
> if "strawberry" in fruits:
>     shopping_list.append(2.5)
> if "mandarin" in fruits:
>     shopping_list.append(2.3)
> if "plum" in fruits:
>     shopping_list.append(0.5)
> if "watermelon" in fruits:
>     v = fifty_percent_off(6.4)
>     shopping_list.append(v)
>
> combine = zip(fruits, shopping_list)
>
> for i in combine:
>     print(f"{i[0]} ${i[1]:.2f}")
>
> total = sum(shopping_list)
> print(f"Total price is ${total:.2f}")
>
>
> fruits_to_buy = ["apple", "orange", "watermelon"]
> calculate_sum_and_display_price_of_fruits(*fruits_to_buy)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> FRUIT_PRICES = {
> "apple": 1.1,
> "pear": 0.8,
> "banana": 1.2,
> "mango": 3.5,
> "peach": 0.5,
> "melon": 4.9,
> "orange": 2.0,
> "strawberry": 2.5,
> "mandarin": 2.3,
> "plum": 0.5,
> "watermelon": 6.4,
> }
> DISCOUNTED_FRUITS = ["apple", "watermelon"]
>
>
> def fifty_percent_off(whole):
> return (float(whole)) * 50 / 100
>
>
> def get_price(fruit):
> full_price = FRUIT_PRICES.get(fruit)
> if fruit in DISCOUNTED_FRUITS:
>     return fifty_percent_off(full_price)
> else:
>     return full_price
>
>
> def display_fruit_and_price(fruits):
> for fruit in fruits:
>     print(f"{fruit} ${get_price(fruit) :.2f}")
>
>
> def get_total(fruits):
> return sum(get_price(f) for f in fruits)
>
>
> fruits_to_buy = ["apple", "orange", "watermelon"]
> display_fruit_and_price(fruits_to_buy)
> print(f"Total price is ${get_total(fruits_to_buy):.2f}")
> ```

> [accordion] Too few public methods (%s/%s)
>
> Flags classes with fewer public methods than a defined threshold, questioning the class's utility or suggesting its potential reimplementation as a function or aggregation into another class.

> [accordion] Too many ancestors (%s/%s)
>
> Warns about classes that inherit from too many parent classes, complicating the inheritance hierarchy. Simplifying these relationships can improve code readability and object model clarity.
>
> ```python Bad theme={"theme":"css-variables"}
> class Animal: ...
> class BeakyAnimal(Animal): ...
> class FurryAnimal(Animal): ...
> class Swimmer(Animal): ...
> class EggLayer(Animal): ...
> class VenomousAnimal(Animal): ...
> class ProtectedSpecie(Animal): ...
> class BeaverTailedAnimal(Animal): ...
> class Vertebrate(Animal): ...
>
>
> # max of 7 by default, can be configured
> # each edge of a diamond inheritance counts
> class Playtypus(  # [too-many-ancestors]
> BeakyAnimal,
> FurryAnimal,
> Swimmer,
> EggLayer,
> VenomousAnimal,
> ProtectedSpecie,
> BeaverTailedAnimal,
> Vertebrate,
> ):
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Animal:
> beaver_tailed: bool
> can_swim: bool
> has_beak: bool
> has_fur: bool
> has_vertebrae: bool
> lays_egg: bool
> protected_specie: bool
> venomous: bool
>
>
> class Invertebrate(Animal):
> has_vertebrae = False
>
>
> class Vertebrate(Animal):
> has_vertebrae = True
>
>
> class Mammal(Vertebrate):
> has_beak = False
> has_fur = True
> lays_egg = False
> venomous = False
>
>
> class Playtypus(Mammal):
> beaver_tailed = True
> can_swim = True
> has_beak = True
> lays_egg = False
> protected_specie = True
> venomous = True
> ```

> [accordion] Too many arguments (%s/%s)
>
> Highlights functions or methods with more arguments than recommended, suggesting refactoring to reduce parameter count, which can enhance readability and usability.
>
> ```python Bad theme={"theme":"css-variables"}
> def three_d_chess_move(  # [too-many-arguments]
> x_white,
> y_white,
> z_white,
> piece_white,
> x_black,
> y_black,
> z_black,
> piece_black,
> x_blue,
> y_blue,
> z_blue,
> piece_blue,
> current_player,
> ):
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from dataclasses import dataclass
>
>
> @dataclass
> class ThreeDChessPiece:
> x: int
> y: int
> z: int
> type: str
>
>
> def three_d_chess_move(
> white: ThreeDChessPiece,
> black: ThreeDChessPiece,
> blue: ThreeDChessPiece,
> current_player,
> ):
> pass
> ```

> [accordion] Too many boolean expressions in if statement (%s/%s)
>
> Flags 'if' statements containing more boolean expressions than recommended, suggesting simplification to improve logic clarity and reduce cognitive load.
>
> ```python Bad theme={"theme":"css-variables"}
> def can_be_divided_by_two_and_are_not_zero(x, y, z):
> # Maximum number of boolean expressions in an if statement (by default 5)
> # +1: [too-many-boolean-expressions]
> if (x and y and z) and (x % 2 == 0 and y % 2 == 0 and z % 2 == 0):
>     pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def can_be_divided_by_two_and_are_not_zero(x, y, z):
> if all(i and i % 2 == 0 for i in [x, y, z]):
>     pass
> ```

> [accordion] Too many branches (%s/%s)
>
> Points out functions with too many conditional branches, recommending refactoring to simplify control flow and enhance the function's readability and maintainability.
>
> ```python Bad theme={"theme":"css-variables"}
> def num_to_word(x):  # [too-many-branches]
> if x == 0:
>     return "zero"
> elif x == 1:
>     return "one"
> elif x == 2:
>     return "two"
> elif x == 3:
>     return "three"
> elif x == 4:
>     return "four"
> elif x == 5:
>     return "five"
> elif x == 6:
>     return "six"
> elif x == 7:
>     return "seven"
> elif x == 8:
>     return "eight"
> elif x == 9:
>     return "nine"
> else:
>     return None
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def num_to_word(x):
> return {
>     0: "zero",
>     1: "one",
>     2: "two",
>     3: "three",
>     4: "for",
>     5: "fie",
>     6: "six",
>     7: "seven",
>     8: "eight",
>     9: "nine",
> }.get(x)
> ```

> [accordion] Too many instance attributes (%s/%s)
>
> Indicates classes with more instance attributes than recommended, suggesting potential for simplifying class design by reevaluating the class's responsibilities and structure.
>
> ```python Bad theme={"theme":"css-variables"}
> class Fruit:  # [too-many-instance-attributes]
> def __init__(self):
>     # max of 7 attributes by default, can be configured
>     self.worm_name = "Jimmy"
>     self.worm_type = "Codling Moths"
>     self.worm_color = "light brown"
>     self.fruit_name = "Little Apple"
>     self.fruit_color = "Bright red"
>     self.fruit_vitamins = ["A", "B1"]
>     self.fruit_antioxidants = None
>     self.secondary_worm_name = "Kim"
>     self.secondary_worm_type = "Apple maggot"
>     self.secondary_worm_color = "Whitish"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import dataclasses
>
>
> @dataclasses.dataclass
> class Worm:
> name: str
> type: str
> color: str
>
>
> class Fruit:
> def __init__(self):
>     self.name = "Little Apple"
>     self.color = "Bright red"
>     self.vitamins = ["A", "B1"]
>     self.antioxidants = None
>     self.worms = [
>         Worm(name="Jimmy", type="Codling Moths", color="light brown"),
>         Worm(name="Kim", type="Apple maggot", color="Whitish"),
>     ]
> ```

> [accordion] Too many local variables (%s/%s)
>
> Flags functions with a high number of local variables, recommending refactoring to reduce complexity, potentially by splitting the function into smaller, more focused functions.
>
> ```python Bad theme={"theme":"css-variables"}
> from childhood import Child, Sweet
>
>
> def handle_sweets(infos):  # [too-many-locals]
> # Create children
> children = [Child(info) for info in infos]
> number_of_sweets = 87
> sweets = [Sweet() * number_of_sweets]
> number_of_sweet_per_child = 5
> money = 45.0
> sweets_given = 0
> time_to_eat_sweet = 54
> price_of_sweet = 0.42
> # distribute sweet
> for child in children:
>     sweets_given += number_of_sweet_per_child
>     child.give(sweets[number_of_sweet_per_child:])
> # calculate prices
> cost_of_children = sweets_given * price_of_sweet
> # Calculate remaining money
> remaining_money = money - cost_of_children
> # Calculate time it took
> time_it_took_assuming_parallel_eating = (
>     time_to_eat_sweet * number_of_sweet_per_child
> )
> print(
>     f"{children} ate {cost_of_children}¤ of sweets in {time_it_took_assuming_parallel_eating}, "
>     f"you still have {remaining_money}"
> )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from typing import NamedTuple
>
> from childhood import Child, Sweet
>
>
> class SweetDistrubutionCharacteristics(NamedTuple):
> number_of_sweets: int
> number_of_sweet_per_child: int
> number_of_children: int
>
> @property
> def sweets_given(self):
>     return self.number_of_sweet_per_child * self.number_of_children
>
>
> def handle_sweets(infos):
> children = [Child(info) for info in infos]
> characteristics = SweetDistrubutionCharacteristics(87, 5, len(children))
> _allocate_sweets_to_children(children, characteristics)
> financial_impact = _assess_financial_impact(characteristics)
> print(f"{children} ate {financial_impact}")
>
>
> def _allocate_sweets_to_children(
> children, characteristics: SweetDistrubutionCharacteristics
> )  None:
> sweets = [Sweet() * characteristics.number_of_sweets]
> for child in children:
>     child.give(sweets[characteristics.number_of_sweet_per_child :])
>
>
> def _assess_financial_impact(characteristics: SweetDistrubutionCharacteristics)  str:
> time_to_eat_sweet = 54
> money = 45.0
> price_of_sweet = 0.42
> cost_of_children = characteristics.sweets_given * price_of_sweet
> remaining_money = money - cost_of_children
> time_it_took_assuming_parallel_eating = (
>     time_to_eat_sweet * characteristics.number_of_sweet_per_child
> )
> return (
>     f"{cost_of_children}¤ of sweets in "
>     f"{time_it_took_assuming_parallel_eating}, you still have {remaining_money}"
> )
> ```

> [accordion] Too many nested blocks (%s/%s)
>
> Warns about excessive nesting in code blocks, which can make code difficult to follow. Flattening these structures can enhance readability and simplify logic.
>
> ```python Bad theme={"theme":"css-variables"}
> def correct_fruits(fruits):
> if len(fruits) > 1:  # [too-many-nested-blocks]
>     if "apple" in fruits:
>         if "orange" in fruits:
>             count = fruits["orange"]
>             if count % 2:
>                 if "kiwi" in fruits:
>                     if count == 2:
>                         return True
> return False
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def correct_fruits(fruits):
> if len(fruits) > 1 and "apple" in fruits and "orange" in fruits:
>     count = fruits["orange"]
>     if count % 2 and "kiwi" in fruits and count == 2:
>         return True
> return False
> ```

> [accordion] Too many public methods (%s/%s)
>
> Indicates classes with more public methods than recommended, suggesting a review of the class's design for potential simplification by splitting responsibilities.
>
> ```python Bad theme={"theme":"css-variables"}
> class SpaceInvaders:  # [too-many-public-methods]
> def __init__(self):
>     pass
>
> def fire_laser_beam(self):
>     pass
>
> def deploy_shield(self):
>     pass
>
> def launch_missile(self):
>     pass
>
> def activate_super_laser(self):
>     pass
>
> def summon_mothership(self):
>     pass
>
> def destroy_planet(self):
>     pass
>
> def teleport(self):
>     pass
>
> def invoke_aliens(self):
>     pass
>
> def invade_earth(self):
>     pass
>
> def takeover_galaxy(self):
>     pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class LaserBeam:
> def __init__(self):
>     pass
>
> def fire(self):
>     pass
>
> def activate_super(self):
>     pass
>
> def destroy_planet(self):
>     pass
>
>
> class Shield:
> def deploy(self):
>     pass
>
>
> class Missile:
> def launch(self):
>     pass
>
>
> class SpaceInvaders:
> def __init__(self):
>     self.laser = LaserBeam()
>     self.shield = Shield()
>     self.missile = Missile()
>
> def summon_mothership(self):
>     pass
>
> def destroy_planet(self):
>     pass
>
> def teleport(self):
>     pass
>
> def invoke_aliens(self):
>     pass
>
> def invade_earth(self):
>     pass
>
> def takeover_galaxy(self):
>     pass
> ```

> [accordion] Too many return statements (%s/%s)
>
> Highlights functions with more return statements than recommended, suggesting that simplifying the function's logic could improve readability and flow.
>
> ```python Bad theme={"theme":"css-variables"}
> def to_string(x):  # [too-many-return-statements]
> # max of 6 by default, can be configured
> if x == 1:
>     return "This is one."
> if x == 2:
>     return "This is two."
> if x == 3:
>     return "This is three."
> if x == 4:
>     return "This is four."
> if x == 5:
>     return "This is five."
> if x == 6:
>     return "This is six."
> if x == 7:
>     return "This is seven."
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> NUMBERS_TO_STRINGS = {
> 1: "one",
> 2: "two",
> 3: "three",
> 4: "four",
> 5: "five",
> 6: "six",
> 7: "seven",
> }
>
>
> def to_string(x):
> return f"This is {NUMBERS_TO_STRINGS.get(x)}."
> ```

> [accordion] Too many statements (%s/%s)
>
> Flags functions containing more statements than recommended, indicating potential for refactoring to break down complex functions into smaller, more manageable pieces.
>
> ```python Bad theme={"theme":"css-variables"}
> import random
>
>
> def distribute_candies(  # [too-many-statements]
> children: list[Child], candies_per_child: int
> ):
> # This function is a masterpiece of code that embodies the epitome of efficiency
> # it's also an essential part of a high-priority project with extremely tight deadlines
> # and there is absolutely no time to refactor it to make it more concise.
> # The lead developer on the project, who has decades of experience,
> # has personally reviewed this implementation and deemed it good enough as it is.
> # The person writing this code has a demanding job and multiple responsibilities,
> # and simply does not have the luxury of spending time making this code more readable.
> total_candies = len(children) * candies_per_child
> eaten_candies = 0
> # Counting candies given to each child
> for child in children:
>     # If a child eat more than 1 candies they're going to eat all
>     # the candies for sure
>     eaten_for_child = random.choices([0, 1, candies_per_child])
>     print(
>         f"Child {child} gets {candies_per_child} candies and eat {eaten_for_child}"
>     )
>     remaining_candies_for_children = child.eat_candies(eaten_for_child)
>     if remaining_candies_for_children == 0:
>         print(f"All the candies have been devoured by {child.name}!")
>     else:
>         print(
>             f"{child.name} still have {remaining_candies_for_children} candies left."
>         )
>     eaten_candies += eaten_for_child
> return eaten_candies, total_candies
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import random
>
>
> def distribute_candies(children: list[Child], candies_per_child: int):
> total_candies = len(children) * candies_per_child
> eaten_candies = 0
> for child in children:
>     eaten_candies += _distribute_candies_to_child(candies_per_child, child)
> return eaten_candies, total_candies
>
>
> def _distribute_candies_to_child(candies_per_child: int, child: Child):
> # If a child eat more than 1 candies they're going to eat all
> # the candies for sure
> eaten_for_child = random.choices([0, 1, candies_per_child])
> print(f"Child {child} gets {candies_per_child} candies and eat {eaten_for_child}")
> remaining_candies_for_children = child.eat_candies(eaten_for_child)
> if remaining_candies_for_children == 0:
>     print(f"All the candies have been devoured by {child.name}!")
> else:
>     print(f"{child.name} still have {remaining_candies_for_children} candies left.")
> return eaten_for_child
> ```

> [accordion] Disallow trailing comma tuple
>
> Highlights tuples created with a trailing comma, which might be mistaken for a tuple with multiple items. Removing unnecessary commas can avoid confusion and make the code clearer.
>
> ```python Bad theme={"theme":"css-variables"}
> COMPASS = "north", "south", "east", "west",  # [trailing-comma-tuple]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> COMPASS = ("north", "south", "east", "west")
> ```

> [accordion] Unnecessary use of a comprehension, use %s instead.
>
> Points out the use of a comprehension where a simpler constructor or function could achieve the same result, enhancing code simplicity and readability by using more direct methods.
>
> ```python Bad theme={"theme":"css-variables"}
> NUMBERS = [1, 1, 2, 2, 3, 3]
>
> UNIQUE_NUMBERS = {number for number in NUMBERS}  # [unnecessary-comprehension]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> NUMBERS = [1, 1, 2, 2, 3, 3]
>
> UNIQUE_NUMBERS = set(NUMBERS)
> ```

> [accordion] Unnecessary dictionary index lookup, use '%s' instead
>
> Identifies instances where dictionary keys are accessed to retrieve values in a way that could be simplified, recommending more direct methods for accessing values to improve code efficiency and readability.
>
> ```python Bad theme={"theme":"css-variables"}
> FRUITS = {"apple": 1, "orange": 10, "berry": 22}
>
> for fruit_name, fruit_count in FRUITS.items():
> print(FRUITS[fruit_name])  # [unnecessary-dict-index-lookup]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> FRUITS = {"apple": 1, "orange": 10, "berry": 22}
>
> for fruit_name, fruit_count in FRUITS.items():
> print(fruit_count)
> ```

> [accordion] Unnecessary list index lookup, use '%s' instead
>
> Flags unnecessary retrieval of list items by index in contexts where a simpler approach could be used, suggesting improvements for code simplicity and performance.
>
> ```python Bad theme={"theme":"css-variables"}
> letters = ["a", "b", "c"]
>
> for index, letter in enumerate(letters):
> print(letters[index])  # [unnecessary-list-index-lookup]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> letters = ["a", "b", "c"]
>
> for index, letter in enumerate(letters):
> print(letter)
> ```

> [accordion] Use a generator instead '%s(%s)'
>
> Recommends using a generator expression instead of a more verbose construct for creating iterators, improving memory efficiency and code readability by lazily generating items.
>
> ```python Bad theme={"theme":"css-variables"}
> from random import randint
>
> all([randint(-5, 5) > 0 for _ in range(10)])  # [use-a-generator]
> any([randint(-5, 5) > 0 for _ in range(10)])  # [use-a-generator]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from random import randint
>
> all(randint(-5, 5) > 0 for _ in range(10))
> any(randint(-5, 5) > 0 for _ in range(10))
> ```

> [accordion] Consider using '%s' instead of a call to 'dict'.
>
> Suggests using the dictionary literal \{} instead of the dict() constructor for initializing dictionaries, enhancing code conciseness and clarity.

> [accordion] Consider using \[] instead of list()
>
> Advises using the list literal \[] over list() for creating empty lists, promoting code clarity and aligning with Pythonic best practices for simplicity.
>
> ```python Bad theme={"theme":"css-variables"}
> empty_list = list()  # [use-list-literal]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> empty_list = []
> ```

> [accordion] Use set for membership test
>
> Recommends using a set for membership tests instead of a list or tuple, especially when dealing with large collections, to improve performance by leveraging the efficiency of hash-based lookups.
>
> ```python Bad theme={"theme":"css-variables"}
> def fruit_is_dangerous_for_cat(fruit: str)  bool:
> """This list is only a silly example, don't make decision regarding your cat diet based on it."""
> return fruit in ["cherry", "grapes"]  # [use-set-for-membership]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def fruit_is_dangerous_for_cat(fruit: str)  bool:
> """This list is only a silly example, don't make decision regarding your cat diet based on it."""
> return fruit in {"cherry", "grapes"}
> ```

> [accordion] Class %r inherits from object, can be safely removed from bases in python3
>
> Indicates a class explicitly inherits from object, which is unnecessary in Python 3 and can be removed for simplicity and to adhere to modern Python class definitions.
>
> ```python Bad theme={"theme":"css-variables"}
> class Banana(object):  # [useless-object-inheritance]
> ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Banana: ...
> ```

> [accordion] Useless option value
>
> Flags configuration options that are set to ineffective or redundant values, suggesting a review and cleanup of configuration settings for clarity and effectiveness.
>
> ```python Bad theme={"theme":"css-variables"}
> """'bad-continuation' was removed from pylint in https://github.com/pylint-dev/pylint/pull/3571"""
>
> # pylint: disable=bad-continuation  # [useless-option-value]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> """'bad-continuation' was removed from pylint in https://github.com/pylint-dev/pylint/pull/3571"""
> ```

> [accordion] Useless return at end of function or method
>
> Highlights return statements at the end of functions that don't return a value, which can be omitted for simplicity and to avoid implying that the function is expected to return a value.
>
> ```python Bad theme={"theme":"css-variables"}
> import sys
>
>
> def print_python_version():  # [useless-return]
> print(sys.version)
> return None
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import sys
>
>
> def print_python_version():
> print(sys.version)
> ```

> [accordion] Old style no self use
>
> Identifies methods that do not use their self parameter, suggesting they could be static in older codebases, which can improve organization and potentially reduce memory usage.

> [accordion] Old style simplifiable if statement
>
> Flags if statements in older code that can be simplified, recommending more concise and readable alternatives to improve code maintainability and clarity.

> [accordion] Old style too many nested blocks
>
> Warns about excessive nesting in older code, suggesting refactoring to reduce complexity and improve readability by flattening deeply nested structures.

> [accordion] Replace bare except statements with explicit exceptions
>
> This rule advises against using a bare except clause in a try-except block, which can catch and suppress unexpected exceptions, making it difficult to diagnose and handle errors. Instead, it recommends using specific exception types or handling exceptions explicitly to ensure that errors are appropriately managed and communicated.
>
> ```python Bad theme={"theme":"css-variables"}
> try:
> some_important_code()
> except:
> raise "Retry"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> try:
> some_important_code()
> except Exception:
> raise "Retry"
> ```

> [accordion] Simplify repeated if statements into one
>
> This rule suggests simplifying repeated if statements by combining them into a single condition. This can make the code more concise and easier to understand, reducing redundancy and improving readability.
>
> ```python Bad theme={"theme":"css-variables"}
> if x < 5 and y < 10:
> grid = range(10)
> if x < 5 and y < 100:
> grid = range(100)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> if x < 5:
> if y < 10:
>     grid = range(10)
> if y < 100:
>     grid = range(100)
> ```

# step 7

> [accordion] Insert default get statements with explicit default values
>
> This rule advises using the get method for dictionary lookups with default values instead of using the in operator to check for the key and then accessing the value directly. Using get can make the code more concise and readable, and it can be more efficient by avoiding redundant dictionary lookups.
>
> ```python Bad theme={"theme":"css-variables"}
> if self.favourite_hat in available_hats:
> hat_to_wear = available_hats[self.favourite_hat]
> else:
> hat_to_wear = NO_HAT
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> hat_to_wear = available_hats.get(self.favourite_hat, NO_HAT)
> ```

> [accordion] Replace any() with in for membership checks
>
> This rule suggests using the in operator to check for the presence of an element in a collection instead of using the any function with a generator expression. Using the in operator can make the code more concise and readable, and it can be more efficient by short-circuiting the iteration when the element is found.
>
> ```python Bad theme={"theme":"css-variables"}
> if any(hat == "bowler" for hat in hats):
> shout("I have a bowler hat!")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> if "bowler" in hats:
> shout("I have a bowler hat!")
> ```

> [accordion] Invert negative any() and all() for better readability
>
> This rule suggests inverting the use of any and all functions by applying De Morgan's laws. This can make the code more concise and readable, and it can be more efficient by short-circuiting the iteration when the condition is met.
>
> ```python Bad theme={"theme":"css-variables"}
> b = not all(a > b for a in things)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> b = any(not a > b for a in things)
> ```

> [accordion] Merge except handlers with same body for better readability
>
> This rule suggests merging multiple except clauses that have the same handler into a single clause. This can make the code more concise and easier to understand, reducing redundancy and improving readability.
>
> ```python Bad theme={"theme":"css-variables"}
> try:
> f = open("myfile.txt")
> s = f.readline()
> i = int(s.strip())
> except OSError as err:
> logger.exception("Error while reading myfile.txt")
> raise
> except ValueError as err:
> logger.exception("Error while reading myfile.txt")
> raise
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> try:
> f = open("myfile.txt")
> s = f.readline()
> i = int(s.strip())
> except (OSError, ValueError) as err:
> logger.exception("Error while reading myfile.txt")
> raise
> ```

> [accordion] autofix/no-unused-vars
>
> Flags variables that are declared but not used, helping to identify potential errors or unnecessary code, improving code readability and efficiency.
>
> ```python Bad theme={"theme":"css-variables"}
> function example() {
>     var unused = "This text is not used";
>     console.log("Hello World");
>   }
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> function example() {
>     console.log("Hello World");
>   }
> ```

> [accordion] autofix/eqeqeq
>
> Enforces the use of strict equality operators (=== and !==) over the abstract equality operators (== and !=) to avoid type coercion errors, ensuring more predictable and safer code.
>
> ```python Bad theme={"theme":"css-variables"}
> if (x == y) {
>     // do something
>   }
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> if (x === y) {
>     // do something
>   }
> ```

> [accordion] autofix/no-var
>
> Encourages the use of let or const instead of var to improve code readability and reduce scope-related errors by using block-scoped variables.
>
> ```python Bad theme={"theme":"css-variables"}
> var x = "Hello World";
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> let x = "Hello World";
> ```

> [accordion] autofix/no-useless-catch
>
> Disallows catch clauses that only rethrow the caught error, encouraging more efficient error handling by either handling the error or allowing it to bubble up naturally.
>
> ```python Bad theme={"theme":"css-variables"}
> try {
>     doSomething();
>   } catch (e) {
>     throw e;
>   }
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> try {
>     doSomething();
>   } catch (e) {
>     handleError(e);
>   }
> ```

> [accordion] autofix/no-useless-concat
>
> Identifies unnecessary string concatenations, promoting the use of template literals or simpler expressions for better readability and performance.
>
> ```python Bad theme={"theme":"css-variables"}
> var fullName = "John " + "Doe";
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> var fullName = "John Doe";
> ```

> [accordion] autofix/prefer-const
>
> Suggests using const for variables that are never reassigned after their initial declaration, indicating to readers that their values remain constant, which enhances code clarity and reliability.
>
> ```python Bad theme={"theme":"css-variables"}
> let x = 10;
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> const x = 10;
> ```

> [accordion] autofix/prefer-arrow-callback
>
> Favors arrow functions as callbacks to utilize their concise syntax and lexical this binding, leading to cleaner and more understandable code.
>
> ```python Bad theme={"theme":"css-variables"}
> arr.map(function(item) { return item * 2; });
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> arr.map(item => item * 2);
> ```

> [accordion] autofix/sort-imports
>
> Enforces sorting of import statements to improve code readability and maintainability by making it easier to visually inspect and manage dependencies.
>
> ```python Bad theme={"theme":"css-variables"}
> import b from 'foo.js';
>   import a from 'bar.js';
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import a from 'bar.js';
>   import b from 'foo.js';
> ```

> [accordion] autofix/no-unneeded-ternary
>
> Flags ternary operators that could be simplified to simpler expressions, promoting cleaner and more direct code by avoiding unnecessary complexity.
>
> ```python Bad theme={"theme":"css-variables"}
> var isAdult = age > 18 ? true : false;
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> var isAdult = age > 18;
> ```

> [accordion] react/react-in-jsx-scope
>
> Previously required React to be in scope when using JSX, but this is turned off to accommodate new JSX transforms that do not require React to be explicitly imported.

> [accordion] array-callback-return
>
> Ensures that callback functions for array methods like map, filter, and reduce return a value, preventing unexpected behavior and bugs in array transformations.
>
> ```python Bad theme={"theme":"css-variables"}
> var indexMap = myArray.reduce(function(memo, item, index) {
>         memo[item] = index;
>     }, {});
>
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> var indexMap = myArray.reduce(function(memo, item, index) {
>         memo[item] = index;
>         return memo; // This is the required return statement
>     }, {});
> ```

> [accordion] logical-assignment-operators
>
> Encourages the use of logical assignment operators to concisely perform logical operations and assignments in one step, enhancing code brevity and readability.
>
> ```python Bad theme={"theme":"css-variables"}
> if (!x) x = y;
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x ||= y;
> ```

> [accordion] no-floating-decimal
>
> Prevents floating decimals without a leading zero, which can make the code harder to read and lead to potential misunderstandings, ensuring numeric values are clearly defined.
>
> ```python Bad theme={"theme":"css-variables"}
> var num = .5;
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> var num = 0.5;
> ```

> [accordion] no-promise-executor-return
>
> Disallows returning values from the executor function of a new Promise, which can lead to confusing and possibly ignored returns, ensuring the executor is used for its intended purpose of resolving or rejecting the promise.
>
> ```python Bad theme={"theme":"css-variables"}
> new Promise((resolve, reject) => {
>     return 'result';
>   });
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> new Promise((resolve, reject) => {
>     resolve('result');
>   });
> ```

> [accordion] no-return-await
>
> Discourages unnecessary use of await inside return statements, which can lead to extra microtask queue jumps and potentially affect performance, simplifying asynchronous control flow.
>
> ```python Bad theme={"theme":"css-variables"}
> async function foo() {
>     return await bar();
>   }
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> async function foo() {
>     return bar();
>   }
> ```

> [accordion] no-undef-init
>
> Disallows initializing variables to undefined, as it is unnecessary and can lead to confusion, promoting cleaner and more intentional variable declarations.
>
> ```python Bad theme={"theme":"css-variables"}
> var x = undefined;
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> var x;
> ```

> [accordion] no-useless-rename
>
> Disallows renaming import, export, and destructured assignments to the same name, reducing redundancy and improving code readability and maintainability.
>
> ```python Bad theme={"theme":"css-variables"}
> import { foo as foo } from 'bar';
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import { foo } from 'bar';
> ```

> [accordion] react/hook-use-state
>
> Enforces the correct usage of useState hook, ensuring state is managed consistently and effectively in React functional components.
>
> ```python Bad theme={"theme":"css-variables"}
> import React from 'react';
>
> export default function useColor() {
> // useState call is not destructured into value + setter pair
> const useStateResult = React.useState();
> return useStateResult;
> }
>
> export default function useColor() {
> // useState call is destructured into value + setter pair, but identifier
> // names do not follow the [thing, setThing] naming convention
> const [color, updateColor] = React.useState();
> return useStateResult;
> }
>
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import React from 'react';
> export default function useColor() {
> // useState call is destructured into value + setter pair whose identifiers
> // follow the [thing, setThing] naming convention
> const [color, setColor] = React.useState();
> return [color, setColor];
> }
>
>
> ```

> [accordion] react/jsx-no-leaked-render
>
> Aims to prevent memory leaks in React components by ensuring JSX elements do not inadvertently retain state or props that could lead to leaks, promoting better resource management and component reliability.
>
> ```python Bad theme={"theme":"css-variables"}
> function ItemList({ items }) {
> return (
>     <div>
>     {items.map((item) => (
>         <div>
>         {item.name}
>         {item.count && <span>Count: {item.count}</span>}
>         </div>
>     ))}
>     </div>
> );
> }
>
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> function ItemList({ items }) {
>     return (
>         <div>
>         {items.map((item) => (
>             <div>
>             {item.name}
>             {item.count > 0 && <span>Count: {item.count}</span>}
>             </div>
>         ))}
>         </div>
>     );
>     }
>
> ```

> [accordion] Regular expressions should not be too complicated
>
> Overly complicated regular expressions are hard to read and to maintain and can easily cause hard-to-find bugs. If a regex is too complicated, you should consider replacing it or parts of it with regular code or splitting it apart into multiple patterns at least.
>
> The complexity of a regular expression is determined as follows:
>
> Each of the following operators increases the complexity by an amount equal to the current nesting level and also increases the current nesting level by one for its arguments:
>
> <ul>
>   <li>
>     \`| - when multiple | operators are used together, the subsequent ones only increase the complexity by 1
>   </li>
>
>   <li>
>     Quantifiers (\*, +, ?, etc.)
>   </li>
>
>   <li>
>     Non-capturing groups that set flags (such as (?i:some\_pattern) or (?i)some\_pattern\`)
>   </li>
>
>   <li>
>     Lookahead and lookbehind assertions
>   </li>
> </ul>
>
> Additionally, each use of the following features increase the complexity by 1 regardless of nesting:
>
> <ul>
>   <li>
>     character classes
>   </li>
>
>   <li>
>     back references
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> p = re.compile(r"^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$")
>
> if p.match($dateString):
> handleDate($dateString)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> p = re.compile("^\d{1,2}([-/.])\d{1,2}\1\d{1,4}$")
> if p.match($dateString):
> dateParts = re.split(r"[-/.]", dateString)
> day = intval(dateParts[0])
> month = intval(dateParts[1])
> year = intval($dateParts[2])
> // Put logic to validate and process the date based on its integer parts here
> ```

> [accordion] Jump statements should not be redundant
>
> Jump statements, such as `return, break and continue` let you change the default flow of program execution, but jump statements that direct the control flow to the original direction are just a waste of keystrokes.
>
> ```python Bad theme={"theme":"css-variables"}
> def redundant_jump(x):
> if x == 1:
>     print(True)
>     return  # NonCompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def redundant_jump(x):
> if x == 1:
>     print(True)
> ```

> [accordion] Test methods should be discoverable
>
> Classes subclassing only \`unittest.TestCase are considered test cases, otherwise they might be mixins.
>
> As classes subclassing unittest.TestCase will be executed as tests, they should define test methods and not be used as "abstract" parent helper. Methods within the class will be discovered by the test runner if their name starts with test. If a method intended to be a test does not respect this convention, it will not be executed.
>
> This rule raises an issue when a method is not discoverable as a test and is never used within its test case class.
>
> This rule will not raise if:
>
> <ul>
>   <li>
>     The method is called directly from another method.
>   </li>
>
>   <li>
>     The method overrides an existing one in unittest.TestCase  (example: a tearDown\`  method).
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> import unittest
> class MyTest(unittest.TestCase):
> def setUp(self): ... # OK (unittest.TestCase method)
> def something_test(self): ... # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import unittest
> class MyTest(unittest.TestCase):
> def setUp(self): ...
> def test_something(self): ...
> ```

> [accordion] return and yield should not be used in the same function
>
> Functions that use `yield are known as "generators". Before Python 3.3, generators cannot return values. Similarly, functions that use return cannot use yield. Doing so will cause a SyntaxError`.
>
> Either upgrade your version of Python to a version >= 3.3, or don’t use both return and yield in a function.
>
> ```python Bad theme={"theme":"css-variables"}
> def adder(n):
>  num = 0
>  while num < n:
>      yield num
>      num += 1
>  return num  #Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] Built-in generic types should be preferred over the typing module in type hints
>
> Python 3.9 introduced built-in generic types such as list\[T], dict\[T], set\[T] to make type hints more concise and easier to read.
> These built-in types have the same functionality as their counterparts in the typing module, but are more readable and idiomatic.
>
> Using types such as typing.List is confusing in the presence of the already existing built-in types.
> This can also create inconsistencies when different parts of the codebase use different syntaxes for the same type.
>
> ```python Bad theme={"theme":"css-variables"}
> import typing
>
> def print_numbers(numbers: typing.List[int])  None:
> for n in numbers:
>     print(n)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def print_numbers(numbers: list[int])  None:
> for n in numbers:
>     print(n)
> ```

> [accordion] **len** should always return an integer greater than or equal to zero
>
> The [\`**len**](https://docs.python.org/3/reference/datamodel.html#object.__len__) special method enables to define the length of an object. As such it should always return an integer greater than or equal to 0. When the len(...) builtin is called on an object, any other return type will raise a TypeError and a negative integer will raise a ValueError.
>
> This rule raises an issue when a **len**\` method returns an expression which is not an integer greater than or equal to 0.
>
> ```python Bad theme={"theme":"css-variables"}
> class A:
> def __len__(self):
>     return 2.0  # Noncompliant
>
> len(A())  # This will raise "TypeError: 'float' object cannot be interpreted as an integer"
>
> class B:
> def __len__(self):
>     return -2  # Noncompliant
>
> len(B())  # This will raise "ValueError: __len__() should return >= 0"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class A:
> def __len__(self):
>     return 2
>
> len(A())  # This will return 2
> ```

> [accordion] Server-side templates should not be vulnerable to injection attacks
>
> Server-side template injections occur in an application when the application
> retrieves data from a user or a third-party service and inserts it into a
> template, without sanitizing it first.
>
> If an application contains a template that is vulnerable to injections,
> it is exposed to attacks that target the underlying rendering server.
>
> A user with malicious intent can create requests that will cause
> the template to change its logic into unwanted behavior.
>
> After creating the malicious request, the attacker can attack the servers
> affected by this vulnerability without relying on any prerequisites.
>
> ```python Bad theme={"theme":"css-variables"}
> from flask import request, render_template_string
>
> @app.route('/example')
> def example():
> username = request.args.get('username')
> template = f"<p>Hello {username}</p>"
> return render_template_string(template) # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from flask import request, render_template_string
>
> @app.route('/example')
> def example():
> username = request.args.get('username')
> template = "<p>Hello {{ username }}</p>"
> return render_template_string(template, username=username)
> ```

> [accordion] Results that depend on random number generation should be reproducible
>
> Data science and machine learning tasks make extensive use of random number generation. It may, for example, be used for:
>
> <ul>
>   <li>
>     Model initialization
>
>     <ul>
>       <li>
>         Randomness is used to initialize the parameters of machine learning models. Initializing parameters with random values helps to break symmetry and prevents models from getting stuck in local optima during training. By providing a random starting point, the model can explore different regions of the parameter space and potentially find better solutions.
>       </li>
>     </ul>
>   </li>
>
>   <li>
>     Regularization techniques
>
>     <ul>
>       <li>
>         Randomness is used to introduce noise into the learning process. Techniques like dropout and data augmentation use random numbers to randomly drop or modify features or samples during training. This helps to regularize the model, reduce overfitting, and improve generalization performance.
>       </li>
>     </ul>
>   </li>
>
>   <li>
>     Cross-validation and bootstrapping
>
>     <ul>
>       <li>
>         Randomness is often used in techniques like cross-validation, where data is split into multiple subsets. By using a predictable seed, the same data splits can be generated, allowing for fair and consistent model evaluation.
>       </li>
>     </ul>
>   </li>
>
>   <li>
>     Hyperparameter tuning
>
>     <ul>
>       <li>
>         Many machine learning algorithms have hyperparameters that need to be tuned for optimal performance. Randomness is often used in techniques like random search or Bayesian optimization to explore the hyperparameter space. By using a fixed seed, the same set of hyperparameters can be explored, making the tuning process more controlled and reproducible.
>       </li>
>     </ul>
>   </li>
>
>   <li>
>     Simulation and synthetic data generation
>
>     <ul>
>       <li>
>         Randomness is often used in techniques such as data augmentation and synthetic data generation to generate diverse and realistic datasets.
>       </li>
>     </ul>
>   </li>
> </ul>
>
> To ensure that results are reproducible, it is important to use a predictable seed in this context.
>
> The preferred way to do this in numpy is by instantiating a Generator object, typically through numpy.random.default\_rng, which should be provided with a seed parameter.
>
> Note that a global seed for RandomState can be set using numpy.random.seed or numpy.seed, this will set the seed for RandomState methods such as numpy.random.randn. This approach is, however, deprecated and Generator should be used instead. This is reported by rule S6711.
>
> ```python Bad theme={"theme":"css-variables"}
> import numpy as np
>
> def foo():
> generator = np.random.default_rng()  # Noncompliant: no seed parameter is provided
> x = generator.uniform()
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import numpy as np
>
> def foo():
> generator = np.random.default_rng(42)  # Compliant
> x = generator.uniform()
> ```

> [accordion] pandas.pipe method should be preferred over long chains of instructions
>
> The pandas library provides many ways to filter, select, reshape and modify a data frame.
> Pandas supports as well method chaining, which means that many `DataFrame methods return a modified DataFrame`.
> This allows the user to chain multiple operations together, making it effortless perform several of them in one line of code:
>
> ```python Bad theme={"theme":"css-variables"}
> import pandas as pd
>
> schema = {'name':str, 'domain': str, 'revenue': 'Int64'}
> joe = pd.read_csv("data.csv", dtype=schema).set_index('name').filter(like='joe', axis=0).groupby('domain').mean().round().sample()
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import pandas as pd
>
> def foo(df: pd.DataFrame):
> return df.set_index('name').filter(like='joe', axis=0).groupby('team').mean().round().sort_values('salary').take([0]) # Noncompliant: too many operations happen on this data frame.
> ```

> [accordion] Only defined names should be listed in **all**
>
> The `all property of a module is used to define the list of names that will be imported when performing a wildcard import of this module, i.e. when from mymodule import *` is used.
>
> In the following example:
>
> ```python Bad theme={"theme":"css-variables"}
> # mymodule.py
>
> def foo(): ...
> def bar(): ...
>
> __all__ = ["foo"]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from mymodule import my_func
>
> __all__ = ["unknown_func"]  # Noncompliant: "unknown_func" is undefined
> ```

> [accordion] Generic type statements should not use TypeVars
>
> Prior to Python 3.12, generic type aliases were defined as follows:
>
> ```python Bad theme={"theme":"css-variables"}
> from typing import TypeAlias, TypeVar
>
> _T = TypeVar("_T")
>
> MyAlias: TypeAlias = set[_T]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> type MyAlias[T] = set[T]
> ```

> [accordion] Python side effects should not be used inside a tf.function
>
> Python sides effects such as printing, mutating a list or a global variable, inside of a tensorflow\.function may not behave as expected.
> Because of the [Rules of tracing](https://www.tensorflow.org/guide/function#rules_of_tracing),
> the execution of side effects will depend on the input values of the function and will execute only once per tracing.
>
> ```python Bad theme={"theme":"css-variables"}
> import tensorflow as tf
>
> @tf.function
> def f(x):
> print("A side effect", x)
>
> f(1) # prints "A side effect 1"
> f(1) # does not print anything
> f(2) # prints "A side effect 2"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import tensorflow as tf
>
> @tf.function
> def f(x):
> print("Printing", x) # Noncompliant print is a side effect
> ```

> [accordion] Static methods should not have self or cls arguments
>
> Unlike class and instance methods, static methods don’t receive an implicit first argument. Nonetheless naming the first argument `self or clz` guarantees confusion - either on the part of the original author, who may never understand why the arguments don’t hold the values he expected, or on that of future maintainers.
>
> ```python Bad theme={"theme":"css-variables"}
> class MyClass:
> @staticmethod
> def s_meth(self, arg1, arg2):  #Noncompliant
> # ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyClass:
> @staticmethod
> def s_meth(arg1, arg2):  #Noncompliant
> # ...
> ```

> [accordion] Iterable unpacking, for-in loops and yield from should use an Iterable object
>
> for-in loops, [yield from](https://docs.python.org/3/whatsnew/3.3.html#pep-380-syntax-for-delegating-to-a-subgenerator) and iterable unpacking only work with [iterable objects](https://docs.python.org/3/glossary.html#term-iterable). In order to be iterable, an object should have either an \`**iter** method or a **getitem** method implementing the [Sequence](https://docs.python.org/3/glossary.html#term-sequence) protocol.
>
> When trying to iterate over an object which does not implement the required methods, a TypeError will be raised.
>
> Below is an example of a basic implementation of a iterator with **iter**\`:
>
> ```python Bad theme={"theme":"css-variables"}
> class IterExample(object):
> def __init__(self):
>     self._values = [1,2,3,4]
>
> def __iter__(self):
>     return iter(self._values)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class GetItemExample(object):
> def __init__(self):
>     self._values = [1,2,3,4]
>
> def __getitem__(self, item):
>     return self._values[item]
> ```

> [accordion] Variables named as constants should not be reassigned
>
> There are no constants in Python, but when a variable is named with all uppercase letters, the convention is to treat it as a constant. I.e. to use it as a read-only variable, and not reassign its value.
>
> Ignore this convention, and you run the risk of confusing other developers, particularly those with experience in other languages. This rule raises an issue each time a variable named with all uppercase letters is reassigned.
>
> ```python Bad theme={"theme":"css-variables"}
> RESOURCE_NAME = 'foo'
> # ...
> RESOURCE_NAME = 'bar'  # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] Sequence indexes must have an **index** method
>
> Objects can be used as sequence indexes to access a specific element from the sequence, through the following syntax:
>
> ```python Bad theme={"theme":"css-variables"}
> my_list = [1, 2, 3, 4]
> x = 1
> print(my_list[x])  # This will print 2
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> my_list = [1, 2, 3, 4]
> x = 1
> print(my_list[1:3]) # This will print [2, 3]
> ```

> [accordion] Variables, classes and functions should be either defined or imported
>
> Variables, Classes and functions should not be undefined, otherwise the code will fail with a NameError.
>
> ```python Bad theme={"theme":"css-variables"}
> my_var # Noncompliant (variable is never defined)
>
> def noncompliant():
> foo()  # Noncompliant
> MyClass()  # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from mod import my_var
>
> my_var
>
> def compliant():
> foo = sum
> foo()
>
> class MyClass:
>     pass
> MyClass()
> ```

> [accordion] Assertions comparing incompatible types should not be made
>
> Calling \`unittest methods assertEqual, assertNotEqual, assertIs or assertIsNot on objects of incompatible types will always fail or always succeed.
>
> For methods assertEqual and assertNotEqual, arguments' types are incompatible if:
>
> <pre>they are unrelated builtin types such as string and integer.</pre>
>
> <pre>they are instances of unrelated classes which do not implement ++**eq**++ or ++**ne**++ (if a class implements one of these methods it could compare to any other type it wants).</pre>
>
> As for methods assertIs and assertIsNot, if arguments' types are different it is not possible for them to point to the same object, thus assertIs will always fail and assertIsNot\` will always succeed.
>
> ```python Bad theme={"theme":"css-variables"}
> import unittest
> class A(): ...
> class MyTest(unittest.TestCase):
> def test_something(self):
> a = A()
> mydict = {"x": a}
> self.assertEqual(a, "x")  # Noncompliant
> self.assertIs(a, "x")  # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import unittest
> class A(): ...
> class MyTest(unittest.TestCase):
> def test_something(self):
> a = A()
> mydict = {"x": a}
> self.assertEqual(a, mydict["x"])  # OK
> self.assertIs(a, mydict["x"])  # OK
> ```

> [accordion] Dictionary unpacking should only be done with mapping objects
>
> Dictionary unpacking allows you to pass the key-value pairs of a dictionary as keyword arguments to a function or merge dictionaries:
>
> ```python Bad theme={"theme":"css-variables"}
> def foo(a, b):
> print(a+b)
>
> my_dict = {"a": 1, "b": 2}
> foo(**my_dict) # will print 3
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class A:
> pass
>
> dict(**A())  # Noncompliant
> {'a': 10, 'b': 20, **A()}  # Noncompliant
> ```

> [accordion] \<> should not be used to test inequality
>
> The operators `<> and != are equivalent.
> However, the <> operator is considered obsolete in Python 2.7 and
> has been removed from Python 3. Therefore, it is recommended to use !=` instead.
>
> ```python Bad theme={"theme":"css-variables"}
> return a <> b # Noncompliant: the operator "<>" is deprecated.
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> return a != b
> ```

> [accordion] f-strings should not be nested too deeply
>
> Through [PEP 701](https://peps.python.org/pep-0701/), Python 3.12 lifts restrictions on how to construct "f-strings".
>
> Prior to Python 3.12, it was not possible to reuse string quotes when nesting "f-strings". Therefore, the maximum level of nesting was:
>
> ```python Bad theme={"theme":"css-variables"}
> f"""{f'''{f'{f"{1+1}"}'}'''}"""
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> f"{f"{f"{f"{f"{f"{1+1}"}"}"}"}"}"
> ```

> [accordion] tf.function should not depend on global or free Python variables
>
> When calling a tensorflow\.function behind the scenes a ConcreteFunction is created everytime a new value is passed as argument.
> This is not the case with Python global variables, closure or nonlocal variables.
>
> This means the state and the result of the tensorflow\.function may not be what is expected.
>
> ```python Bad theme={"theme":"css-variables"}
> import tensorflow as tf
>
> @tf.function
> def addition():
> return 1 + foo
>
> foo = 4
> addition() # tf.Tensor(5, shape=(), dtype=int32): on this first step we obtain the expected result
>
> foo = 10
> addition() # tf.Tensor(5, shape=(), dtype=int32): unexpected result of 5 instead of 11
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import tensorflow as tf
>
> @tf.function
> def addition():
> return 1 + foo
>
> foo = tf.Variable(4)
> addition()
>
> foo.assign(10)
> addition()
> ```

> [accordion] The new raise form should be used
>
> The `raise a, b` syntax is deprecated in Python 3, and should no longer be used.
>
> ```python Bad theme={"theme":"css-variables"}
> try:
> if not is_okay:
> raise Exception, 'It\'s not okay'  # Noncompliant
> except Exception as e:
> # ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> try:
> if not is_okay:
> raise Exception('It\'s not okay')
> except Exception as e:
> # ...
> ```

> [accordion] Raised Exceptions must derive from BaseException
>
> Attempting to raise an object which does not derive from BaseException will raise a \`TypeError.
>
> If you are about to create a custom exception class, note that custom exceptions should inherit from Exception, rather than BaseException.
>
> BaseException is the base class for all built-in exceptions in Python, including system-exiting exceptions like SystemExit or KeyboardInterrupt, which are typically not meant to be caught. On the other hand, Exception is intended for exceptions that are expected to be caught, which is generally the case for user-defined exceptions. See [PEP 352](https://www.python.org/dev/peps/pep-0352/#exception-hierarchy-changes) for more information.
>
> To fix this issue, make sure that the object you’re attempting to raise inherits from BaseException\`.
>
> ```python Bad theme={"theme":"css-variables"}
> raise "Something went wrong"  # Noncompliant: a string is not a valid exception
>
> class A:
> pass
>
> raise A  # Noncompliant: A does not inherit from Exception
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyError(Exception):
> pass
>
> raise MyError("Something went wrong")
> raise MyError
> ```

> [accordion] Assignments of lambdas to variables should be replaced by function definitions
>
> Assigning a lambda to a variable is not inherently wrong or discouraged in Python. Lambdas are anonymous functions that can be useful for short and simple expressions or as function arguments. However, there are a few reasons why you might consider alternatives to assigning a lambda to a variable:
>
> <ol>
>   <li>
>     **Readability and clarity:** Lambdas can be concise, but they may become less readable as the expression or logic becomes more complex. For more complex or longer functions, using a regular named function defined with def can make the code more readable and self-explanatory.
>   </li>
>
>   <li>
>     **Reusability:** Lambdas are often used for one-off or small, isolated tasks. If you find that you need to reuse a piece of functionality in multiple places within your code or across modules, it is better to define a named function using def. This promotes code modularity and maintainability.
>   </li>
>
>   <li>
>     **Documentation:** Lambdas do not support docstrings, which are important for providing clear and comprehensive documentation for your functions. If you need to document the purpose, parameters, or behavior of a function, it is best to define a named function using def and include a docstring.
>   </li>
>
>   <li>
>     **Debugging and error handling:** Lambdas are anonymous functions, which means that when an error occurs during execution, the traceback will not provide a specific name associated with the lambda function. This can make it more challenging to identify and troubleshoot errors. Named functions defined with def provide more meaningful tracebacks.
>   </li>
> </ol>
>
> Using a def statements rather than assigning lambdas to variable is also recommended by [PEP8](https://peps.python.org/pep-0008/).
>
> ```python Bad theme={"theme":"css-variables"}
> def foo():
> multiply = lambda x, y: x * y # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def foo():
> def multiply(x, y):
> return x * y
> ...
> ```

> [accordion] in and not in operators should be used on objects supporting them
>
> Operators \`in and not in, also called ["membership test operators"](https://docs.python.org/3/reference/expressions.html#membership-test-operations), require that the right operand supports the membership protocol.
>
> In order to support the membership protocol, a user-defined class should implement at least one of the following methods: **contains**, **iter**, **getitem**.
>
> If none of these methods is implemented, a TypeError\` will be raised when performing a membership test.
>
> ```python Bad theme={"theme":"css-variables"}
> myint = 42
>
> if 42 in myint:  # Noncompliant: integers don't support membership protocol
> ...
>
> class A:
> def __init__(self, values):
>     self._values = values
>
> if "mystring" in A(["mystring"]):  # Noncompliant: class A doesn't support membership protocol
> ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> mylist = [42]
>
> if 42 in mylist:
> ...
>
> class MyContains:
> def __init__(self, values):
>     self._values = values
>
> def __contains__(self, value):
>     return value in self._values
>
> if "mystring" in MyContains(["mystring"]):
> ...
>
> # OR
>
> class MyIterable:
> def __init__(self, values):
>     self._values = values
>
> def __iter__(self):
>     return iter(self._values)
>
> if "mystring" in MyIterable(["mystring"]):
> ...
>
> # OR
>
> class MyGetItem:
> def __init__(self, values):
>     self._values = values
>
> def __getitem__(self, key):
>     return self._values[key]
>
> if "mystring" in MyGetItem(["mystring"]):
> ...
> ```

> [accordion] Deprecated NumPy aliases of built-in types should not be used
>
> In NumPy, some built-in types such as int have aliases in the form of numpy.int. However, these aliases have been deprecated and should not be used anymore.
>
> The following deprecated aliases should be replaced with their built-in alternatives:
>
> <table>
>   <thead>
>     <tr>
>       <th>Deprecated name</th>
>       <th>Equivalent built-in type</th>
>     </tr>
>   </thead>
>
>   <tbody>
>     <tr>
>       <td>numpy.bool</td>
>       <td>bool</td>
>     </tr>
>
>     <tr>
>       <td>numpy.int</td>
>       <td>int</td>
>     </tr>
>
>     <tr>
>       <td>numpy.float</td>
>       <td>float</td>
>     </tr>
>
>     <tr>
>       <td>numpy.complex</td>
>       <td>complex</td>
>     </tr>
>
>     <tr>
>       <td>numpy.object</td>
>       <td>object</td>
>     </tr>
>
>     <tr>
>       <td>numpy.str</td>
>       <td>str</td>
>     </tr>
>
>     <tr>
>       <td>numpy.long</td>
>       <td>int</td>
>     </tr>
>
>     <tr>
>       <td>numpy.unicode</td>
>       <td>str</td>
>     </tr>
>   </tbody>
> </table>
>
> ```python Bad theme={"theme":"css-variables"}
> import numpy as np
> def foo():
> x = np.int(42)  # Noncompliant: deprecated type alias
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import numpy as np
> def foo():
> x = 42  # Compliant
> ```

> [accordion] pytz.timezone should not be passed to the datetime.datetime constructor
>
> When working with timezones in Python, it’s important to understand that the datetime.datetime constructor and pytz timezone objects handle timezones differently. This difference can lead to unexpected results if a pytz object is used as the tzinfo argument in the datetime.datetime constructor.
>
> The datetime.datetime constructor expects a tzinfo object that is a subclass of the datetime.tzinfo base class. pytz timezone objects do provide this interface, but they implement it in a way that’s not fully compatible with datetime.datetime.
>
> One key difference is how they handle historical changes in timezone offsets. The datetime module uses the IANA time zone database, which includes historical changes.
>
> When you create a datetime object with a pytz timezone object as the tzinfo argument, it uses the earliest known offset for that timezone. This can lead to unexpected offsets, as the earliest known offset may not match the current or most commonly used offset for that timezone.
>
> For example, if you were to use 'US/Eastern' as your timezone, you might expect the offset to be either -5 hours (Eastern Standard Time) or -4 hours (Eastern Daylight Time), depending on the time of the year. However, due to historical changes, the actual offset might be something different, like -4 hours and 56 minutes. This can lead to subtle bugs in your code, especially if you’re doing calculations with datetime objects.
>
> Note that, when using Python 3.9 and later, it is recommended to use the zoneinfo package from the standard library over pytz.
>
> ```python Bad theme={"theme":"css-variables"}
> import datetime
> import pytz
>
> dt = datetime.datetime(2022, 1, 1, tzinfo=pytz.timezone('US/Eastern'))  # Noncompliant: 2022-01-01 00:00:00-04:56
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import datetime
> import pytz
>
> dt = pytz.timezone('US/Eastern').localize(datetime.datetime(2022, 1, 1))  # OK: 2022-01-01 00:00:00-05:00
> ```

> [accordion] Special method **exit** should not re-raise the provided exception
>
> Methods `enter and exit make it possible to implement objects which can be used as the expression of a with` statement:
>
> ```python Bad theme={"theme":"css-variables"}
> with MyContextManager() as c :
> ... # do something with c
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> c = MyContextManager()
> c.__enter__()
> try:
> ... # do something with c
> finally:
> c.__exit__()
> ```

> [accordion] The pandas.DataFrame.to\_numpy() method should be preferred to the pandas.DataFrame.values attribute
>
> The \`values attribute and the to\_numpy() method in pandas both provide a way to return a NumPy representation of the DataFrame. However, there are some reasons why the to\_numpy() method is recommended over the values attribute:
>
> <ul>
>   <li>
>     **Future Compatibility:**
>     The values attribute is considered a legacy feature, while the to\_numpy() is the recommended method to extract data and is considered more future-proof.
>   </li>
>
>   <li>
>     **Data type consistency:**
>     If the DataFrame has columns with different data types, NumPy will choose a common data type that can hold all the data. This may lead to loss of information, unexpected type conversions, or increased memory usage. The to\_numpy() allows you to select the common type manually, passing the dtype argument.
>   </li>
>
>   <li>
>     **View vs Copy:**
>     The values attribute can return a view or a copy of the data depending on whether the data needs to be transposed. This can lead to confusion when modifying the extracted data. On the other hand, to\_numpy() has copy argument allowing to force it always to return a new NumPy array, ensuring that any changes you make won’t affect the original DataFrame.
>   </li>
>
>   <li>
>     **Missing values control:**
>     The to\_numpy() allows to specify the default value used for missing values in the DataFrame, while the values will always use numpy.nan\` for missing values.
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> import pandas as pd
>
> df = pd.DataFrame({
>     'X': ['A', 'B', 'A', 'C'],
>     'Y': [10, 7, 12, 5]
> })
>
> arr = df.values # Noncompliant: using the 'values' attribute is not recommended
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import pandas as pd
>
> df = pd.DataFrame({
>     'X': ['A', 'B', 'A', 'C'],
>     'Y': [10, 7, 12, 5]
> })
>
> arr = df.to_numpy() # Compliant
> ```

> [accordion] Operators should be used on compatible types
>
> For a specific operator, two types are considered incompatible if no built-in operations between those types exist and none of the operands has implemented the operator’s corresponding special methods.
> Performing such an operation on incompatible types will raise a TypeError.
>
> Calling an operator in Python is equivalent to calling a special method (except for the identity operator is).
> Python provides a set of built-in operations. For example, to add two integers: 1 + 2, calling the built-in operator + is equivalent to calling the special method \`**add** on the type int.
>
> Python allows developers to define how an operator will behave with a custom class by implementing the corresponding special method.
> When defining such methods for symmetrical binary operators, developers need to define two methods so that the order of operands doesn’t matter, ex: **add** and **radd**\`.
>
> For a complete list of operators and their methods see the Python documentation: [arithmetic and bitwise operators](https://docs.python.org/3/reference/datamodel.html?#emulating-numeric-types), [comparison operators](https://docs.python.org/3/reference/datamodel.html?#object.__lt__).
>
> ```python Bad theme={"theme":"css-variables"}
> class Empty:
> pass
>
> class Add:
> def __add__(self, other):
>     return 42
>
> Empty() + 1  # Noncompliant: no __add__ method is defined on the Empty class
> Add() + 1
> 1 + Add()  # Noncompliant: no __radd__ method is defined on the Add class
> Add() + Empty()
> Empty() + Add()  # Noncompliant: no __radd__ method is defined on the Add class
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Empty:
> pass
>
> class Add:
> def __add__(self, other):
>     return 42
>
> def __radd__(self, other):
>     return 42
>
> Add() + 1
> 1 + Add()
> Add() + Empty()
> Empty() + Add()
> ```

> [accordion] Exceptions **cause** should be either an Exception or None
>
> Exception chaining enables users to see if an exception is the direct consequence of another exception (see [PEP-3134](https://peps.python.org/pep-3134/)). This is useful to propagate the original context of the error.
>
> Exceptions are chained using either of the following syntax:
>
> <ul>
>   <li>
>     With the from keyword
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> try:
> ...
> except OSError as e:
> raise RuntimeError("Something went wrong") from e
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> try:
> ...
> except OSError as e:
> new_exception = RuntimeError("Something went wrong")
> new_exception.__cause__ = e
> raise new_exception
> ```

> [accordion] Loops with at most one iteration should be refactored
>
> A loop with at most one iteration is equivalent to the use of an \`if statement to conditionally execute one piece of code. No developer expects to find such a use of a loop statement. If the initial intention of the author was really to conditionally execute one piece of code, an if statement should be used instead.
>
> At worst that was not the initial intention of the author and so the body of the loop should be fixed to use the nested return, break or raise\` statements in a more appropriate way.
>
> ```python Bad theme={"theme":"css-variables"}
> while node is not None:
> node = node.parent()
> print(node)
> break
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> while node is not None:
> node = node.parent()
> print(node)
> ```

> [accordion] Generic classes should be defined using the type parameter syntax
>
> Through [PEP 695](https://peps.python.org/pep-0695/), Python 3.12 introduces the type parameter syntax to allow for a more compact and explicit way to define generic classes and functions.
>
> Prior to Python 3.12, defining a generic class would be done through the following syntax:
>
> ```python Bad theme={"theme":"css-variables"}
> from typing import Generic, TypeVar
>
> _T_co = TypeVar("_T_co", covariant=True, bound=str)
>
> class ClassA(Generic[_T_co]):
> def method1(self)  _T_co:
>     ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class ClassA[T: str]:
> def method1(self)  T:
>     ...
> ```

> [accordion] Some special methods should return NotImplemented instead of raising NotImplementedError
>
> In Python, special methods corresponding to numeric operators and rich comparison operators should return \`NotImplemented when the operation is not supported.
>
> For example A + B is equivalent to calling A.**add**(B). If this binary operation is not supported by class A, A.**add**(B) should return NotImplemented. The interpreter will then try the reverse operation, i.e. B.**radd**(A). If these special methods were to raise NotImplementedError, the callers would not catch the exception and the reverse operation would not be called.
>
> Below is the list of special methods this rule applies to:
>
> <ul>
>   <li>
>     **lt**(self, other)
>   </li>
>
>   <li>
>     **le**(self, other)
>   </li>
>
>   <li>
>     **eq**(self, other)
>   </li>
>
>   <li>
>     **ne**(self, other)
>   </li>
>
>   <li>
>     **gt**(self, other)
>   </li>
>
>   <li>
>     **ge**(self, other)
>   </li>
>
>   <li>
>     **add**(self, other)
>   </li>
>
>   <li>
>     **sub**(self, other)
>   </li>
>
>   <li>
>     **mul**(self, other)
>   </li>
>
>   <li>
>     **matmul**(self, other)
>   </li>
>
>   <li>
>     **truediv**(self, other)
>   </li>
>
>   <li>
>     **floordiv**(self, other)
>   </li>
>
>   <li>
>     **mod**(self, other)
>   </li>
>
>   <li>
>     **divmod**(self, other)
>   </li>
>
>   <li>
>     **pow**(self, other\[, modulo])
>   </li>
>
>   <li>
>     **lshift**(self, other)
>   </li>
>
>   <li>
>     **rshift**(self, other)
>   </li>
>
>   <li>
>     **and**(self, other)
>   </li>
>
>   <li>
>     **xor**(self, other)
>   </li>
>
>   <li>
>     **or**(self, other)
>   </li>
>
>   <li>
>     **radd**(self, other)
>   </li>
>
>   <li>
>     **rsub**(self, other)
>   </li>
>
>   <li>
>     **rmul**(self, other)
>   </li>
>
>   <li>
>     **rmatmul**(self, other)
>   </li>
>
>   <li>
>     **rtruediv**(self, other)
>   </li>
>
>   <li>
>     **rfloordiv**(self, other)
>   </li>
>
>   <li>
>     **rmod**(self, other)
>   </li>
>
>   <li>
>     **rdivmod**(self, other)
>   </li>
>
>   <li>
>     **rpow**(self, other\[, modulo])
>   </li>
>
>   <li>
>     **rlshift**(self, other)
>   </li>
>
>   <li>
>     **rrshift**(self, other)
>   </li>
>
>   <li>
>     **rand**(self, other)
>   </li>
>
>   <li>
>     **rxor**(self, other)
>   </li>
>
>   <li>
>     **ror**(self, other)
>   </li>
>
>   <li>
>     **iadd**(self, other)
>   </li>
>
>   <li>
>     **isub**(self, other)
>   </li>
>
>   <li>
>     **imul**(self, other)
>   </li>
>
>   <li>
>     **imatmul**(self, other)
>   </li>
>
>   <li>
>     **itruediv**(self, other)
>   </li>
>
>   <li>
>     **ifloordiv**(self, other)
>   </li>
>
>   <li>
>     **imod**(self, other)
>   </li>
>
>   <li>
>     **ipow**(self, other\[, modulo])
>   </li>
>
>   <li>
>     **ilshift**(self, other)
>   </li>
>
>   <li>
>     **irshift**(self, other)
>   </li>
>
>   <li>
>     **iand**(self, other)
>   </li>
>
>   <li>
>     **ixor**(self, other)
>   </li>
>
>   <li>
>     **ior**(self, other)
>   </li>
>
>   <li>
>     **length\_hint**(self)\`
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> class MyClass:
> def __add__(self, other):
>     raise NotImplementedError()  # Noncompliant: the exception will be propagated
> def __radd__(self, other):
>     raise NotImplementedError()  # Noncompliant: the exception will be propagated
>
> class MyOtherClass:
> def __add__(self, other):
>     return 42
> def __radd__(self, other):
>     return 42
>
> MyClass() + MyOtherClass()  # This will raise NotImplementedError
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyClass:
> def __add__(self, other):
>     return NotImplemented
> def __radd__(self, other):
>     return NotImplemented
>
> class MyOtherClass:
> def __add__(self, other):
>     return 42
> def __radd__(self, other):
>     return 42
>
> MyClass() + MyOtherClass()  # This returns 42
> ```

> [accordion] Identity operators should not be used with dissimilar types
>
> Operators [is](https://docs.python.org/3/reference/expressions.html#is-not) and [is not](https://docs.python.org/3/reference/expressions.html#is-not) check if their operands point to the same instance, thus they will always return respectively False and True when they are used to compare objects of different types.
>
> ```python Bad theme={"theme":"css-variables"}
> a = 1
> b = "1"
> value = a is b  # Noncompliant. Always False
> value = a is not b  # Noncompliant. Always True
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> a = 1
> b = 1
> value = a is b
> value = a is not b
> ```

> [accordion] Tests should be skipped explicitly
>
> Test frameworks provide a mechanism to skip tests if their prerequisites are not met, by either calling dedicated methods (e.g: \`unittest.TestCase.skipTest, pytest.skip, …​) or using decorators (e.g: unittest.skip, pytest.mark.skip, …​)
>
> Using a return statement instead will make the test succeed, even though no assertion has been performed. It is therefore better to flag the test as skipped in such situation.
>
> This rule raises an issue when a return is performed conditionally at the beginning of a test method.
>
> No issue will be raised if the return is unconditional as S1763 already raises an issue in such case.
>
> The supported frameworks are Pytest and Unittest\`.
>
> ```python Bad theme={"theme":"css-variables"}
> import unittest
> class MyTest(unittest.TestCase):
>
> def test_something(self):
>     if not external_resource_available():
>         return  # Noncompliant
>     self.assertEqual(foo(), 42)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import unittest
> class MyTest(unittest.TestCase):
>
> def test_something(self):
>     if not external_resource_available():
>         self.skipTest("prerequisite not met")
>     self.assertEqual(foo(), 42)
> ```

> [accordion] The first argument to class methods should follow the naming convention
>
> By convention, the first argument in a class method, i.e. methods decorated with \`@classmethod, is named cls as a representation and a reminder that the argument is the class itself. If you were to name the argument something else, you would stand a good chance of confusing both users and maintainers of the code. It might also indicate that the cls parameter was forgotten, in which case calling the method will most probably fail. This rule also applies to methods **init\_subclass**, **class\_getitem** and **new** as their first argument is always the class instead of "self".
>
> By default this rule accepts cls and mcs, which is sometime used in metaclasses, as valid names for class parameters. You can set your own list of accepted names via the parameter classParameterNames\`.
>
> ```python Bad theme={"theme":"css-variables"}
> class Rectangle(object):
>
> @classmethod
> def area(bob, height, width):  #Noncompliant
> return height * width
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Rectangle(object):
>
> @classmethod
> def area(cls, height, width):
> return height * width
> ```

> [accordion] Union type expressions should be preferred over typing.Union in type hints
>
> Python 3.10 introduced a specific syntax using the "or" operator (X | Y) to represent a union of types.
> This syntax has the same functionality as typing.Union, but it is more concise and easier to read.
>
> Using typing.Union is more verbose and less convenient. It can also create inconsistencies when different parts of the codebase use different syntaxes for the same type.
>
> ```python Bad theme={"theme":"css-variables"}
> from typing import Union
>
> def foo(arg: Union[int, str])  Union[int, str]:
> if isinstance(arg, int):
>     return arg + 1
> else:
>     return arg.upper()
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def foo(arg: int | str)  int | str:
> if isinstance(arg, int):
>     return arg + 1
> else:
>     return arg.upper()
> ```

> [accordion] Dictionarys setdefault should be used instead of checking key existence
>
> A common anti-pattern is to check that a key does not exist in a dictionary before adding it with a corresponding value. This pattern works but is less readable than the equivalent call to the built-in dictionary method "setdefault()".
>
> Note that if a default value is set for every key of the dictionary it is possible to use python’s `defaultdict` instead.
>
> This rule raises an issue when a key presence is checked before being set. It only raises an issue when the value is a hard-coded string, number, list, dictionary or tuple. Computed values will not raise an issue as they can have side-effects.
>
> ```python Bad theme={"theme":"css-variables"}
> if "key" not in my_dictionary:
> my_dictionary["key"] = ["a", "b", "c"]  # Noncompliant
>
> if "key" not in my_dictionary:
> my_dictionary["key"] = generate_value()  # Compliant. No issue is raised as generate_value() might have some side-effect.
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> my_dictionary.setdefault("key", ["a", "b", "c"])
>
> # OR, if ["a", "b", "c"] is the default value for every key
>
> from collections import defaultdict
> my_dictionary = defaultdict(lambda: ["a", "b", "c"])
> ```

> [accordion] Functions and lambdas should not reference variables defined in enclosing loops
>
> Nested functions and lambdas can reference variables defined in enclosing scopes. This can create tricky bugs when the variable and the function are defined in a loop. If the function is called in another iteration or after the loop finishes, it will see the variables' last value instead of seeing the values corresponding to the iteration where the function was defined.
>
> Capturing loop variables might work for some time but:
>
> <ul>
>   <li>
>     it makes the code difficult to understand.
>   </li>
>
>   <li>
>     it increases the risk of introducing a bug when the code is refactored or when dependencies are updated. See an example with the builtin "map" below.
>   </li>
> </ul>
>
> One solution is to add a parameter to the function/lambda and use the previously captured variable as its default value. Default values are only executed once, when the function is defined, which means that the parameter’s value will remain the same even when the variable is reassigned in following iterations.
>
> Another solution is to pass the variable as an argument to the function/lambda when it is called.
>
> This rule raises an issue when a function or lambda references a variable defined in an enclosing loop.
>
> ```python Bad theme={"theme":"css-variables"}
> def run():
> mylist = []
> for i in range(5):
>     mylist.append(lambda: i)  # Noncompliant
>
>     def func():
>         return i  # Noncompliant
>     mylist.append(func)
>
> def example_of_api_change():
> """"
> Passing loop variable as default values also makes sure that the code is future-proof.
> For example the following code will work as intended with python 2 but not python 3.
> Why? because "map" behavior changed. It now returns an iterator and only executes
> the lambda when required. The same is true for other functions such as "filter".
> """
> lst = []
> for i in range(5):
>     lst.append(map(lambda x: x + i, range(3)))  # Noncompliant
> for sublist in lst:
>     # prints [4, 5, 6] x 4 with python 3, with python 2 it prints [0, 1, 2], [1, 2, 3], ...
>     print(list(sublist))
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def run():
> mylist = []
> for i in range(5):
>     mylist.append(lambda i=i: i)  # passing the variable as a parameter with a default value
>
>     def func(i=i):  # same for nested functions
>         return i
>     mylist.append(func)
>
> def example_of_api_change():
> """"
> This will work for both python 2 and python 3.
> """
> lst = []
> for i in range(5):
>     lst.append(map(lambda x, value=i: x + value, range(3)))  # Passing "i" as a default value
> for sublist in lst:
>     print(list(sublist))
> ```

> [accordion] Type hints of generic types should specify their type parameters
>
> Generic types, such as list or dict accept type arguments to specify the type of elements contained in the list or the keys and values in the dictionary.
>
> If a generic type is used without a type argument, the type arguments will implicitly assumed to be Any. This makes the type hint less informative and makes the contract of the function or variable annotated with the type hint more difficult to understand.
>
> Furthermore, incomplete type hints can hinder IDE autocompletion and code insight capabilities of static analyis tools.
>
> ```python Bad theme={"theme":"css-variables"}
> def print_list(numbers: list)  None:
> for n in numbers:
>     print(n)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def print_list(numbers: list[int])  None:
> for n in numbers:
>     print(n)
> ```

> [accordion] Set members and dictionary keys should be hashable
>
> The hash value of an object is an integer returned by its \`**hash** method. Objects that are considered equal to each other (as per the **eq** method) should have the same hash value.
>
> Whenever using an object as a dictionary key or inserting it into a set, the hash value of that object will be used to derive a bucket in which the object will be inserted.
>
> When attempting to insert an unhashable object into a set, a TypeError will be raised instead.
>
> If an object defines a **hash** method derived from mutable properties, no TypeError\` will be raised. However, having a mutable hash value should never be done as this would prevent dictionaries and set from retrieving the object.
>
> ```python Bad theme={"theme":"css-variables"}
> def foo():
> my_list = [1,2,3]
> my_set = {my_list}  # Noncompliant: list is not hashable.
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def foo():
> my_list = [1,2,3]
> my_set = set(my_list) # This will insert the elements of my_list into a new set.
>
> # OR
>
> def foo():
> my_tuple = (1,2,3)
> my_set = {my_tuple} # tuples are immutable and hashable. They can be inserted into sets.
> ```

> [accordion] np.nonzero should be preferred over np.where when only the condition parameter is set
>
> The NumPy function `np.where` provides a way to execute operations on an array under a certain condition:
>
> ```python Bad theme={"theme":"css-variables"}
> import numpy as np
>
> arr = np.array([1,2,3,4])
>
> result = np.where(arr > 3, arr * 2, arr)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import numpy as np
>
> arr = np.array([1,2,3,4])
>
> result = np.where(arr > 2)
> ```

> [accordion] Methods and field names should not differ only by capitalization
>
> Looking at the set of methods and fields in a `class` and finding two that differ only by capitalization is confusing to users of the class.
>
> This situation may simply indicate poor naming. Method names should be action-oriented, and thus contain a verb, which is unlikely in the case where both a method and a field have the same name (with or without capitalization differences). However, renaming a public method could be disruptive to callers. Therefore renaming the member is the recommended action.
>
> ```python Bad theme={"theme":"css-variables"}
> class SomeClass:
> lookUp = false
> def lookup():       # Non-compliant; method name differs from field name only by capitalization
>     pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class SomeClass:
> lookUp = false
> def getLookUp():
>     pass
> ```

> [accordion] await should be used on awaitable objects
>
> The `await keyword can only be used on "Awaitable" objects. Python has three types of awaitables: Future, Task and Coroutines. Calling await on any other object will raise a TypeError`.
>
> ```python Bad theme={"theme":"css-variables"}
> import asyncio
>
> def myfunction():
> print("myfunction")
>
> async def otherfunction():
> await myfunction()  # Noncompliant. myfunction is not marked as "async"
>
> asyncio.run(otherfunction())
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import asyncio
>
> async def myfunction():
> print("myfunction")
>
> async def otherfunction():
> await myfunction()
>
> asyncio.run(otherfunction())
> ```

> [accordion] Dates should be formatted correctly when using pandas.to\_datetime with dayfirst or yearfirst arguments
>
> The pandas.to\_datetime function transforms a string to a date object. The string representation of the date can take multiple formats. To correctly parse these strings,
> pandas.to\_datetime provides several arguments to setup the parsing, such as dayfirst or yearfirst. For example setting dayfirst to True indicates to pandas.to\_datetime
> that the date and time will be represented as a string with the shape day month year time. Similarly with yearfirst, the string should have the following shape year month day time.
>
> These two arguments are not strict, meaning if the shape of the string is not the one expected by pandas.to\_datetime, the function will not fail and try to figure out which part of the string is the day, month or year.
>
> In the following example the dayfirst argument is set to True but we can clearly see that the month part of the date would be incorrect. In this case pandas.to\_datetime will ignore the dayfirst argument, and parse the date
> as the 22nd of January.
>
> ```python Bad theme={"theme":"css-variables"}
> import pandas as pd
>
> pd.to_datetime(["01-22-2000 10:00"], dayfirst=True)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import pandas as pd
>
> pd.to_datetime(["01-22-2000 10:00"], dayfirst=True) # Noncompliant: the second part of the date (22) is not a valid month
>
> pd.to_datetime(["02/03/2000 12:00"], yearfirst=True) # Noncompliant: the year is not the first part of the date
>
> pd.to_datetime(["03-14-2000 10:00"], dayfirst=True) # Noncompliant
> ```

> [accordion] Static methods should not have self or cls arguments
>
> Unlike class and instance methods, static methods don’t receive an implicit first argument. Nonetheless naming the first argument `self or clz` guarantees confusion - either on the part of the original author, who may never understand why the arguments don’t hold the values he expected, or on that of future maintainers.
>
> ```python Bad theme={"theme":"css-variables"}
> class MyClass:
> @staticmethod
> def s_meth(self, arg1, arg2):  #Noncompliant
> # ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyClass:
> @staticmethod
> def s_meth(arg1, arg2):  #Noncompliant
> # ...
> ```

> [accordion] Exceptions should not be created without being raised
>
> Creating a new `Exception` without actually raising it has no effect and is probably due to a mistake.
>
> ```python Bad theme={"theme":"css-variables"}
> def func(x):
> if not isinstance(x, int):
>     TypeError("Wrong type for parameter 'x'. func expects an integer")  # Noncompliant
> if x < 0:
>     ValueError  # Noncompliant
> return x + 42
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def func(x):
> if not isinstance(x, int):
>     raise TypeError("Wrong type for parameter 'x'. func expects an integer")
> if x < 0:
>     raise ValueError
> return x + 42
> ```

> [accordion] isinstance() should be preferred to direct type comparisons
>
> In Python, using the isinstance() function is generally preferred over direct type comparison for several reasons:
>
> <ol>
>   <li>
>     **Compatibility with inheritance:** isinstance() considers inheritance hierarchy, whereas direct type comparison does not. This means that isinstance() can handle cases where an object belongs to a subclass of the specified type, making your code more flexible and robust. It allows you to write code that can work with objects of different but related types.
>   </li>
>
>   <li>
>     **Support for duck typing:** Python follows the principle of "duck typing," which focuses on an object’s behavior rather than its actual type. isinstance() enables you to check if an object has certain behavior (by checking if it belongs to a particular class or subclass) rather than strictly requiring a specific type. This promotes code reusability and enhances the flexibility of your programs.
>   </li>
>
>   <li>
>     **Code maintainability and extensibility:** By using isinstance(), your code becomes more maintainable and extensible. If you directly compare types, you would need to modify your code whenever a new subtype is introduced or the inheritance hierarchy is changed. On the other hand, isinstance() allows your code to accommodate new types without requiring any modifications, as long as they exhibit the desired behavior.
>   </li>
>
>   <li>
>     **Polymorphism and interface-based programming:** isinstance() supports polymorphism, which is the ability of different objects to respond to the same method calls. It allows you to design code that interacts with objects based on their shared interface rather than their specific types. This promotes code reuse and modularity, as you can write functions and methods that operate on a range of compatible objects.
>   </li>
>
>   <li>
>     **Third-party library compatibility:** Many third-party libraries and frameworks in Python rely on isinstance() for type checking and handling different types of objects. By using isinstance(), your code becomes more compatible with these libraries and frameworks, making it easier to integrate your code into larger projects or collaborate with other developers.
>   </li>
> </ol>
>
> In summary, using isinstance() over direct type comparison in Python promotes flexibility, code reusability, maintainability, extensibility, and compatibility with the wider Python ecosystem. It aligns with the principles of object-oriented programming and supports the dynamic nature of Python. It is also recommended by the [PEP8](https://peps.python.org/pep-0008/) style guide.
>
> ```python Bad theme={"theme":"css-variables"}
> class MyClass:
> ...
>
> def foo(a):
> if type(a) == MyClass: # Noncompliant
> ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyClass:
> ...
>
> def foo(a):
> if isinstance(a, MyClass):
> ...
> ```

> [accordion] Boolean expressions of exceptions should not be used in except statements
>
> The only two possible types for an \`except's expression are a class deriving from BaseException, or a tuple composed of such classes.
>
> Trying to catch multiple exception in the same except with a boolean expression of exceptions may not work as intended.
> The result of a boolean expression of exceptions is a single exception class, thus using a boolean expression in an except\` block will result in catching only one kind of exception.
>
> ```python Bad theme={"theme":"css-variables"}
> error = ValueError or TypeError  
> error is ValueError # True
> error is TypeError # False
>
> error = ValueError and TypeError  
> error is ValueError # False
> error is TypeError # True
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> try:
> raise TypeError()
> except ValueError or TypeError:  # Noncompliant
> print("Catching only ValueError")
> except ValueError and TypeError:  # Noncompliant
> print("Catching only TypeError")
> except (ValueError or TypeError) as exception:  # Noncompliant
> print("Catching only ValueError")
>
> foo = ValueError or TypeError  # foo == ValueError
> foo = ValueError and TypeError  # foo == TypeError
> ```

> [accordion] Identity comparisons should not be used with cached types
>
> The identity operators `is and is not check if the same object is on both sides,
> i.e. a is b returns True if `++id(a)
>
> ```python Bad theme={"theme":"css-variables"}
> my_int = 1
> other_int = 1
>
> id(my_int) == id(other_int) # True
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> my_int = 1000
>
> id(my_int) == id(1000) # False
> my_int is 1000 # False
> ```

> [accordion] self should be the first argument to instance methods
>
> Instance methods, i.e. methods not annotated with \`@classmethod or @staticmethod, are expected to have at least one parameter. This parameter will reference the object instance on which the method is called. By convention, this first parameter is named "self".
>
> Naming the first parameter something different from "self" is not recommended as it could lead to confusion. It might indicate that the "self" parameter was forgotten, in which case calling the method will most probably fail.
>
> Note also that creating methods which are used as static methods without the @staticmethod decorator is a bad practice. Calling these methods on an instance will raise a TypeError. Either move the method out of the class or decorate it with @staticmethod\`.
>
> ```python Bad theme={"theme":"css-variables"}
> class MyClass(ABC):
> @myDecorator
> def method(arg):  # No issue will be raised.
>     pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyClass:
> def send_request(request):  # Noncompliant: the "self" parameter is missing.
>     print("send_request")
>
> class ClassWithStaticMethod:
> def static_method(param):  # Noncompliant: the "@staticmethod" decorator is missing.
>     print(param)
>
> ClassWithStaticMethod().static_method(42)  # The method is available on the instance but calling it will raise a TypeError.
> ```

> [accordion] New objects should not be created only to check their identity
>
> Identity operators `is and is not check if the same object is on both sides, i.e. a is b returns True if `++id(a)
>
> ```python Bad theme={"theme":"css-variables"}
> def func(param):
> param is {1: 2}  # Noncompliant: always False
> param is not {1, 2, 3}  # Noncompliant: always True
> param is [1, 2, 3]  # Noncompliant: always False
>
> param is dict(a=1)  # Noncompliant: always False
>
> mylist = []  # mylist is assigned a new object
> param is mylist  # Noncompliant: always False
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def func(param):
> param == {1: 2}
> param != {1, 2, 3}
> param == [1, 2, 3]
>
> param == dict(a=1)
>
> mylist = []
> param == mylist
> ```

> [accordion] startswith or endswith methods should be used instead of string slicing in condition expressions
>
> Using the startswith and endswith methods in Python instead of string slicing offers several advantages:
>
> <ol>
>   <li>
>     **Readability and Intent:** Using startswith and endswith methods provides code that is more readable and self-explanatory. It clearly communicates your intention to check if a string starts or ends with a specific pattern. This makes the code more maintainable and easier to understand for other developers.
>   </li>
>
>   <li>
>     **Flexibility:** The startswith and endswith methods allow you to check for patterns of varying lengths. With string slicing, you would need to specify the exact length of the substring to compare. However, with the methods, you can pass in a pattern of any length, making your code more flexible and adaptable.
>   </li>
>
>   <li>
>     **Error Handling:** The methods handle edge cases automatically. If you pass a substring length that exceeds the length of the original string, slicing would raise an IndexError exception. On the other hand, the methods gracefully handle such cases and return False, avoiding any potential errors.
>   </li>
>
>   <li>
>     **Performance Optimization:** In some cases, using startswith and endswith methods can provide better performance. These methods are optimized and implemented in C, which can make them faster than manually slicing the string in Python. Although the performance gain might be negligible for small strings, it can be significant when working with large strings or processing them in a loop.
>   </li>
> </ol>
>
> Overall, using startswith and endswith methods provides a cleaner, more readable, and error-resistant approach for checking if a string starts or ends with a specific pattern. It promotes code clarity, flexibility, and can potentially improve performance. This is also recommended by the [PEP8](https://peps.python.org/pep-0008/) style guide.
>
> ```python Bad theme={"theme":"css-variables"}
> message = "Hello, world!"
>
> if message[:5] == "Hello":
> ...
>
> if message[-6:] == "world!":
> ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> message = "Hello, world!"
>
> if message.startswith("Hello"):
> ...
>
> if message.endswith("world!"):
> ...
> ```

> [accordion] Increment and decrement operators should not be used
>
> Python has no pre/post increment/decrement operator. For instance, `x++ and x-- will fail to parse. More importantly, ++x and --x will do nothing. To increment a number, simply write x += 1`.
>
> ```python Bad theme={"theme":"css-variables"}
> ++x # Noncompliant: pre and post increment operators do not exist in Python.
>
> x-- # Noncompliant: pre and post decrement operators do not exist in Python.
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x += 1
>
> x -= 1
> ```

> [accordion] Bare raise statements should not be used in finally blocks
>
> A bare \`raise statement, i.e. a raise with no exception provided, will re-raise the last active exception in the current scope. If no exception is active a RuntimeError is raised instead.
>
> If the bare "raise" statement is in a finally block, it will only have an active exception to re-raise when an exception from the try block is not caught or when an exception is raised by an except or else block. Thus bare raise statements should not be relied upon in finally\` blocks. It is simpler to let the exception raise automatically.
>
> ```python Bad theme={"theme":"css-variables"}
> def foo(param):
> result = 0
> try:
>     print("foo")
> except ValueError as e:
>     pass
> else:
>     if param:
>         raise ValueError()
> finally:
>     if param:
>         raise  # Noncompliant: This will fail in some context.
>     else:
>         result = 1
> return result
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def foo(param):
> result = 0
> try:
>     print("foo")
> except ValueError as e:
>     pass
> else:
>     if param:
>         raise ValueError()
> finally:
>     if not param:
>         result = 1
> return result
> ```

> [accordion] **init** should not return a value
>
> By contract, every Python function returns something, even if it is the \`None value, which can be returned implicitly by omitting the return statement, or explicitly.
>
> The **init** method is required to return None. A TypeError will be raised if the **init** method either yields or returns any expression other than None. While explicitly returning an expression that evaluates to None will not raise an error, it is considered bad practice.
>
> To fix this issue, make sure that the **init**\` method does not contain any return statement.
>
> ```python Bad theme={"theme":"css-variables"}
> class MyClass(object):
> def __init__(self):
>     self.message = 'Hello'
>     return self  # Noncompliant: a TypeError will be raised
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyClass(object):
> def __init__(self):
>     self.message = 'Hello'
> ```

> [accordion] Redundant pairs of parentheses should be removed
>
> Parentheses can disambiguate the order of operations in complex expressions and make the code easier to understand.
>
> ```python Bad theme={"theme":"css-variables"}
> a = (b * c) + (d * e) # Compliant: the intent is clear.
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> return ((3))        # Noncompliant
> return ((x + 1))    # Noncompliant
> x = ((y / 2)) + 1   # Noncompliant
> ```

> [accordion] `str.replace` should be preferred to `re.sub`
>
> An re.sub call always performs an evaluation of the first argument as a regular expression, even if no regular expression features were used. This has a significant performance cost and therefore should be used with care.
>
> When re.sub is used, the first argument should be a real regular expression. If it’s not the case, str.replace does exactly the same thing as re.sub without the performance drawback of the regex.
>
> This rule raises an issue for each re.sub used with a simple string as first argument which doesn’t contains special regex character or pattern.
>
> ```python Bad theme={"theme":"css-variables"}
> init = "Bob is a Bird... Bob is a Plane... Bob is Superman!"
> changed = re.sub(r"Bob is", "It's", init) # Noncompliant
> changed = re.sub(r"\.\.\.", ";", changed) # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> init = "Bob is a Bird... Bob is a Plane... Bob is Superman!"
> changed = init.replace("Bob is", "It's")
> changed = changed.replace("...", ";")
> ```

> [accordion] Function return types should be consistent with their type hint
>
> Developers can use type hints to specify which type a function is expected to return. Doing so improves maintainability since it clarifies the contract of the function, making it easier to use and understand.
>
> When annotating a function with a specific type hint, it is expected that the returned value matches the type specified in the hint.
>
> If the type hint specifies a class or a named type, then the value returned should be an instance of that class or type. If the type hint specifies a structural type, then the value returned should have the same structure as the type hint.
>
> In the following example, while Bucket does not directly inherit from Iterable, it does implement the Iterable protocol thanks to its `iter method and can therefore be used as a valid Iterable` return type.
>
> ```python Bad theme={"theme":"css-variables"}
> from collections.abc import Iterator, Iterable
>
> class Bucket:  # Note: no base classes
> ...
> def __len__(self)  int: ...
> def __iter__(self)  Iterator[int]: ...
>
>
> def collect()  Iterable: return Bucket()
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def hello()  str:
> return 42  # Noncompliant: Function's type hint asks for a string return value
> ```

> [accordion] The abs\_tol parameter should be provided when using math.isclose to compare values to 0
>
> Comparing float values for equality directly is not reliable and should be avoided, due to the inherent imprecision in the binary representation of floating point numbers. Such comparison is reported by S1244.
>
> One common solution to this problem is to use the math.isclose function to perform the comparison. Behind the scenes, the math.isclose function uses a tolerance value (also called epsilon) to define an acceptable range of difference between two floats. A tolerance value may be relative (based on the magnitude of the numbers being compared) or absolute.
>
> Using a relative tolerance would be equivalent to:
>
> ```python Bad theme={"theme":"css-variables"}
> def isclose_relative(a, b, rel_tol=1e-09):
> diff = abs(a - b)
> max_diff = rel_tol * max(abs(a), abs(b))
> return diff <= max_diff
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def isclose_absolute(a, b, abs_tol=1e-09):
> diff = abs(a - b)
> return diff <= abs_tol
> ```

> [accordion] Identical expressions should not be used on both sides of a binary operator
>
> Using the same value on either side of a binary operator is almost always a mistake. In the case of logical operators, it is either a copy/paste error and therefore a bug, or it is simply wasted code, and should be simplified. In the case of bitwise operators and most binary mathematical operators, having the same value on both sides of an operator yields predictable results, and should be simplified.
>
> Note that this rule will raise issues on \`\`++a
>
> ```python Bad theme={"theme":"css-variables"}
> if a == a: # Noncompliant
> work()
>
> if  a != a: # Noncompliant
> work()
>
> if  a == b and a == b: # Noncompliant
> work()
>
> if a == b or a == b: # Noncompliant
> work()
>
> j = 5 / 5 # Noncompliant
> k = 5 - 5 # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] Floating point numbers should not be tested for equality
>
> Floating point math is imprecise because of the challenges of storing such values in a binary representation.
>
> In base 10, the fraction 1/3 is represented as 0.333…​ which, for a given number of significant digit, will never exactly be 1/3. The same problem happens when trying to represent 1/10 in base 2, with leads to the infinitely repeating fraction 0.0001100110011…​. This makes floating point representations inherently imprecise.
>
> Even worse, floating point math is not associative; push a \`float through a series of simple mathematical operations and the answer will be different based on the order of those operation because of the rounding that takes place at each step.
>
> Even simple floating point assignments are not simple, as can be vizualized using the format\` function to check for significant digits:
>
> ```python Bad theme={"theme":"css-variables"}
> >>> format(0.1, ".17g")
> '0.10000000000000001'
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> >>> my_float = 0.1
> >>> numerator, denominator = my_float.as_integer_ratio()
> >>> f"{numerator} / {denominator}"
> '3602879701896397 / 36028797018963968'
> ```

> [accordion] Only existing object members should be accessed
>
> Accessing a non-existing member on an object will raise in most case an `AttributeError` exception.
>
> This rule raises an issue when a non-existing member is accessed on a class instance and nothing indicates that this was expected.
>
> ```python Bad theme={"theme":"css-variables"}
> def access_attribute():
> x = 42
> return x.isnumeric()  # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def access_attribute():
> x = "42"
> return x.isnumeric()
> ```

> [accordion] Recursion should not be infinite
>
> Recursion happens when control enters a loop that has no exit. This can happen when a method invokes itself or when a pair of methods invoke each other. It can be a useful tool, but unless the method includes a provision to break out of the recursion and `return`, the recursion will continue until the stack overflows and the program crashes.
>
> ```python Bad theme={"theme":"css-variables"}
> def my_pow(num, exponent):  # Noncompliant
> num = num * my_pow(num, exponent - 1)
> return num  # this is never reached
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def my_pow(num, exponent):  # Compliant
> if exponent > 1:
>   num = num * my_pow(num, exponent - 1)
> return num
> ```

> [accordion] Custom Exception classes should inherit from Exception or one of its subclasses
>
> [\`SystemExit](https://docs.python.org/3/library/exceptions.html#SystemExit) is raised when [sys.exit()](https://docs.python.org/3/library/sys.html#sys.exit) is called. [KeyboardInterrupt](https://docs.python.org/3/library/exceptions.html#KeyboardInterrupt) is raised when the user asks the program to stop by pressing interrupt keys. Both exceptions are expected to propagate up until the application stops.
>
> In order to avoid catching SystemExit and KeyboardInterrupt by mistake, [PEP-352](https://www.python.org/dev/peps/pep-0352/#exception-hierarchy) created the root class BaseException from which SystemExit, KeyboardInterrupt and Exception derive. Thus developers can use except Exception: without preventing the software from stopping.
>
> The GeneratorExit class also derives from BaseException as it is not really an error and is not supposed to be caught by user code.
>
> As said in [Python’s documentation](https://docs.python.org/3/library/exceptions.html#BaseException), user-defined exceptions are not supposed to inherit directly from BaseException. They should instead inherit from Exception\` or one of its subclasses.
>
> ```python Bad theme={"theme":"css-variables"}
> class MyException(BaseException):  # Noncompliant
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyException(Exception):
> pass
> ```

> [accordion] Comparison to None should not be constant
>
> Checking if a variable or parameter is None should only be done when you expect that it can be None. Doing so when the variable is always None or never None is confusing at best. At worse, there is a bug and the variable is not updated properly.
>
> This rule raises an issue when expressions X is None, X is not None, \`X
>
> ```python Bad theme={"theme":"css-variables"}
> def foo():
> my_var = None
> if my_var == None:  # Noncompliant: always True.
>     ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def foo(my_var):
> if my_var == None:
>     ...
> ```

> [accordion] Iterator classes should have a valid **iter** method
>
> The [iterator protocol](https://www.python.org/dev/peps/pep-0234/#python-api-specification) specifies that an iterator object should have
>
> <ul>
>   <li>
>     a \`**next** method retrieving the next value or raising StopIteration when there are no more values left.
>   </li>
>
>   <li>
>     an **iter** method which should always return self. This enables iterators to be used as sequences in for-loops and other places.
>   </li>
> </ul>
>
> This rule raises an issue when a class has a **next** method and either:
>
> <ul>
>   <li>
>     it doesn’t have an **iter** method.
>   </li>
>
>   <li>
>     or its **iter**\` method does not return "self".
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> class MyIterator:  # Noncompliant. Class has a __next__ method but no __iter__ method
>
> def __init__(self, values):
>     self._values = values
>     self._index = 0
>
> def __next__(self):
>     if self._index >= len(self._values):
>         raise StopIteration()
>     value = self._values[self._index]
>     self._index += 1
>     return value
>
>
> class MyIterator:
> def __init__(self, values):
>     self._values = values
>     self._index = 0
>
> def __next__(self):
>     if self._index >= len(self._values):
>         raise StopIteration()
>     value = self._values[self._index]
>     self._index += 1
>     return value
>
> def __iter__(self):
>     return 42  # Noncompliant. This __iter__ method does not return self
>
>
> class MyIterable:  # Ok. This is an iterable, not an iterator, i.e. it has an __iter__ method but no __next__ method. Thus __iter__ doesn't have to return "self"
>
> def __init__(self, values):
>     self._values = values
>
> def __iter__(self):
>     return MyIterator(self._values)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyIterator:
> def __init__(self, values):
>     self._values = values
>     self._index = 0
>
> def __next__(self):
>     if self._index >= len(self._values):
>         raise StopIteration()
>     value = self._values[self._index]
>     self._index += 1
>     return value
>
> def __iter__(self):
>     return self
>
> class MyIterable:
> def __init__(self, values):
>     self._values = values
>
> def __iter__(self):
>     return MyIterator(self._values)
> ```

> [accordion] Dictionarys get(..., default) should be used instead of checking key existence
>
> A common anti-pattern is to check that a key exists in a dictionary before retrieving its corresponding value and providing a default value otherwise. This pattern works but is less readable than the equivalent call to the built-in dictionary method "get()" with a default value.
>
> Note that if a default value is set for every key of the dictionary it is possible to use python’s defaultdict instead.
>
> This rule raises an issue when a key presence is checked before retrieving its value or providing a default value. It only raises an issue when the default value is a hard-coded string, number, list, dictionary or tuple. Computed values will not raise an issue as they can have side-effects.
>
> ```python Bad theme={"theme":"css-variables"}
> result = "default"
> if "missing" in mydict:
> result = mydict["missing"]  # Noncompliant
>
> if "missing" in mydict:
> result = mydict["missing"]  # Noncompliant
> else:
> result = "default"
>
> if "missing" in mydict:
> result = mydict["missing"]  # Compliant. No issue is raised as generate_value() might have some side-effect.
> else:
> result = generate_value()
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> result = mydict.get("missing", "default")
>
> # OR, if "default" is the default value for every key
>
> from collections import defaultdict
> mydict = defaultdict(lambda: "default")
> result =  mydict["missing"]
> ```

> [accordion] Equality checks should not be made against numpy.nan
>
> The \`numpy.nan is a floating point representation of Not a Number (NaN) used as a placeholder for undefined or missing values in numerical computations.
>
> Equality checks of variables against numpy.nan in NumPy will always be False due to the special nature of numpy.nan. This can lead to unexpected and incorrect results.
>
> Instead of standard comparison the numpy.isnan()\` function should be used.
>
> ```python Bad theme={"theme":"css-variables"}
> import numpy as np
>
> x = np.nan
>
> if x == np.nan: # Noncompliant: always False
> ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import numpy as np
>
> x = np.nan
>
> if np.isnan(x):
> ...
> ```

> [accordion] NotImplemented should not be raised
>
> `NotImplemented is a constant which is intended to be used only by comparison methods such as lt. Use it instead of  NotImplementedError`, which is an exception, and callers will have a hard time using your code.
>
> ```python Bad theme={"theme":"css-variables"}
> class MyClass:
> def do_something(self):
>     raise NotImplemented("Haven't gotten this far yet.")  #Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyClass:
> def do_something(self):
>     raise NotImplementedError("Haven't gotten this far yet.")
> ```

> [accordion] Back references in regular expressions should only refer to capturing groups that are matched before the reference
>
> When a back reference in a regex refers to a capturing group that hasn’t been defined yet (or at all), it can never be matched and will  fail with an re.error exception
>
> ```python Bad theme={"theme":"css-variables"}
> import re
> pattern1 = re.compile(r"\1(.)") # Noncompliant, group 1 is defined after the back reference
> pattern2 = re.compile(r"(.)\2") # Noncompliant, group 2 isn't defined at all
> pattern3 = re.compile(r"(.)|\1") # Noncompliant, group 1 and the back reference are in different branches
> pattern4 = re.compile(r"(?P<x>.)|(?P=x)") # Noncompliant, group x and the back reference are in different branches
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import re
> pattern1 = re.compile(r"(.)\1")
> pattern2 = re.compile(r"(?P<x>.)(?P=x)")
> ```

> [accordion] Non-existent operators like =+ should not be used
>
> Using operator pairs (`=+ or =-) that look like reversed single operators (+= or -=`) is confusing. They compile and run but do not produce the same result as their mirrored counterpart.
>
> ```python Bad theme={"theme":"css-variables"}
> target = -5
> num = 3
>
> target =- num  # Noncompliant: target = -3. Is that really what's meant?
> target =+ num # Noncompliant: target = 3
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> target = -5
> num = 3
>
> target -= num  # target = -8
> ```

> [accordion] Unused private nested classes should be removed
>
> "Private" nested classes that are never used inside the enclosing class are usually dead code: unnecessary, inoperative code that should be removed. Cleaning out dead code decreases the size of the maintained codebase, making it easier to understand the program and preventing bugs from being introduced.
>
> Python has no real private classes. Every class is accessible. There are however two conventions indicating that a class is not meant to be "public":
>
> <ul>
>   <li>
>     classes with a name starting with a single underscore (ex: \`\_MyClass) should be seen as non-public and might change without prior notice. They should not be used by third-party libraries or software. It is ok to use those classes inside the library defining them but it should be done with caution.
>   </li>
>
>   <li>
>     "class-private" classes are defined inside another class, and have a name starting with at least two underscores and ending with at most one underscore. These classes' names will be automatically mangled to avoid collision with subclasses' nested classes. For example \_\_MyClass will be renamed as \_classname\_\_MyClass, where classname\` is the enclosing class’s name without its leading underscore(s). Class-Private classes shouldn’t be used outside of their enclosing class.
>   </li>
> </ul>
>
> This rule raises an issue when a private nested class (either with one or two leading underscores) is never used inside its parent class.
>
> ```python Bad theme={"theme":"css-variables"}
> class TopLevel:
> class __Nested():  # Noncompliant: __Nested is never used
>     pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class TopLevel:
> class __Nested():
>     pass
>
> def process(self):
>     return TopLevel.__Nested()
> ```

> [accordion] When using pandas.merge or pandas.join, the parameters on, how and validate should be provided
>
> The Pandas library provides a user-friendly API to concatenate two data frames together with the methods \`merge and join.
>
> When using these methods, it is possible to specify how the merge will be performed:
>
> <ul>
>   <li>
>     The parameter how specifies the type of merge (left, inner, outer, etc..).
>   </li>
>
>   <li>
>     The parameter on specifies the column(s) on which the merge will be performed.
>   </li>
>
>   <li>
>     The parameter validate\` specifies a way to verify if the merge result is what was expected.
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> import pandas as pd
>
> age_df = pd.DataFrame({"user_id":[1,2,4], "age":[42,45, 35]})
> name_df = pd.DataFrame({"user_id":[1,2,3,4], "name":["a","b","c","d"]})
>
> result = age_df.merge(name_df, on="user_id", how="right", validate="1:1")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import pandas as pd
>
> age_df = pd.DataFrame({"user_id":[1,2,4], "age":[42,45, 35]})
> name_df = pd.DataFrame({"user_id":[1,2,3,4], "name":["a","b","c","d"]})
>
> result = age_df.merge(name_df)
> ```

> [accordion] Numpy weekmask should have a valid value
>
> To allow a datetime to be used in contexts where only certain days of the week are valid, NumPy includes a set of business day functions. Weekmask is used to customize valid business days.
>
> Weekmask can be specified in several formats:
>
> <ol>
>   <li>
>     As an array of 7 1 or 0 values, e.g. \[1, 1, 1, 1, 1, 0, 0]
>   </li>
>
>   <li>
>     As a string of 7 1 or 0 characters, e.g. "1111100"
>   </li>
>
>   <li>
>     As a string with abbreviations of valid days from this list: Mon Tue Wed Thu Fri Sat Sun, e.g. "Mon Tue Wed Thu Fri"
>   </li>
> </ol>
>
> Setting an incorrect weekmask leads to ValueError.
>
> ```python Bad theme={"theme":"css-variables"}
> import numpy as np
>
> offset = np.busday_offset('2012-05', 1, roll='forward', weekmask='01') # Noncompliant: ValueError
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import numpy as np
>
> offset = np.busday_offset('2012-05', 1, roll='forward', weekmask='0111100') # OK
> ```

> [accordion] ExceptionGroup and BaseExceptionGroup should not be caught with except\*
>
> Python 3.11 introduced \`except\* and ExceptionGroup, making it possible to handle and raise multiple unrelated exceptions simultaneously.
>
> In the example below, we gather multiple exceptions in an ExceptionGroup. This ExceptionGroup\` is then caught by a single except block:
>
> ```python Bad theme={"theme":"css-variables"}
> try:
> exception_group = ExceptionGroup("Files not found", [FileNotFoundError("file1.py"), FileNotFoundError("file2.py")])
>
> raise exception_group
>
> except ExceptionGroup as exceptions:
> # Do something with all the exceptions
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> try:
> exception_group = ExceptionGroup("Operation errors", [ValueError("Value bigger than 100"), TypeError("Type str is not allowed")])
>
> raise exception_group
>
> except* ValueError as v:
> # Do something with only ValueErrors
> pass
>
> except* TypeError as t:
> # Do something with only TypeErrors
> pass
> ```

> [accordion] All code should be reachable
>
> Jump statements (`return, break, continue, and raise`) move control flow out of the current code block. So any statements that come after a jump are dead code.
>
> ```python Bad theme={"theme":"css-variables"}
> def fun(a):
> i = 10
> return i + a       # Noncompliant 
> i += 1             # this is never executed
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def fun(a):
> i = 10
> return i + a
> ```

> [accordion] Fields of a Django ModelFom should be defined explicitly
>
> In Django, when creating a ModelForm, it is common to use exclude to remove fields from the form. It is also possible to set the fields value to `all to conveniently indicate that all the model fields should be included in the form. However, this can lead to security issues when new fields are added to the model, as they will automatically be included in the form, which may not be intended. Additionally, exclude or all` can make it harder to maintain the codebase by hiding the dependencies between the model and the form.
>
> ```python Bad theme={"theme":"css-variables"}
> from django import forms
>
> class MyForm(forms.ModelForm):
> class Meta:
>     model = MyModel
>     exclude = ['field1', 'field2']  # Noncompliant
>
>
> class MyOtherForm(forms.ModelForm):
> class Meta:
>     model = Post
>     fields = '__all__'  # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from django import forms
>
> class MyForm(forms.ModelForm):
> class Meta:
>     model = MyModel
>     fields = ['field3', 'field4']
> ```

> [accordion] Conditionally executed code should be reachable
>
> Unreachable code is never executed, so it has no effect on the behaviour of the program.
> If it is not executed because it no longer serves a purpose, then it adds unnecessary complexity.
> Otherwise, it indicates that there is a logical error in the condition.
>
> ```python Bad theme={"theme":"css-variables"}
> def foo(a, b):
> flag = True
>
> if (a and not a):  # Noncompliant
>     doSomething()  # Never executed
>
> if (flag): # Noncompliant
>     return "Result 1"
> return "Result 2" # Never executed
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def foo(a, b):
> if (a and not b):
>     doSomething()
>
> return "Result 1"
> ```

> [accordion] Functions, methods and lambdas should not have too many mandatory parameters
>
> Function, methods and lambdas should not have too many mandatory parameters, i.e. parameters with no default value. Calling them will require code difficult to read and maintain. To solve this problem you could wrap some parameters in an object, split the function into simpler functions with less parameters or provide default values for some parameters.
>
> ```python Bad theme={"theme":"css-variables"}
> def do_something(param1, param2, param3, param4, param5):  # Noncompliant
> ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def do_something(param1, param2, param3, param4):
> ...
>
> # Or
>
> def do_something(param1, param2, param3, param4, param5="a default value"):
> ...
> ```

> [accordion] List comprehensions should be used
>
> There are several ways to create a new list based on the elements of some other collection, but the use of a list comprehension has multiple benefits. First, it is both concise and readable, and second, it yields a fully-formed object without requiring a mutable object as input that must be updated multiple times in the course of the list creation.
>
> ```python Bad theme={"theme":"css-variables"}
> squares = []
> for x in range(10):
> squares.append(x**2)  # Noncompliant
>
> squares = map(lambda x: x**2, range(10))  #Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> squares = [x**2 for x in range(10)]
> ```

> [accordion] zoneinfo should be preferred to pytz when using Python 3.9 and later
>
> In Python 3.9 and later, the zoneinfo module is the recommended tool for handling timezones, replacing the pytz library. This recommendation is based on several key advantages.
>
> First, zoneinfo is part of Python’s standard library, making it readily available without needing additional installation, unlike pytz.
>
> Second, zoneinfo integrates seamlessly with Python’s datetime module. You can directly use zoneinfo timezone objects when creating datetime objects, making it more intuitive and less error-prone than pytz, which requires a separate localize method for this purpose.
>
> Third, zoneinfo handles historical timezone changes more accurately than pytz. When a pytz timezone object is used, it defaults to the earliest known offset, which can lead to unexpected results. zoneinfo does not have this issue.
>
> Lastly, zoneinfo uses the system’s IANA time zone database when available, ensuring it works with the most up-to-date timezone data. In contrast, pytz includes its own copy of the IANA database, which may not be as current.
>
> In summary, zoneinfo offers a more modern, intuitive, and reliable approach to handling timezones in Python 3.9 and later, making it the preferred choice over pytz.
>
> ```python Bad theme={"theme":"css-variables"}
> from datetime import datetime
> import pytz
>
> dt = pytz.timezone('America/New_York').localize(datetime(2022, 1, 1))  # Noncompliant: the localize method is needed to avoid bugs (see S6887)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from datetime import datetime
> from zoneinfo import ZoneInfo
>
> dt = datetime(2022, 1, 1, tzinfo=ZoneInfo('America/New_York'))  # OK: timezone object can be used safely through the datetime constructor
> ```

> [accordion] Collection sizes and array length comparisons should make sense
>
> The length of a collection is always greater than or equal to zero. Testing it doesn’t make sense, since the result is always `true`.
>
> ```python Bad theme={"theme":"css-variables"}
> mylist = []
> if len(myList) >= 0:  # Noncompliant: always true
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] SystemExit should be re-raised
>
> A [\`SystemExit](https://docs.python.org/3/library/exceptions.html#SystemExit) exception is raised when [sys.exit()](https://docs.python.org/3/library/sys.html#sys.exit) is called.
> This exception is used to signal the interpreter to exit. The exception is expected to propagate up until the program stops.
> It is possible to catch this exception in order to perform, for example, clean-up tasks. It should, however, be raised again to allow the interpreter to exit as expected.
> Not re-raising such exception could lead to undesired behaviour.
>
> A [bare except: statement](https://docs.python.org/3/reference/compound_stmts.html#the-try-statement), i.e. an except block without any exception class, is equivalent to [except BaseException](https://docs.python.org/3/library/exceptions.html#BaseException).
> Both statements will catch every exceptions, including SystemExit. It is recommended to catch instead a more specific exception.
> If it is not possible, the exception should be raised again.
>
> It is also a good idea to re-raise the [KeyboardInterrupt](https://docs.python.org/3/library/exceptions.html#KeyboardInterrupt) exception. Similarly to SystemExit,KeyboardInterrupt\` is used to signal the interpreter to exit. Not re-raising such exception could also lead to undesired behaviour.
>
> ```python Bad theme={"theme":"css-variables"}
> try:
> ...
> except SystemExit:  # Noncompliant: the SystemExit exception is not re-raised.
> pass
>
> try:
> ...
> except BaseException:  # Noncompliant: BaseExceptions encompass SystemExit exceptions and should be re-raised.
> pass
>
> try:
> ...
> except:  # Noncompliant: exceptions caught by this statement should be re-raised or a more specific exception should be caught.
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> try:
> ...
> except SystemExit as e:
> ...
> raise e
>
> try:
> ...
> except BaseException as e:
> ...
> raise e
>
> try:
> ...
> except FileNotFoundError:
> ... # Handle a more specific exception
> ```

> [accordion] inplace=True should not be used when modifying a Pandas DataFrame
>
> Using inplace=True when modifying a Pandas DataFrame means that the method will modify the DataFrame in place, rather than returning a new object:
>
> ```python Bad theme={"theme":"css-variables"}
> df.an_operation(inplace=True)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> df2 = df.an_operation(inplace=False)
> ```

> [accordion] Silly equality checks should not be made
>
> In some cases a comparison with operators \`==, or != will always return True or always return False. When this happens, the comparison and all its dependent code can simply be removed. This includes:
>
> <ul>
>   <li>
>     comparing unrelated builtin types such as string and integer.
>   </li>
>
>   <li>
>     comparing class instances which do not implement **eq** or **ne** to an object of a different type (builtin or from an unrelated class which also doesn’t implement **eq** or **ne**\`).
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> foo = 1 == "1"  # Noncompliant. Always False.
>
> foo = 1 != "1"  # Noncompliant. Always True.
>
> class A:
> pass
>
> myvar = A() == 1  # Noncompliant. Always False.
> myvar = A() != 1  # Noncompliant. Always True.
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> foo = 1 == int("1")
>
> foo = str(1) != "1"
>
> class Eq:
> def __eq__(self, other):
>     return True
>
> myvar = Eq() == 1
> myvar = 1 == Eq()
> myvar = Eq() != 1  # Ok. "__ne__" calls "__eq__" by default
> myvar = 1 != Eq()
> ```

> [accordion] Assertions should not fail or succeed unconditionally
>
> Assertions are meant to detect when code behaves as expected. An assertion which fails or succeeds all the time does not achieve this. Either it is redundant and should be removed to improve readabity or it is a mistake and the assertion should be corrected.
>
> This rule raises an issue when an assertion method is given parameters which will make it succeed or fail all the time. It covers three cases:
>
> <ul>
>   <li>
>     an \`assert statement or a unittest’s assertTrue or assertFalse method is called with a value which will be always True or always False.
>   </li>
>
>   <li>
>     a unittest’s assertIsNotNone or assertIsNone method is called with a value which will always be None or never be None.
>   </li>
>
>   <li>
>     a unittest’s assertIsNot or assertIs method is called with a literal expression creating a new object every time (ex: \[1, 2, 3]\`).
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> import unittest
>
> class MyTestCase(unittest.TestCase):
> def expect_not_none(self):
>     self.assertIsNotNone(round(1.5))  # Noncompliant: This assertion always succeeds because "round" returns a number, not None.
>
> def helper_compare(param):
>     self.assertIs(param, [1, 2, 3])  # Noncompliant: This assertion always fails because [1, 2, 3] creates a new object.
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import unittest
>
> class MyTestCase(unittest.TestCase):
> def expect_not_none(self):
>     self.assertNotEqual(round(1.5), 0)
>
> def helper_compare(param):
>     self.assertEqual(param, [1, 2, 3])
> ```

> [accordion] Function parameters initial values should not be ignored
>
> While it is technically correct to assign to parameters from within function bodies, doing so before the parameter value is read is likely a bug. Instead, initial values of parameters should be, if not treated as read-only, then at least read before reassignment.
>
> ```python Bad theme={"theme":"css-variables"}
> def foo(strings, param):
> param = 1  # NonCompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] The method **ne** should not be implemented without also implementing **eq**
>
> Implementing the special method \`**ne** is not equivalent to implementing the special method **eq**. By default **ne** will call **eq**, but the default implementation of **eq** does not call **ne**.
>
> This rule raises an issue when the special method **ne** is implemented but not the **eq**\` method.
>
> ```python Bad theme={"theme":"css-variables"}
> class Ne:
> def __ne__(self, other):   # Noncompliant.
>     return False
>
> myvar = Ne() == 1  # False. __ne__ is not called
> myvar = 1 == Ne()  # False. __ne__ is not called
> myvar = Ne() != 1  # False
> myvar = 1 != Ne()  # False
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> # Recommended, as __ne__ delegates to __eq__ by default
> class Eq:
> def __eq__(self, other):
>     return True
>
> myvar = Eq() == 1  # True
> myvar = 1 == Eq()  # True
> myvar = Eq() != 1  # False. __eq__ is called
> myvar = 1 != Eq()  # False. __eq__ is called
>
> # OR if __ne__ needs a special implementation
>
> class Eq:
> def __eq__(self, other):
>     return True
>
> def __ne__(self, other):
>     return False
> ```

> [accordion] **iter** should return an iterator
>
> An [iterable](https://docs.python.org/3/glossary.html#term-iterable) object is an object capable of returning its members one at a time. To do so, it must define an \`**iter** method that returns an iterator.
>
> The [iterator protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types) specifies that, in order to be a valid iterator, an object must define a **next** and an **iter** method (because iterators are also iterable).
>
> Defining an **iter** method that returns anything else than an iterator will raise a TypeError as soon as the iteration begins.
>
> Note that [generators](https://docs.python.org/3/tutorial/classes.html#generators) and [generator expressions](https://docs.python.org/3/tutorial/classes.html#generator-expressions) have both **next** and **iter**\` methods generated automatically.
>
> ```python Bad theme={"theme":"css-variables"}
> class MyIterable:
> def __init__(self, values):
>     self._values = values
>
> def __iter__(self):
>     return None  # Noncompliant: Not a valid iterator
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyIterable:
> def __init__(self, values):
>     self._values = values
>
> def __iter__(self):
>     return MyIterator(self._values)
>
> class MyIterator:
> def __init__(self, values):
>     self._values = values
>     self._index = 0
>
> def __next__(self):
>     if self._index >= len(self._values):
>         raise StopIteration()
>     value = self._values[self._index]
>     self._index += 1
>     return value
>
> def __iter__(self):
>     return self
> ```

> [accordion] \ should only be used as an escape character outside of raw strings
>
> Typically, backslashes are seen only as part of escape sequences. Therefore, the use of a backslash outside of a raw string or escape sequence looks suspiciously like a broken escape sequence.
>
> Characters recognized as escape-able are: `abfnrtvox'"`
>
> ```python Bad theme={"theme":"css-variables"}
> s = "Hello \world."
> t = "Nice to \ meet you"
> u = "Let's have \ lunch"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> s = "Hello world."
> t = "Nice to \\ meet you"
> u = r"Let's have \ lunch"  // raw string
> ```

> [accordion] Unread private attributes should be removed
>
> Python has no real private attribute. Every attribute is accessible. There are however two conventions indicating that an attribute is not meant to be "public":
>
> <ul>
>   <li>
>     attributes with a name starting with a single underscore (ex: \`\_myattribute) should be seen as non-public and might change without prior notice. They should not be used by third-party libraries or software. It is ok to use those methods inside the library defining them but it should be done with caution.
>   </li>
>
>   <li>
>     "class-private" attributes have a name starting with at least two underscores and ending with at most one underscore. These attributes' names will be automatically mangled to avoid collision with subclasses' attributes. For example \_\_myattribute will be renamed as \_classname\_\_myattribute, where classname\` is the attribute’s class name without its leading underscore(s). They shouldn’t be used outside of the class defining the attribute.
>   </li>
> </ul>
>
> This rule raises an issue when a class-private attribute (two leading underscores, max one underscore at the end) is never read inside the class. It optionally raises an issue on unread attributes prefixed with a single underscore. Both class attributes and instance attributes will raise an issue.
>
> ```python Bad theme={"theme":"css-variables"}
> class Noncompliant:
> _class_attr = 0  # Noncompliant if enable_single_underscore_issues is enabled
> __mangled_class_attr = 1  # Noncompliant
>
> def __init__(self, value):
>     self._attr = 0  # Noncompliant if enable_single_underscore_issues is enabled
>     self.__mangled_attr = 1  # Noncompliant
>
> def compute(self, x):
>     return x * x
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Compliant:
> _class_attr = 0
> __mangled_class_attr = 1
>
> def __init__(self, value):
>     self._attr = 0
>     self.__mangled_attr = 1
>
> def compute(self, x):
>     return x * Compliant._class_attr * Compliant.__mangled_class_attr * self._attr * self.__mangled_attr
> ```

> [accordion] Unpacking should be done with the same number of elements of the iterable.
>
> In Python, the unpacking assignment is a powerful feature that allows you to assign multiple values to multiple variables in a single statement.
>
> The basic rule for the unpacking assignment is that the number of variables on the left-hand side must be equal to the number of elements in the iterable. If this is not respected, a `ValueError` will be produced at runtime.
>
> ```python Bad theme={"theme":"css-variables"}
> def foo(param):
> ls = [1, 2, 3]
> x, y = ls # Noncompliant: 'ls' contains more elements than there are variables on the left-hand side
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def foo(param):
> ls = [1, 2, 3]
> x, y, z = ls
> ```

> [accordion] The axis argument should be specified when using TensorFlows reduction operations
>
> The result of TensorFlow’s reduction operations (i.e. `tf.math.reduce_sum, tf.math.reduce_std`),
> highly depends on the shape of the Tensor provided.
>
> ```python Bad theme={"theme":"css-variables"}
> import tensorflow as tf
>
> x = tf.constant([[1, 1, 1], [1, 1, 1]])
> tf.math.reduce_sum(x)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import tensorflow as tf
>
> x = tf.constant([[1, 1, 1], [1, 1, 1]])
> tf.math.reduce_sum(x, axis=0)
> ```

> [accordion] Caught Exceptions must derive from BaseException
>
> In Python 3’s except statement, attempting to catch an object that does not derive from BaseException will raise a TypeError.
>
> In order to catch multiple exceptions in an except statement, a tuple of exception classes should be provided. Trying to catch multiple exceptions with a list or a set will raise a TypeError.
>
> If you are about to create a custom exception class, note that custom exceptions should inherit from \`Exception, rather than BaseException.
>
> BaseException is the base class for all built-in exceptions in Python, including system-exiting exceptions like SystemExit or KeyboardInterrupt, which are typically not meant to be caught. On the other hand, Exception is intended for exceptions that are expected to be caught, which is generally the case for user-defined exceptions. See [PEP 352](https://www.python.org/dev/peps/pep-0352/#exception-hierarchy-changes) for more information.
>
> To fix this issue, make sure the expression used in an except statement is an exception which derives from BaseException/Exception\` or a tuple of such exceptions.
>
> ```python Bad theme={"theme":"css-variables"}
> class CustomException(object):
> """An Invalid exception class."""
> pass
>
> try:
> ...
> except CustomException:  # Noncompliant: this custom exception does not derive from BaseException or Exception.
> print("exception")
>
> try:
> ...
> except [TypeError, ValueError]:  # Noncompliant: list of exceptions, only tuples are valid.
> print("exception")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class CustomException(Exception):
> pass
>
> try:
> ...
> except CustomException: 
> print("exception")
>
> try:
> ...
> except (TypeError, ValueError):
> print("exception")
> ```

> [accordion] Only strings should be listed in **all**
>
> The `all property of a module is used to define the list of names that will be imported when performing a wildcard import of this module, i.e. when from mymodule import *` is used.
>
> In the following example:
>
> ```python Bad theme={"theme":"css-variables"}
> # mymodule.py
> def foo(): ...
> def bar(): ...
> __all__ = ["foo"]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyClass:
> pass
>
> __all__ = [
> MyClass  # Noncompliant: wildcard import will raise a TypeError
> ]
> ```

> [accordion] **slots** should not be used in old-style classes
>
> A class without an explicit extension of object (`class ClassName(object)) is considered an old-style class, and slots` declarations are ignored in old-style classes. Having such a declaration in an old-style class could be confusing for maintainers and lead them to make false assumptions about the class.
>
> ```python Bad theme={"theme":"css-variables"}
> class A:
> __slots__ = ["id"]  # Noncompliant; this is ignored
>
> def __init__(self):
> self.id = id
> self.name = "name"  # name wasn't declared in __slots__ but there's no error
>
> a = A()
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class A(object):  # Converting to a new-style class is the preferred method of addressing this issue
> __slots__ = ["id"]
>
> def __init__(self):
> self.id = id
> self.name = "name"  # "name" is not listed in __slots__, so as expected there is an error in this line
>
> a = A()
> ```

> [accordion] Function returns should have type hints
>
> Being a dynamically typed language, the Python interpreter only does type checking during runtime. Getting the typing right is important as certain operations may result in a TypeError.
>
> Type hints can be used to clarify the expected return type of a function, enabling developers to better document its contract. Applying them consistently makes the code easier to read and understand.
>
> In addition, type hints allow some development environments to offer better autocompletion and improve the precision of static analysis tools.
>
> ```python Bad theme={"theme":"css-variables"}
> def hello(name):
> return 'Hello ' + name
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def hello(name)  str:
> return 'Hello ' + name
> ```

> [accordion] Method names should comply with a naming convention
>
> Shared naming conventions allow teams to collaborate efficiently.
>
> This rule raises an issue when a method name does not match a provided regular expression.
>
> For example, with the default provided regular expression `^[a-z_][a-z0-9_]*$`, the method:
>
> ```python Bad theme={"theme":"css-variables"}
> class MyClass:
> def MyMethod(a,b): # Noncompliant
>     ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyClass:
> def my_method(a,b):
>     ...
> ```

> [accordion] Django models should define a **str** method
>
> The `str` method in Django models is used to represent the model instance as a string. For example, the return value of this method will be inserted in a template when displaying an object in the Django admin site. Without this method, the model instance will be represented by its object identifier, which is not meaningful to end-users. This can result in confusion and make debugging more difficult.
>
> ```python Bad theme={"theme":"css-variables"}
> from django.db import models
>
> class MyModel(models.Model):
> name = models.CharField(max_length=100)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from django.db import models
>
> class MyModel(models.Model):
> name = models.CharField(max_length=100)
>
> def __str__(self):
>     return self.name
> ```

> [accordion] Doubled prefix operators not and \~ should not be used
>
> The repetition of a prefix operator (`not or ~`) is usually a typo. The second operator invalidates the first one:
>
> ```python Bad theme={"theme":"css-variables"}
> a = False
> b = ~~a # Noncompliant: equivalent to "a"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> a = 0
>
> b = not not a # Noncompliant: use bool()
> ```

> [accordion] Type checks shouldnt be confusing
>
> Checking that variable X has type T with [type annotations](https://docs.python.org/3/library/typing.html) implies that X’s value is of type T or a subtype of T. After such a check, it is a good practice to limit actions on X to those allowed by type T, even if a subclass of T allows different actions. Doing otherwise will confuse your fellow developers.
>
> Just to be clear, it is common in python to perform an action without checking first if it is possible (see ["Easier to ask for forgiveness than permission."](https://docs.python.org/3/glossary.html#term-eafp)). However when type checks are performed, they should not contradict the following actions.
>
> This rule raises an issue when an action performed on a variable might be possible, but it contradicts a previous type check. The list of checked actions corresponds to rules S2159, S3403, S5607, S5756, S5644, S3862, S5797, S5795 and S5632. These other rules only detect cases where the type of a variable is certain, i.e. it cannot be a subclass.
>
> ```python Bad theme={"theme":"css-variables"}
> def add_the_answer(param: str):
> return param + 42  # Noncompliant. Fix this "+" operation; Type annotation on "param" suggest that operands have incompatible types.
> # Note: In practice it is possible to create a class inheriting from both "str" and "int", but this would be a very confusing design.
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def add_the_answer(param: str):
> return param + "42"
> ```

> [accordion] Names of regular expressions named groups should be used
>
> Why use named groups only to never use any of them later on in the code?
>
> This rule raises issues every time named groups are:
>
> <ul>
>   <li>
>     referenced while not defined;
>   </li>
>
>   <li>
>     defined but called elsewhere in the code by their number instead.
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> import re
>
> def foo():
> pattern = re.compile(r"(?P<a>.)")
> matches = pattern.match("abc")
> g1 = matches.group("b") # Noncompliant - group "b" is not defined
> g2 = matches.group(1) # Noncompliant - Directly use 'a' instead of its group number.
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import re
>
> def foo():
> pattern = re.compile(r"(?P<a>.)")
> matches = pattern.match("abc")
> g = matches.group("a")
> ```

> [accordion] Control flow statements if, for, while, try and with should not be nested too deeply
>
> Nested control flow statements `if, for, while, try, and with` are often key ingredients in creating
> what’s known as "Spaghetti code". This code smell can make your program difficult to understand and maintain.
>
> When numerous control structures are placed inside one another, the code becomes a tangled, complex web.
> This significantly reduces the code’s readability and maintainability, and it also complicates the testing process.
>
> ```python Bad theme={"theme":"css-variables"}
> if condition1:           # Compliant - depth = 1
> # ...
> if condition2:         # Compliant - depth = 2
> # ...
> for i in range(10):  # Compliant - depth = 3
>   # ...
>   if condition3:     # Compliant - depth = 4
>     if condition4:     # Non-Compliant - depth = 5, which exceeds the limit
>       if condition5:   # Depth = 6, exceeding the limit, but issues are only reported on depth = 5
>         # ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> if not condition1:
> return
> # ...
> if not condition2:
> return
> # ...
> for i in range(10):
> # ...
> if condition3:
>   if condition4:
>     if condition5:
>       # ...
> ```

> [accordion] Conditional expressions should not be nested
>
> Nested conditionals are hard to read and can make the order of operations complex to understand.
>
> ```python Bad theme={"theme":"css-variables"}
> class Job:
> @property
> def readable_status(self):
>     return "Running" if job.is_running else "Failed" if job.errors else "Succeeded"  # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Job:
> @property
> def readable_status(self):
>     if job.is_running:
>         return "Running"
>     return "Failed" if job.errors else "Succeeded"
> ```

> [accordion] A subclass should not be in the same except statement as a parent class
>
> In Python it is possible to catch multiple types of exception in a single except statement using a tuple of the exceptions.
>
> Repeating an exception class in a single except statement will not fail but it does not have any effect. Either the exception class is not the one which should be caught, or it is duplicated code which should be removed.
>
> Having a subclass and a parent class in the same except statement does not provide any benefit either. It is enough to keep only the parent class.
>
> ```python Bad theme={"theme":"css-variables"}
> try:
> ...
> except (TypeError, TypeError):  # Noncompliant: duplicated code or incorrect exception class.
> print("Foo")
>
> try:
> ...
> except (NotImplementedError, RuntimeError):  # Noncompliant: NotImplementedError inherits from RuntimeError.
> print("Foo")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> try:
> ...
> except (TypeError, ValueError):
> print("Foo")
>
> try:
> ...
> except RuntimeError:
> print("Foo")
> ```

> [accordion] tf.Variable objects should be singletons when created inside of a tf.function
>
> `tensorflow.functions only supports singleton tensorflow.Variables. This means the variable will be created on the first call
> of the tensorflow.function and will be reused across the subsequent calls. Creating a tensorflow.Variable that is not a singleton
> will raise a ValueError`.
>
> ```python Bad theme={"theme":"css-variables"}
> import tensorflow as tf
>
> @tf.function
> def f(x):
> v = tf.Variable(1.0)
> return v
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import tensorflow as tf
>
> class Count(tf.Module):
> def __init__(self):
> self.count = None
>
> @tf.function
> def __call__(self):
> self.count = tf.Variable(0) # Noncompliant: the variable will be re-created for each call
> return self.count.assign_add(1)
>
> c = Count()
> c() # ValueError is raised
> c()
> ```

> [accordion] **future** imports should be the first statements in a module
>
> Importing a feature from the `future` module turns on that feature from a future version of Python in your module. The purpose is to allow you to gradually transition to the new features or incompatible changes in future language versions, rather than having to make the entire jump at once.
>
> Because such changes must be applied to the entirety of a module to work, putting such imports anywhere but in the beginning of the module doesn’t make sense. It would mean applying those restrictions to only part of your code. Because that would lead to inconsistencies and massive confusion, it’s not allowed.
>
> ```python Bad theme={"theme":"css-variables"}
> name = "John"
>
> from __future__ import division # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from __future__ import division
>
> name = "John"
> ```

> [accordion] except clauses should do more than raise the same issue
>
> An except clause that only rethrows the caught exception has the same effect as omitting the except altogether and letting it bubble up automatically.
>
> ```python Bad theme={"theme":"css-variables"}
> a = {}
> try:
> a[5]
> except KeyError:
> raise  # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> a = {}
> try:
> a[5]
> except KeyError as e:
> logging.exception('error while accessing the dict')
> raise e
> ```

> [accordion] numpy.random.Generator should be preferred to numpy.random.RandomState
>
> Using a predictable seed is a common best practice when using NumPy to create reproducible results. To that end, using np.random.seed(number) to set the seed of the global numpy.random.RandomState has been the privileged solution for a long time.
>
> numpy.random.RandomState and its associated methods rely on a global state, which may be problematic when threads or other forms of concurrency are involved. The global state may be altered and the global seed may be reset at various points in the program (for instance, through an imported package or script), which would lead to irreproducible results.
>
> Instead, the preferred best practice to generate reproducible pseudorandom numbers is to instantiate a numpy.random.Generator object with a seed and reuse it in different parts of the code. This avoids the reliance on a global state. Whenever a new seed is needed, a new generator may be created instead of mutating a global state.
>
> Below is the list of legacy functions and their alternatives:
>
> <table>
>   <tbody>
>     <tr>
>       <td>Legacy function name</td>
>       <td>numpy.random.Generator alternative</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.seed</td>
>       <td>numpy.random.default\_rng</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.rand</td>
>       <td>numpy.random.Generator.random</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.randn</td>
>       <td>numpy.random.Generator.standard\_normal</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.randint</td>
>       <td>numpy.random.Generator.integers</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.random\_integers</td>
>       <td>numpy.random.Generator.integers</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.random\_sample</td>
>       <td>numpy.random.Generator.random</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.choice</td>
>       <td>numpy.random.Generator.choice</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.bytes</td>
>       <td>numpy.random.Generator.bytes</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.shuffle</td>
>       <td>numpy.random.Generator.shuffle</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.permutation</td>
>       <td>numpy.random.Generator.permutation</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.beta</td>
>       <td>numpy.random.Generator.beta</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.binomial</td>
>       <td>numpy.random.Generator.binomial</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.chisquare</td>
>       <td>numpy.random.Generator.chisquare</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.dirichlet</td>
>       <td>numpy.random.Generator.dirichlet</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.exponential</td>
>       <td>numpy.random.Generator.exponential</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.f</td>
>       <td>numpy.random.Generator.f</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.gamma</td>
>       <td>numpy.random.Generator.gamma</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.geometric</td>
>       <td>numpy.random.Generator.geometric</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.gumbel</td>
>       <td>numpy.random.Generator.gumbel</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.hypergeometric</td>
>       <td>numpy.random.Generator.hypergeometric</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.laplace</td>
>       <td>numpy.random.Generator.laplace</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.logistic</td>
>       <td>numpy.random.Generator.logistic</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.lognormal</td>
>       <td>numpy.random.Generator.lognormal</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.logseries</td>
>       <td>numpy.random.Generator.logseries</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.multinomial</td>
>       <td>numpy.random.Generator.multinomial</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.multivariate\_normal</td>
>       <td>numpy.random.Generator.multivariate\_normal</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.negative\_binomial</td>
>       <td>numpy.random.Generator.negative\_binomial</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.noncentral\_chisquare</td>
>       <td>numpy.random.Generator.noncentral\_chisquare</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.noncentral\_f</td>
>       <td>numpy.random.Generator.noncentral\_f</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.normal</td>
>       <td>numpy.random.Generator.normal</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.pareto</td>
>       <td>numpy.random.Generator.pareto</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.poisson</td>
>       <td>numpy.random.Generator.poisson</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.power</td>
>       <td>numpy.random.Generator.power</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.rayleigh</td>
>       <td>numpy.random.Generator.rayleigh</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.standard\_cauchy</td>
>       <td>numpy.random.Generator.standard\_cauchy</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.standard\_exponential</td>
>       <td>numpy.random.Generator.standard\_exponential</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.standard\_gamma</td>
>       <td>numpy.random.Generator.standard\_gamma</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.standard\_normal</td>
>       <td>numpy.random.Generator.standard\_normal</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.standard\_t</td>
>       <td>numpy.random.Generator.standard\_t</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.triangular</td>
>       <td>numpy.random.Generator.triangular</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.uniform</td>
>       <td>numpy.random.Generator.uniform</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.vonmises</td>
>       <td>numpy.random.Generator.vonmises</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.wald</td>
>       <td>numpy.random.Generator.wald</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.weibull</td>
>       <td>numpy.random.Generator.weibull</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.RandomState.zipf</td>
>       <td>numpy.random.Generator.zipf</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.beta</td>
>       <td>numpy.random.Generator.beta</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.binomial</td>
>       <td>numpy.random.Generator.binomial</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.bytes</td>
>       <td>numpy.random.Generator.bytes</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.chisquare</td>
>       <td>numpy.random.Generator.chisquare</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.choice</td>
>       <td>numpy.random.Generator.choice</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.dirichlet</td>
>       <td>numpy.random.Generator.dirichlet</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.exponential</td>
>       <td>numpy.random.Generator.exponential</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.f</td>
>       <td>numpy.random.Generator.f</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.gamma</td>
>       <td>numpy.random.Generator.gamma</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.geometric</td>
>       <td>numpy.random.Generator.geometric</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.gumbel</td>
>       <td>numpy.random.Generator.gumbel</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.hypergeometric</td>
>       <td>numpy.random.Generator.hypergeometric</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.laplace</td>
>       <td>numpy.random.Generator.laplace</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.logistic</td>
>       <td>numpy.random.Generator.logistic</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.lognormal</td>
>       <td>numpy.random.Generator.lognormal</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.logseries</td>
>       <td>numpy.random.Generator.logseries</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.multinomial</td>
>       <td>numpy.random.Generator.multinomial</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.multivariate\_normal</td>
>       <td>numpy.random.Generator.multivariate\_normal</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.negative\_binomial</td>
>       <td>numpy.random.Generator.negative\_binomial</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.noncentral\_chisquare</td>
>       <td>numpy.random.Generator.noncentral\_chisquare</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.noncentral\_f</td>
>       <td>numpy.random.Generator.noncentral\_f</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.normal</td>
>       <td>numpy.random.Generator.normal</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.pareto</td>
>       <td>numpy.random.Generator.pareto</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.permutation</td>
>       <td>numpy.random.Generator.permutation</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.poisson</td>
>       <td>numpy.random.Generator.poisson</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.power</td>
>       <td>numpy.random.Generator.power</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.rand</td>
>       <td>numpy.random.Generator.random</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.randint</td>
>       <td>numpy.random.Generator.integers</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.randn</td>
>       <td>numpy.random.Generator.standard\_normal</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.random</td>
>       <td>numpy.random.Generator.random</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.random\_integers</td>
>       <td>numpy.random.Generator.integers</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.random\_sample</td>
>       <td>numpy.random.Generator.random</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.ranf</td>
>       <td>numpy.random.Generator.random</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.rayleigh</td>
>       <td>numpy.random.Generator.rayleigh</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.sample</td>
>       <td>numpy.random.Generator.random</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.seed</td>
>       <td>numpy.random.default\_rng</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.shuffle</td>
>       <td>numpy.random.Generator.shuffle</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.standard\_cauchy</td>
>       <td>numpy.random.Generator.standard\_cauchy</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.standard\_exponential</td>
>       <td>numpy.random.Generator.standard\_exponential</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.standard\_gamma</td>
>       <td>numpy.random.Generator.standard\_gamma</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.standard\_normal</td>
>       <td>numpy.random.Generator.standard\_normal</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.standard\_t</td>
>       <td>numpy.random.Generator.standard\_t</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.triangular</td>
>       <td>numpy.random.Generator.triangular</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.uniform</td>
>       <td>numpy.random.Generator.uniform</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.vonmises</td>
>       <td>numpy.random.Generator.vonmises</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.wald</td>
>       <td>numpy.random.Generator.wald</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.weibull</td>
>       <td>numpy.random.Generator.weibull</td>
>     </tr>
>
>     <tr>
>       <td>numpy.random.zipf</td>
>       <td>numpy.random.Generator.zipf</td>
>     </tr>
>   </tbody>
> </table>
>
> ```python Bad theme={"theme":"css-variables"}
> import numpy as np
> def foo():
> np.random.seed(42)
> x = np.random.randn()  # Noncompliant: this relies on numpy.random.RandomState, which is deprecated
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import numpy as np
> def foo():
> generator = np.random.default_rng(42)
> x = generator.standard_normal()
> ```

> [accordion] Docstrings should be defined
>
> A string literal that is the first statement in a module, function, class, or method is a docstring. A docstring should document what a caller needs to know about the code. Information about what it does, what it returns, and what it requires are all valid candidates for documentation. Well written docstrings allow callers to use your code without having to first read it and understand its logic.
>
> By convention, docstrings are enclosed in three sets of double-quotes.
>
> ```python Bad theme={"theme":"css-variables"}
> def my_function(a,b):
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def my_function(a,b):
>   """Do X"""
> ```

> [accordion] tensorflow\.function should not be recursive
>
> When defining a tensorflow\.function it is generally a bad practice to make this function recursive. TensorFlow does not
> support recursive tensorflow\.function and will in the majority of cases throw an exception. However it is possible as
> well that the execution of such function succeeds, but with multiple tracings which has strong performance implications.
> When executing tensorflow\.function, the code is split into two distinct stages.
> The first stage call tracing creates a new tensorflow\.Graph, runs the Python code normally,
> but defers the execution of TensorFlow operations (i.e. adding two Tensors). These operations are added to the graph without being ran.
> The second stage which is much faster than the first, runs everything that was deferred previously.
> Depending on the input of the tensorflow\.function the first stage may not be needed, see: [Rules of tracing](https://www.tensorflow.org/guide/function#rules_of_tracing).
> Skipping this first stage is what provides the user with TensorFlow’s high performance.
>
> Having a recursive tensorflow\.function prevents the user from benefiting of TensorFlow’s capabilities.
>
> ```python Bad theme={"theme":"css-variables"}
> import tensorflow as tf
>
> @tf.function
> def factorial(n):
>  if n == 1:
>     return 1
> else:
>     return (n * factorial(n-1)) # Noncompliant: the function is recursive
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import tensorflow as tf
>
> @tf.function
> def factorial(n):
>  return tf.exp(tf.lgamma(n + 1)) # Compliant
> ```

> [accordion] Default parameter values should be immutable
>
> While the assignment of default parameter values is typically a good thing, it can go very wrong very quickly when mutable objects are used. That’s because a new instance of the object *is not* created for each function invocation. Instead, all invocations share the same instance, and the changes made for one caller are made for all!
>
> ```python Bad theme={"theme":"css-variables"}
> def get_attr_array(obj, arr=[]):  # Noncompliant
> props = (name for name in dir(obj) if not name.startswith('_'))
> arr.extend(props)  # after only a few calls, this is a big array!
> return arr
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def get_attr_array(obj, arr):
> props = (name for name in dir(obj) if not name.startswith('_'))
> arr.extend(props)
> return arr
> ```

> [accordion] Functions returns should not be invariant
>
> When a function is designed to return an invariant value, it may be poor design, but it shouldn’t adversely affect the outcome of your program. However, when it happens on all paths through the logic, it is surely a bug.
>
> This rule raises an issue when a function contains several return statements that all return the same value.
>
> ```python Bad theme={"theme":"css-variables"}
> def foo(a):  # NonCompliant
> b = 12
> if a == 1:
>     return b
> return b
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] Exception and BaseException should not be raised
>
> Raising instances of [\`Exception](https://docs.python.org/3/library/exceptions.html#Exception) and [BaseException](https://docs.python.org/3/library/exceptions.html#BaseException) will have a negative impact on any code trying to catch these exceptions.
>
> From a consumer perspective, it is generally a best practice to only catch exceptions you intend to handle. Other exceptions should ideally not be caught and let to propagate up the stack trace so that they can be dealt with appropriately. When a generic exception is thrown, it forces consumers to catch exceptions they do not intend to handle, which they then have to re-raise.
>
> Besides, when working with a generic type of exception, the only way to distinguish between multiple exceptions is to check their message, which is error-prone and difficult to maintain. Legitimate exceptions may be unintentionally silenced and errors may be hidden.
>
> For instance, if an exception such as SystemExit\` is caught and not re-raised, it will prevent the program from stopping.
>
> When raising an exception, it is therefore recommended to raising the most specific exception possible so that it can be handled intentionally by consumers.
>
> ```python Bad theme={"theme":"css-variables"}
> def check_value(value):
> if value < 0:
>     raise BaseException("Value cannot be negative") # Noncompliant: this will be difficult for consumers to handle
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def check_value(value):
> if value < 0:
>     raise ValueError("Value cannot be negative") # Compliant
> ```

> [accordion] The input\_shape parameter should not be specified for tf.keras.Model subclasses
>
> Keras provides a full-featured model class called tensorflow\.keras.Model. It inherits from tensorflow\.keras.layers.Layer, so a Keras model can be used and nested in the same way as Keras layers. Keras models come with extra functionality that makes them easy to train, evaluate, load, save, and even train on multiple machines.
>
> As the tensorflow\.keras.Model class inherits from the 'tensorflow\.keras.layers' you do not need to specify input\_shape in a subclassed model; this argument will be ignored.
>
> ```python Bad theme={"theme":"css-variables"}
> import tensorflow as tf
>
> class MyModel(tf.keras.Model):
> def __init__(self):
>     super(MyModel, self).__init__(input_shape=...)  # Noncompliant: this parameter will be ignored
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import tensorflow as tf
>
> class MyModel(tf.keras.Model):
> def __init__(self):
>     super(MyModel, self).__init__()  # OK
> ```

> [accordion] Function parameters should have type hints
>
> Being a dynamically typed language, the Python interpreter only does type checking during runtime. Getting the typing right is important as certain operations may result in a TypeError.
>
> Type hints can be used to clarify the expected parameters of a function, enabling developers to better document its contract. Applying them consistently makes the code easier to read and understand.
>
> In addition, type hints allow some development environments to offer better autocompletion and improve the precision of static analysis tools.
>
> ```python Bad theme={"theme":"css-variables"}
> def hello(name)  str:
> return 'Hello ' + name
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def hello(name: str)  str:
> return 'Hello ' + name
> ```

> [accordion] Generic functions should be defined using the type parameter syntax
>
> Prior to Python 3.12 functions using generic types were created as follows:
>
> ```python Bad theme={"theme":"css-variables"}
> from typing import TypeVar
>
> _T = TypeVar("_T")
>
> def func(a: _T, b: _T)  _T:
> ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def func[T](a: T, b: T)  T:
> ...
> ```

> [accordion] Function parameters default values should not be modified or assigned
>
> In Python, function parameters can have default values.
>
> These default values are expressions which are evalutated when the function is defined, i.e. only once. The same default value will be used every time the function is called. Therefore, modifying it will have an effect on every subsequent call. This can lead to confusing bugs.
>
> ```python Bad theme={"theme":"css-variables"}
> def myfunction(param=foo()):  # foo is called only once, when the function is defined.
> ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def myfunction(param=list()):  # Noncompliant: param is a list that gets mutated
> param.append('a')  # modification of the default value.
> return param
>
> print(myfunction()) # returns ['a']
> print(myfunction()) # returns ['a', 'a']
> print(myfunction()) # returns ['a', 'a', 'a']
> ```

> [accordion] New-style classes should be used
>
> The new style of class creation, with the declaration of a parent class, created a unified object model in Python, so that the type of an instantiated class is equal to its class. In Python 2.2-2.7, this is not the case for old-style classes. In Python 3+ all classes are new-style classes. However, since the behavior can differ from 2.2+ to 3+, explicitly inheriting from `object` (if there is no better candidate) is recommended.
>
> ```python Bad theme={"theme":"css-variables"}
> class MyClass():
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyClass(object):
> pass
> ```

> [accordion] String formatting should not lead to runtime errors
>
> Formatting strings, either with the `% operator or str.format` method, requires a valid string and arguments matching this string’s replacement fields.
>
> This rule raises an issue when formatting a string will raise an exception because the input string or arguments are invalid. Rule S3457 covers cases where no exception is raised and the resulting string is simply not formatted properly.
>
> ```python Bad theme={"theme":"css-variables"}
> print('Error code %d' % '42')  # Noncompliant. Replace this value with a number as %d requires.
>
> print('User {1} is not allowed to perform this action'.format('Bob'))  # Noncompliant. Replacement field numbering should start at 0.
>
> print('User {0} has not been able to access {}'.format('Alice', 'MyFile'))  # Noncompliant. Use only manual or only automatic field numbering, don't mix them.
>
> print('User {a} has not been able to access {b}'.format(a='Alice'))  # Noncompliant. Provide a value for field "b".
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print('Error code %d' % 42)
>
> print('User {0} is not allowed to perform this action'.format('Bob'))
>
> print('User {0} has not been able to access {1}'.format('Alice', 'MyFile'))
>
> print('User {a} has not been able to access {b}'.format(a='Alice', b='MyFile'))
> ```

> [accordion] Using timezone-aware datetime objects should be preferred over using datetime.datetime.utcnow and datetime.datetime.utcfromtimestamp
>
> Python’s datetime API provide several different ways to create datetime objects. One possibility is the to use
> datetime.datetime.utcnow or datetime.datetime.utcfromtimestamp functions. The issue with these two functions is they are not time zone aware, even if their name would suggest otherwise.
>
> Using these functions could cause issue as they may not behave as expected, for example:
>
> ```python Bad theme={"theme":"css-variables"}
> from datetime import datetime
> timestamp = 1571595618.0
> date = datetime.utcfromtimestamp(timestamp)
> date_timestamp = date.timestamp()
>
> assert timestamp == date_timestamp
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from datetime import datetime
>
> datetime.utcnow() # Noncompliant
>
> timestamp = 1571595618.0
> datetime.utcfromtimestamp(timestamp) # Noncompliant
> ```

> [accordion] The exec statement should not be used
>
> Use of the \`exec statement could be dangerous, and should be avoided. Moreover, the exec statement was removed in Python 3.0. Instead, the built-in exec() function can be used.
>
> Use of the exec statement is strongly discouraged for several reasons such as:
>
> <ul>
>   <li>
>     **Security Risks:** Executing code from a string opens up the possibility of code injection attacks.
>   </li>
>
>   <li>
>     **Readability and Maintainability:** Code executed with exec statement is often harder to read and understand since it is not explicitly written in the source code.
>   </li>
>
>   <li>
>     **Performance Implications:** The use of exec statement can have performance implications since the code is compiled and executed at runtime.
>   </li>
>
>   <li>
>     **Limited Static Analysis:** Since the code executed with exec\` statement is only known at runtime, static code analysis tools may not be able to catch certain errors or issues, leading to potential bugs.
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> exec 'print 1' # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> exec('print 1')
> ```

> [accordion] Collections should not be modified while they are iterated
>
> Iterating over a collection using a for loop in Python relies on iterators.
>
> An iterator is an object that allows you to traverse a collection of elements, such as a list or a dictionary. Iterators are used in for loops to iterate over the elements of a collection one at a time.
>
> When you create an iterator, it keeps track of the current position in the collection and provides a way to access the next element. The next() function is used to retrieve the next element from the iterator. When there are no more elements to iterate over, the next() function raises a StopIteration exception and the iteration stops.
>
> It is important to note that iterators are designed to be read-only. Modifying a collection while iterating over it can cause unexpected behavior, as the iterator may skip over or repeat elements. A RuntimeError may also be raised in this situation, with the message changed size during iteration. Therefore, it is important to avoid modifying a collection while iterating over it to ensure that your code behaves as expected.
>
> If you still want to modify the collection, it is best to use a second collection or to iterate over a copy of the original collection instead.
>
> ```python Bad theme={"theme":"css-variables"}
> def my_fun(my_dict):
> for key in my_dict:
>     if my_dict[key] == 'foo':
>         my_dict.pop(key) # Noncompliant: this will make the iteration unreliable
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def my_fun(my_dict):
> for key in list(my_dict.keys()):
>     if my_dict[key] == 'foo':
>         my_dict.pop(key)
> ```

> [accordion] Parentheses should not be used after certain keywords
>
> Parentheses are not required after the `assert, del, elif, except, for, if, in, not, raise, return, while, and yield` keywords, and using them unnecessarily impairs readability. They should therefore be omitted.
>
> ```python Bad theme={"theme":"css-variables"}
> x = 1
> while (x < 10):
> print "x is now %d" % (x)
> x += 1
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> x = 1
> while x < 10:
> print "x is now %d" % (x)
> x += 1
> ```

> [accordion] Static methods should not have self or cls arguments
>
> Unlike class and instance methods, static methods don’t receive an implicit first argument. Nonetheless naming the first argument `self or cls` guarantees confusion - either on the part of the original author, who may never understand why the arguments don’t hold the values he expected, or on that of future maintainers.
>
> ```python Bad theme={"theme":"css-variables"}
> class MyClass:
> @staticmethod
> def s_meth(self, arg1, arg2):  #Noncompliant
> # ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyClass:
> @staticmethod
> def s_meth(arg1, arg2):  #Noncompliant
> # ...
> ```

> [accordion] Return values from functions without side effects should not be ignored
>
> When the call to a function doesn’t have any side effects, what is the point of making the call if the results are ignored? In such case, either the function call is useless and should be dropped or the source code doesn’t behave as expected.
>
> This rule raises an issue when a builtin function or methods which has no side effects is called and its result is not used.
>
> ```python Bad theme={"theme":"css-variables"}
> myvar = "this is a multiline"
> "message from {}".format(sender)  # Noncompliant. The formatted string is not used because the concatenation is not done properly.
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> myvar = ("this is a multiline"
> "message from {}".format(sender))
> ```

> [accordion] The yield keyword should only be used in generators
>
> As soon as the \`yield keyword is used the enclosing method or function becomes a generator. Thus yield should never be used in a function or method which is not intended to be a generator.
>
> This rule raises an issue when yield or yield from are used in a function or method which is not a generator because:
>
> <ul>
>   <li>
>     the function/method’s return type annotation is not \[typing.Generator\[...]|[https://docs.python.org/3/library/typing.html#typing.Generator](https://docs.python.org/3/library/typing.html#typing.Generator)]
>   </li>
>
>   <li>
>     it is a special method which can never be a generator (ex: **init**\`).
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> class A:
> def __init__(self, value):
>     self.value = value
>     yield value  # Noncompliant
>
> def mylist2()  List[str]:
> yield ['string']  # Noncompliant. Return should be used instead of yield
>
> def generator_ok()  Generator[int, float, str]:
> sent = yield 42
> return '42'
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class A:
> def __init__(self, value):
>     self.value = value
>
> def mylist2()  List[str]:
> return ['string']
>
> def generator_ok()  Generator[int, float, str]:
> sent = yield 42
> return '42'
> ```

> [accordion] Builtins should not be shadowed by local variables
>
> Defining a variable with the same name as a built-in symbol will "shadow" it. That means that the builtin will no longer be accessible through its original name, having locally been replaced by the variable.
>
> Shadowing a builtin makes the code more difficult to read and maintain. It may also be a source of bugs as you can reference the builtin by mistake.
>
> It is sometimes acceptable to shadow a builtin to improve the readability of a public API or to support multiple versions of a library. In these cases, benefits are greater than the maintainability cost. This should, however, be done with care.
>
> It is generally not a good practice to shadow builtins with variables which are local to a function or method. These variables are not public and can easily be renamed, thus reducing the confusion and making the code less error-prone.
>
> ```python Bad theme={"theme":"css-variables"}
> def a_function():
> int = 42  # Noncompliant; int is a builtin
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def a_function():
> value = 42
> ```

> [accordion] Calls should not be made to non-callable values
>
> In order to be callable, a Python class should implement the [\`**call**](https://docs.python.org/3/reference/datamodel.html#object.__call__) method. Thanks to this method, an instance of this class will be callable as a function.
>
> However, when making a call to a non-callable object, a TypeError will be raised.
>
> In order to fix this issue, make sure that the object you are trying to call has a **call**\` method.
>
> ```python Bad theme={"theme":"css-variables"}
> class MyClass:
> pass
>
> myvar = MyClass()
> myvar()  # Noncompliant
>
> none_var = None
> none_var()  # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyClass:
> def __call__(self):
>     print("called")
>
> myvar = MyClass()
> myvar()
> ```

> [accordion] Asserts should not be used to check the parameters of a public method
>
> An assert is inappropriate for parameter validation because assertions are disabled globally at the interpreter level when the application runs as optimize bytecode (-O and -OO command line switches). It means that the optimize version of the application would completely eliminate the intended checks.
>
> This rule raises an issue when a `public method uses one or more of its parameters with assert`s.
>
> ```python Bad theme={"theme":"css-variables"}
> class Shop:
>
> def setPrice(self, price):
> assert(price >= 0 and price <= MAX_PRICE) # Noncompliant
> // Set the price
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Shop:
>
> def setPrice(self, price):
> if(price < 0 or price > MAX_PRICE):
>   raise ValueError("Invalid price: " + price)
> // Set the price
> ```

> [accordion] Function arguments should be passed only once
>
> When a function is called, it accepts only one value per parameter. The Python interpreter will raise a SyntaxError when the same parameter is provided more than once, i.e. myfunction(a=1, a=2).
>
> Other less obvious cases will also fail at runtime by raising a TypeError, when:
>
> <ul>
>   <li>
>     An argument is provided by value and position at the same time.
>   </li>
>
>   <li>
>     An argument is provided twice, once via unpacking and once by value or position.
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> def func(a, b, c):
> return a * b * c
>
> func(6, 93, 31, c=62) # Noncompliant: argument "c" is duplicated
>
> params = {'c':31}
> func(6, 93, 31, **params) # Noncompliant: argument "c" is duplicated
> func(6, 93, c=62, **params) # Noncompliant: argument "c" is duplicated
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def func(a, b, c):
> return a * b * c
>
> func(c=31, b=93, a=6) # Compliant  
>
> params = {'c':31}
> func(6, 93, **params) # Compliant
> ```

> [accordion] with statements should be used with context managers
>
> The [with statement](https://docs.python.org/3/reference/compound_stmts.html#the-with-statement) is used to wrap the execution of a block with methods defined by a context manager. The [context manager](https://docs.python.org/3/reference/datamodel.html#context-managers) handles the entry into, and the exit from, the desired runtime context for the execution of the block of code. To do so, a context manager should have an **enter** and an **exit** method.
>
> Executing the  following block of code:
>
> ```python Bad theme={"theme":"css-variables"}
> class MyContextManager:
> def __enter__(self):
>     print("Entering")
>
> def __exit__(self, exc_type, exc_val, exc_tb):
>     print("Exiting")
>
>
> with MyContextManager():
> print("Executing body")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> Entering
> Executing body
> Exiting
> ```

> [accordion] Wildcard imports should not be used
>
> Importing every public name from a module using a wildcard (`from mymodule import *`) is a bad idea because:
>
> <ul>
>   <li>
>     It could lead to conflicts between names defined locally and the ones imported.
>   </li>
>
>   <li>
>     It reduces code readability as developers will have a hard time knowing where names come from.
>   </li>
>
>   <li>
>     It clutters the local namespace, which makes debugging more difficult.
>   </li>
> </ul>
>
> Remember that imported names can change when you update your dependencies. A wildcard import that works today might be broken tomorrow.
>
> ```python Bad theme={"theme":"css-variables"}
> # file: mylibrary/pyplot.py
> try:
> from guiqwt.pyplot import *  # Ok
> except Exception:
> from matplotlib.pyplot import *  # Ok
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from math import *  # Noncompliant
> def exp(x):
> pass
> print(exp(0))   # "None" will be printed
> ```

> [accordion] **exit** should accept type, value, and traceback arguments
>
> The `exit method is invoked with four arguments: self, type, value and traceback. Leave one of these out of the method declaration and the result will be a TypeError` at runtime.
>
> ```python Bad theme={"theme":"css-variables"}
> class MyClass:
> def __enter__(self):
>    pass
> def __exit__(self, exc_type, exc_val):  # Noncompliant
>    pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] The number and name of arguments passed to a function should match its parameters
>
> Calling a function or a method with fewer or more arguments than expected will raise a `TypeError`. This is usually a bug and should be fixed.
>
> ```python Bad theme={"theme":"css-variables"}
> ######################
> # Positional Arguments
> ######################
>
> param_args = [1, 2, 3]
> param_kwargs = {'x': 1, 'y': 2}
>
> def func(a, b=1):
> print(a, b)
>
> def positional_unlimited(a, b=1, *args):
> print(a, b, *args)
>
> func(1)
> func(1, 42)
> func(1, 2, 3)  # Noncompliant. Too many positional arguments
> func()  # Noncompliant. Missing positional argument for "a"
>
> positional_unlimited(1, 2, 3, 4, 5)
>
> def positional_limited(a, *, b=2):
> print(a, b)
>
> positional_limited(1, 2)  # Noncompliant. Too many positional arguments
>
>
> #############################
> # Unexpected Keyword argument
> #############################
>
> def keywords(a=1, b=2, *, c=3):
> print(a, b, c)
>
> keywords(1)
> keywords(1, z=42)  # Noncompliant. Unexpected keyword argument "z"
>
> def keywords_unlimited(a=1, b=2, *, c=3, **kwargs):
> print(a, b, kwargs)
>
> keywords_unlimited(a=1, b=2, z=42)
>
> #################################
> # Mandatory Keyword argument only
> #################################
>
> def mandatory_keyword(a, *, b):
> print(a, b)
>
> mandatory_keyword(1, b=2)
> mandatory_keyword(1)  # Noncompliant. Missing keyword argument "b"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] break and continue should not be used outside a loop
>
> break and continue are control flow statements used inside of loops. break is used to break out of its innermost enclosing loop and continue will continue with the next iteration.
>
> The example below illustrates the use of break in a while loop:
>
> ```python Bad theme={"theme":"css-variables"}
> n = 1
> while n < 10:
> if n % 3 == 0:
>   print("Found a number divisible by 3", n)
>   break
> n = n + 1
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> words = ["alice", "bob", "charlie"]
> for word in words:
> if word == word[::-1]:
>     print("Found a palindrome", word)
>     continue
> print("This is not a palindrome", word)
> ```

> [accordion] Functions and methods should only return expected values
>
> Python allows developers to customize how code is interpreted by defining special methods (also called magic methods). For example, it is possible to define the objects own truthiness or falsiness by iverriding \`**bool** method. It is invoked when the built-in bool() function is called on an object. The bool() function returns True or False based on the truth value of the object.
>
> The Python interpreter will call these methods when performing the operation they’re associated with. Each special method expects a specific return type. Calls to a special method will throw a TypeError if its return type is incorrect.
>
> An issue will be raised when one of the following methods doesn’t return the indicated type:
>
> <ul>
>   <li>
>     **bool** method should return bool
>   </li>
>
>   <li>
>     **index** method should return integer
>   </li>
>
>   <li>
>     **repr** method should return string
>   </li>
>
>   <li>
>     **str** method should return string
>   </li>
>
>   <li>
>     **bytes** method should return bytes
>   </li>
>
>   <li>
>     **hash** method should return integer
>   </li>
>
>   <li>
>     **format** method should return string
>   </li>
>
>   <li>
>     **getnewargs** method should return tuple
>   </li>
>
>   <li>
>     **getnewargs\_ex**\` method should return something which is of the form tuple(tuple, dict)
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> class MyClass:
> def __bool__(self):
>     return 0 # Noncompliant: Return value of type bool here.
>
> obj1 = MyClass()
> print(bool(obj1)) # TypeError: __bool__ should return bool, returned int
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyClass:
> def __bool__(self):
>     return False
>
> obj1 = MyClass()
> print(bool(obj1))
> ```

> [accordion] Item operations should be done on objects supporting them
>
> Getting, setting and deleting items using square brackets requires the accessed object to have special methods:
>
> <ul>
>   <li>
>     Getting items such as \`my\_variable\[key] requires my\_variable to have the [**getitem**](https://docs.python.org/3/reference/datamodel.html#object.__getitem__) method, or the [**class\_getitem**](https://docs.python.org/3/reference/datamodel.html#object.__class_getitem__) method if my\_variable is a class.
>   </li>
>
>   <li>
>     Setting items such as my\_variable\[key] = 42 requires my\_variable to have the [**setitem**](https://docs.python.org/3/reference/datamodel.html#object.__setitem__) method.
>   </li>
>
>   <li>
>     Deleting items such as del my\_variable\[key] requires my\_variable to have the [**delitem**](https://docs.python.org/3/reference/datamodel.html#object.__delitem__) method.
>   </li>
> </ul>
>
> Performing these operations on an object that doesn’t have the corresponding method will result in a TypeError\`.
>
> To fix this issue, make sure that the class for which you are trying to perform item operations implements the required methods.
>
> ```python Bad theme={"theme":"css-variables"}
> del (1, 2)[0]  # Noncompliant: tuples are immutable
> (1, 2)[0] = 42  # Noncompliant
> (1, 2)[0]
>
> class A:
> def __init__(self, values):
>     self._values = values
>
> a = A([0,1,2])
>
> a[0]  # Noncompliant
> del a[0]  # Noncompliant
> a[0] = 42  # Noncompliant
>
> class B:
> pass
>
> B[0]  # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> del [1, 2][0]  # Lists are mutable
> [1, 2][0] = 42
> [1, 2][0]
>
> class A:
> def __init__(self, values):
>     self._values = values
>
> def __getitem__(self, key):
>     return self._values[key]
>
> def __setitem__(self, key, value):
>     self._values[key] = value
>
> def __delitem__(self, key):
>     del self._values[key]
>
> a = A([0,1,2])
>
> a[0] 
> del a[0]
> a[0] = 42
>
> class B:
> def __class_getitem__(cls, key):
>     return [0, 1, 2, 3][key]
>
> B[0]
> ```

> [accordion] Replacement strings should reference existing regular expression groups
>
> The regex function re.sub can be used to perform a search and replace based on regular expression matches. The repl parameter can contain references to capturing groups used in the pattern parameter. This can be achieved with \n to reference the n’th group.
>
> When referencing a nonexistent group an error will be thrown for Python \< 3.5 or replaced by an empty string for Python >= 3.5.
>
> ```python Bad theme={"theme":"css-variables"}
> re.sub(r"(a)(b)(c)", r"\1, \9, \3", "abc") # Noncompliant - result is an re.error: invalid group reference
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> re.sub(r"(a)(b)(c)", r"\1, \2, \3", "abc")
> ```

> [accordion] The first argument to a super call should be the name of the calling class
>
> The first argument to `super` must be the name of the class making the call. If it’s not, the result will be a runtime error.
>
> ```python Bad theme={"theme":"css-variables"}
> class Person(object):
> #...
>
> class PoliceOfficer(Person):
> def __init__(self, name):
> super().__init__(name)  // Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Person(object):
> #...
>
> class PoliceOfficer(Person):
> def __init__(self, name):
> super(PoliceOfficer).__init__(name)
> ```

> [accordion] null=True should not be used on string-based fields in Django models
>
> Using "null=True" on string-based fields can lead to inconsistent and unexpected behavior. In Django, "null=True" allows the field to have a NULL value in the database. However, the Django convention to represent the absence of data for a string is an empty string. Having two ways to represent the absence of data can cause problems when querying and filtering on the field. For example, if a CharField with "null=True" has a value of NULL in the database, querying for an empty string will not return that object.
>
> ```python Bad theme={"theme":"css-variables"}
> class ExampleModel(models.Model):
> name = models.CharField(max_length=50, null=True)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class ExampleModel(models.Model):
> name = models.CharField(max_length=50, blank=True)
> ```

> [accordion] GraphQL introspection should be disabled in production
>
> GraphQL introspection is a feature that allows client applications to query the
> schema of a GraphQL API at runtime. It provides a way for developers to explore
> and understand the available data and operations supported by the API.
>
> This feature is a diagnostic tool that should only be used in the development
> phase as its presence also creates risks.
>
> Clear documentation and API references should be considered better
> discoverability tools for a public GraphQL API.
>
> ```python Bad theme={"theme":"css-variables"}
> from graphql_server.flask import GraphQLView
>
> app.add_url_rule("/api",
> view_func=GraphQLView.as_view(  # Noncompliant
>     name="api",
>     schema=schema,
> )
> )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from graphql_server.flask import GraphQLView
>
> # Only one of the following needs to be used
> from graphql.validation import NoSchemaIntrospectionCustomRule # graphql-core v3
> from graphene.validation import DisableIntrospection           # graphene v3
>
>
> app.add_url_rule("/api",
> view_func=GraphQLView.as_view(
>     name="api",
>     schema=schema,
>     validation_rules=[
>         NoSchemaIntrospectionCustomRule,
>         DisableIntrospection,
>     ]
> )
> )
> ```

> [accordion] Functions, methods and lambdas should not have too many parameters
>
> Functions, methods, or lambdas with a long parameter list are difficult to use, as maintainers must figure out the role of each parameter and keep track of their position.
>
> ```python Bad theme={"theme":"css-variables"}
> def set_coordinates(x1, y1, z1, x2, y2, z2): # Noncompliant
> # ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> # Each function does a part of what the original set_coordinates function was doing, so confusion risks are lower
> def set_origin(x, y, z):
> # ...
>
> def set_size(width, height, depth):
> # ...
> ```

> [accordion] The safe flag should be set to False when serializing non-dictionary objects in Django JSON-encoded responses.
>
> By default, only dictionary objects can be serialized in Django JSON-encoded response. Before ECMASCript 5, serializing non-dictionary objects could lead to security vulnerabilities. Since most modern browsers implement ECMAScript 5, this vector of attack is no longer a threat and it is possible to serialize non-dictionary objects by setting the safe flag to False. However, if this flag is not set, a TypeError will be thrown by the serializer.
>
> Despite this possibility, it is still recommended to serialize dictionary objects, as an API based on dict is generally more extensible and easier to maintain.
>
> ```python Bad theme={"theme":"css-variables"}
> from django.http import JsonResponse
> response = JsonResponse([1, 2, 3])
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from django.http import JsonResponse
> response = JsonResponse([1, 2, 3], safe=False)
> ```

> [accordion] Walrus operator should not make code confusing
>
> The [walrus operator](https://www.python.org/dev/peps/pep-0572) `:= (also known as "assignment expression") should be used with caution as it can easily make code more difficult to understand and thus maintain. In such case it is advised to refactor the code and use an assignment statement (i.e. =`) instead.
>
> Reasons why it is better to avoid using the walrus operator in Python:
>
> <ul>
>   <li>
>     **Readability:** The walrus operator can lead to more complex and nested expressions, which might reduce the readability of the code, especially for developers who are not familiar with this feature.
>   </li>
>
>   <li>
>     **Compatibility:** If you are working on projects that need to be compatible with older versions of Python (before 3.8), you should avoid using the walrus operator, as it won’t be available in those versions.
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> v0 = (v1 := f(p))  # Noncompliant: Use an assignment statement ("=") instead; ":=" operator is confusing in this context
> f'{(x:=10)}' # Noncompliant: Move this assignment out of the f-string; ":=" operator is confusing in this context
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> v0 = v1 = f(p)
> x = 10
> f'{x}'
> ```

> [accordion] Loops without break should not have else clauses
>
> The `else clause of a loop is skipped when a break is executed in this loop. In other words, a loop with an else but no break statement will always execute the else part (unless of course an exception is raised or return is used). If this is what the developer intended, it would be much simpler to have the else statement removed and its body unindented. Thus having a loop with an else and no break` is most likely an error.
>
> ```python Bad theme={"theme":"css-variables"}
> from typing import List
>
> def foo(elements: List[str]):
> for elt in elements:
>     if elt.isnumeric():
>         return elt
> else:  # Noncompliant: no break in the loop
>     raise ValueError("List does not contain any number")
>
> def bar(elements: List[str]):
> for elt in elements:
>     if elt.isnumeric():
>         return elt
> else:  # Noncompliant: no break in the loop
>     raise ValueError("List does not contain any number")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from typing import List
>
> def foo(elements: List[str]):
> for elt in elements:
>     if elt.isnumeric():
>         break
> else:
>     raise ValueError("List does not contain any number")
> return elt
>
> def bar(elements: List[str]):
> for elt in elements:
>     if elt.isnumeric():
>         return elt
> raise ValueError("List does not contain any number")
> ```

> [accordion] Methods and properties that dont access instance data should be static
>
> Class methods that don’t access instance data can and should be static because they yield more performant code.
>
> To implement a static method in Python one should use either `@classmethod or @staticmethod`. A class method receives the class as implicit first argument, just like an instance method receives the instance. A static method does not receive an implicit first argument.
>
> ```python Bad theme={"theme":"css-variables"}
> class Utilities:
> def do_the_thing(self, arg1, arg2, ...):  # Noncompliant
>     #...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Utilities:
> @classmethod
> def do_the_thing(cls, arg1, arg2, ...):
>     #...
> ```

> [accordion] Method overrides should not change contracts
>
> Because a subclass instance may be used as an instance of the superclass, overriding methods should uphold the aspects of the superclass contract that relate to the [Liskov Substitution Principle](https://en.wikipedia.org/wiki/Liskov_substitution_principle). Specifically, an overriding method should be callable with the same parameters as the overriden one.
>
> The following modifications are OK:
>
> <ul>
>   <li>
>     Adding an optional parameter, i.e. with a default value, as long as they don’t change the order of positional parameters.
>   </li>
>
>   <li>
>     Renaming a positional-only parameter.
>   </li>
>
>   <li>
>     Reordering keyword-only parameters.
>   </li>
>
>   <li>
>     Adding a default value to an existing parameter.
>   </li>
>
>   <li>
>     Changing the default value of an existing parameter.
>   </li>
>
>   <li>
>     Extend the ways a parameter can be provided, i.e. change a keyword-only or positional-only parameter to a keyword-or-positional parameter. This is only true if the order of positional parameters doesn’t change. New positional parameters should be placed at the end.
>   </li>
>
>   <li>
>     Adding a vararg parameter (\`\*args).
>   </li>
>
>   <li>
>     Adding a keywords parameter (\*\*kwargs).
>   </li>
> </ul>
>
> The following modifications are not OK:
>
> <ul>
>   <li>
>     Removing parameters, even when they have default values.
>   </li>
>
>   <li>
>     Adding mandatory parameters, i.e. without a default value.
>   </li>
>
>   <li>
>     Removing the default value of a parameter.
>   </li>
>
>   <li>
>     Reordering parameters, except when they are keyword-only parameters.
>   </li>
>
>   <li>
>     Removing some ways of providing a parameter. If a parameter could be passed as keyword it should still be possible to pass it as keyword, and the same is true for positional parameters.
>   </li>
>
>   <li>
>     Removing a vararg parameter (\*args).
>   </li>
>
>   <li>
>     Removing a keywords parameter (\*\*kwargs\`).
>   </li>
> </ul>
>
> This rule raises an issue when the signature of an overriding method does not accept the same parameters as the overriden one. Only instance methods are considered, class methods and static methods are ignored.
>
> ```python Bad theme={"theme":"css-variables"}
> class ParentClass(object):
> def mymethod(self, param1):
>     pass
>
> class ChildClassRenamed(ParentClass):
> def mymethod(self, renamed): # No issue but this is suspicious. Rename this parameter as "param1" or use positional only arguments if possible.
>     pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class ParentClass(object):
> def mymethod(self, param1):
>     pass
>
> class ChildClassMore(ParentClass):
> def mymethod(self, param1, param2, param3): # Noncompliant * 2.
>     # Remove parameter "param2" or provide a default value.
>     # Remove parameter "param3" or provide a default value.
>     pass
>
> class ChildClassLess(ParentClass):
> def mymethod(self): # Noncompliant. Add missing parameter "param1".
>     pass
>
> class ChildClassReordered(ParentClass):
> def mymethod(self, inserted, param1): # Noncompliant
>     # Remove parameters "inserted" or provide a default value.
>     pass
> ```

> [accordion] All branches in a conditional structure should not have exactly the same implementation
>
> Having all branches of an if chain with the same implementation indicates a problem.
>
> In the following code:
>
> ```python Bad theme={"theme":"css-variables"}
> if b == 0:  # Noncompliant
> do_one_more_thing()
> elif b == 1:
> do_one_more_thing()
> else:
> do_one_more_thing()
>
> b = 4 if a > 12 else 4  # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> if b == 0:  # no issue, this could have been done on purpose to make the code more readable
> do_one_more_thing()
> elif b == 1:
> do_one_more_thing()
> ```

> [accordion] Instance and class methods should have at least one positional parameter
>
> Every instance method is expected to have at least one positional parameter. This parameter will reference the object instance on which the method is called. Calling an instance method which doesn’t have at least one parameter will raise a TypeError. By convention, this first parameter is usually named self.
>
> Class methods, i.e. methods annotated with @classmethod, also require at least one parameter. The only differences is that they will receive the class itself instead of a class instance. By convention, this first parameter is usually named cls.
>
> ```python Bad theme={"theme":"css-variables"}
> class MyClass:
> def instance_method():  # Noncompliant: "self" parameter is missing.
>     print("instance_method")
>
> @classmethod
> def class_method():  # Noncompliant: "cls" parameter is missing.
>     print("class_method")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyClass:
> def instance_method(self):
>     print("instance_method")
>
> @classmethod
> def class_method(cls):
>     print("class_method")
>
> @staticmethod
> def static_method():
>     print("static_method")
> ```

> [accordion] Assert should not be called on a tuple literal
>
> When tested for truthiness, a sequence or collection will evaluate to False if it is empty (its \`**len** method returns 0) and to True if it contains at least one element.
>
> Using the assert statement on a tuple literal will therefore always fail if the tuple is empty, and always succeed otherwise.
>
> The assert statement does not take parentheses around its parameters. Calling assert(x, y) will test if the tuple (x, y) is True, which is always the case.
>
> There are two possible fixes:
>
> <ul>
>   <li>
>     If your intention is to test the first value of the tuple and use the second value as a message, simply remove the parentheses.
>   </li>
>
>   <li>
>     If your intention is to check that every element of the tuple is True\`, test each value separately.
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> def test_values(a, b):
> assert (a, b)  # Noncompliant: will always be True
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def test_values(a, b):
> # If you mean to test "a" and use "b" as an error message
> assert a, b
>
> # If you mean to test the values of "a" and "b"
> assert a and b
> ```

> [accordion] Long suffix L should be upper case
>
> The long suffix should always be written in uppercase, i.e. 'L', as the lowercase 'l' can easily be confused with the digit one '1'.
>
> ```python Bad theme={"theme":"css-variables"}
> return 10l  // Noncompliant; easily confused with one zero one
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> return 10L
> ```

> [accordion] The validate\_indices argument should not be set for tf.gather function call
>
> The tf.gather function allows you to gather slices from a tensor along a specified axis according to the indices provided.
> The validate\_indices argument is deprecated and setting its value has no effect. Indices are always validated on CPU and never validated on GPU.
>
> ```python Bad theme={"theme":"css-variables"}
> import tensorflow as tf
>
> x = tf.constant([[1, 2], [3, 4]])
> y = tf.gather(x, [1], validate_indices=True)  # Noncompliant: validate_indices is deprecated
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import tensorflow as tf
>
> x = tf.constant([[1, 2], [3, 4]])
> y = tf.gather(x, [1])  # OK
> ```

> [accordion] Special methods should have an expected number of parameters
>
> Python allows developers to customize how code is interpreted by defining special methods (also called magic methods). For example, it is possible to override how the multiplication operator (\`a \* b) will apply to instances of a class by defining in this class the **mul** and **rmul** methods. Whenever a multiplication operation is performed with this class, the Python interpreter will call one of these methods instead of performing the default multiplication.
>
> Each special method expects a specific number of parameters. The Python interpreter will call these methods with those parameters. Calls to a special method will throw a TypeError\` if it is defined with an incorrect number of parameters.
>
> ```python Bad theme={"theme":"css-variables"}
> class A:
> def __mul__(self, other, unexpected):  # Noncompliant: too many parameters
>     return 42
>
> def __add__(self):  # Noncompliant: missing one parameter
>     return 42
>
> A() * 3  # TypeError: __mul__() missing 1 required positional argument: 'unexpected'
> A() + 3  # TypeError: __add__() takes 1 positional argument but 2 were given
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class A:
> def __mul__(self, other):
>     return 42
>
> def __add__(self, other):
>     return 42
>
> A() * 3
> A() + 3
> ```

> [accordion] Octal escape sequences should not be used in regular expressions
>
> Using octal escapes in regular expressions can create confusion with backreferences.
> Octal escapes are sequences of digits that represent a character in the ASCII table, and they are sometimes used to represent special characters in regular expressions.
> However, they can be easily mistaken for backreferences, which are also sequences of digits that represent previously captured groups. This confusion can lead to unexpected results or errors in the regular expression.
>
> ```python Bad theme={"theme":"css-variables"}
> import re
>
> match = re.match(r"\101", "A")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import re
>
> match = re.match(r"\x41", "A")
> ```

> [accordion] Unused class-private methods should be removed
>
> A method that is never called is dead code, and should be removed. Cleaning out dead code decreases the size of the maintained codebase, making it easier to understand the program and preventing bugs from being introduced.
>
> Python has no real private methods. Every method is accessible. There are however two conventions indicating that a method is not meant to be "public":
>
> <ul>
>   <li>
>     methods with a name starting with a single underscore (ex: \`\_mymethod) should be seen as non-public and might change without prior notice. They should not be used by third-party libraries or software. It is ok to use those methods inside the library defining them but it should be done with caution.
>   </li>
>
>   <li>
>     "class-private" methods have a name which starts with at least two underscores and ends with at most one underscore. These methods' names will be automatically mangled to avoid collision with subclasses' methods. For example \_\_mymethod will be renamed as \_classname\_\_mymethod, where classname\` is the method’s class name without its leading underscore(s). These methods shouldn’t be used outside of their enclosing class.
>   </li>
> </ul>
>
> This rule raises an issue when a class-private method (two leading underscores, max one underscore at the end) is never called inside the class. Class methods, static methods and instance methods will all raise an issue.
>
> ```python Bad theme={"theme":"css-variables"}
> class Noncompliant:
>
> @classmethod
> def __mangled_class_method(cls):  # Noncompliant
>     print("__mangled_class_method")
>
> @staticmethod
> def __mangled_static_method():  # Noncompliant
>     print("__mangled_static_method")
>
> def __mangled_instance_method(self):  # Noncompliant
>     print("__mangled_instance_method")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Compliant:
>
> def __init__(self):
>     Compliant.__mangled_class_method()
>     Compliant.__mangled_static_method()
>     self.__mangled_instance_method()
>
> @classmethod
> def __mangled_class_method(cls):
>     print("__mangled_class_method")
>
> @staticmethod
> def __mangled_static_method():
>     print("__mangled_static_method")
>
> def __mangled_instance_method(self):
>     print("__mangled_instance_method")
> ```

> [accordion] Passing a list to np.array should be preferred over passing a generator
>
> The creation of a NumPy array can be done in several ways, for example by passing a Python list to the np.array function.
> Another way would be to pass a generator to the `np.array function, but doing so creates a 0-dimensional array of objects and may not be the intended goal.
> This NumPy array will have a have a data type (dtype) of object` and could hold any Python objects.
>
> One of the characteristics of NumPy arrays is homogeneity, meaning all its elements are of the same type.
> Creating an array of objects allows the user to create heterogeneous array without raising any errors and creating such an array can lead to bugs further in the program.
>
> ```python Bad theme={"theme":"css-variables"}
> arr = np.array(x**2 for x in range(10))
>
> arr.reshape(1)
> arr.resize(2)
> arr.put(indices=1, values=3) # No issues raised.
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> arr = np.array(x**2 for x in range(10)) # Noncompliant: the resulting array will be of the data type: object.
>
> gen = (x*2 for x in range(5))
> arr = np.array(gen) # Noncompliant: the resulting array will be of the data type: object.
> ```

> [accordion] \* and \*\* should not be used in function calls
>
> `* and **, conventionally known as *args and **kwargs` (although any names can be used), can be used in either a function definition or in a function call. In a function definition, they allow a variable number of arguments to be passed. In a function call, they simply obscure the actual values being used in the call.
>
> ```python Bad theme={"theme":"css-variables"}
> my_arg_list = ("yellow", "green", 42)
> my_arg_dictionary = {"first" : "Sam", "next": 4, "last": my_obj}
> # many lines of code...
>
> function_with_args(*my_arg_list) #Noncompliant
> function_with_named_args(**my_arg_dictionary) #Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> function_with_args("yellow", "green", 42)
> function_with_named_args(first = "Sam", next = 4, last = my_obj)
> ```

> [accordion] Character classes should be preferred over reluctant quantifiers in regular expressions
>
> Using reluctant quantifiers (also known as lazy or non-greedy quantifiers) in patterns can often lead to needless backtracking, making the regex needlessly inefficient and potentially vulnerable to [catastrophic backtracking](https://www.regular-expressions.info/catastrophic.html). Particularly when using `.? or .+? to match anything up to some terminating character, it is usually a better idea to instead use a greedily or quantified negated character class containing the terminating character. For example <.+?> should be replaced with <[^>]> or <[^>]+>`.
>
> ```python Bad theme={"theme":"css-variables"}
> r'<.+?>'
> r'".*?"'
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> r'<[^>]+>'
> r'"[^"]*"'
> ```

> [accordion] The open builtin function should be called with a valid mode
>
> The open builtin function can open files in different modes. These modes are provided as a combination of characters. Using an invalid sequence of characters will make open fail with a ValueError.
>
> A valid mode:
>
> <ul>
>   <li>
>     should contain only one of the following characters: r (read), w (write), a (append), x (create).
>   </li>
>
>   <li>
>     should contain zero or one of the following characters: t (text), b (binary).
>   </li>
>
>   <li>
>     should contain zero or one + character (open for updating)
>   </li>
> </ul>
>
> For example: a, rt, r+ and w+b are valid modes.
>
> If no t or b character is provided the mode will default to t (text), so specifying r is equivalent to rt.
>
> **Note**: *In Python 2, providing an incorrect mode may have an undefined behavior (ex: it might ignore some characters)*
>
> ```python Bad theme={"theme":"css-variables"}
> with open("test.txt", "aw") as f:  # Noncompliant: ValueError
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> with open("test.txt", "a") as f:
> pass
> ```

> [accordion] HTML autoescape mechanism should not be globally disabled
>
> Template engines have an HTML autoescape mechanism that protects web applications against most common cross-site-scripting (XSS) vulnerabilities.
>
> By default, it automatically replaces HTML special characters in any template variables. This secure by design configuration should not be globally disabled.
>
> Escaping HTML from template variables prevents switching into any execution context, like `<script>`. Disabling autoescaping forces developers to manually escape each template variable for the application to be safe. A more pragmatic approach is to escape by default and to manually disable escaping when needed.
>
> A successful exploitation of a cross-site-scripting vulnerability by an attacker allow him to execute malicious JavaScript code in a user’s web browser. The most severe XSS attacks involve:
>
> <ul>
>   <li>
>     Forced redirection
>   </li>
>
>   <li>
>     Modify presentation of content
>   </li>
>
>   <li>
>     User accounts takeover after disclosure of sensitive information like session cookies or passwords
>   </li>
> </ul>
>
> This rule supports the following libraries:
>
> <ul>
>   <li>
>     [Django Templates](https://github.com/django/django)
>   </li>
>
>   <li>
>     [Jinja2](https://github.com/pallets/jinja)
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> from jinja2 import Environment
>
> env = Environment() # Noncompliant; New Jinja2 Environment has autoescape set to false
> env = Environment(autoescape=False) # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from jinja2 import Environment
> env = Environment(autoescape=True) # Compliant
> ```

> [accordion] Bare raise statements should only be used in except blocks
>
> A bare raise statement, i.e. a raise with no exception provided, will re-raise the last active exception in the current scope:
>
> ```python Bad theme={"theme":"css-variables"}
> def foo():
> try:
>     ...
> except ValueError as e:
>     raise # this will re-raise "e"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> raise  # Noncompliant: no active exception
>
> def foo():
> raise  # Noncompliant: no active exception
> try:
>     raise  # Noncompliant: no active exception
> except ValueError:
>     handle_error()
>
> def handle_error():
> raise  # Noncompliant: this is not reliable
> ```

> [accordion] yield and return should not be used outside functions
>
> yield and return only make sense in the context of functions. Using them outside a function raises a SyntaxError.
>
> If the goal is to break out of a loop, use break instead of return.
>
> ```python Bad theme={"theme":"css-variables"}
> a = 1
> while a < 3:
> if a % 2 == 0:
>     return # Noncompliant: return is outside of a function
> a += 1
>
> for n in range(5):
> yield n # Noncompliant: yield is outside of a function
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> a = 1
> while a < 3:
> if a % 2 == 0:
>     break
> a += 1
>
> def gen():
> for n in range(5):
>   yield n
> ```

> [accordion] The output of functions that dont return anything should not be used
>
> If a function does not return anything, it makes no sense to use its output. Specifically, passing it to another function, or assigning its "result" to a variable is probably a bug because such functions return nothing, which is probably not what was intended.
>
> ```python Bad theme={"theme":"css-variables"}
> def foo():
> l = [1, 2, 3]
> result = l.append(42) # Noncompliant, `append` mutates list l
> return result
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def foo():
> l = [1, 2, 3]
> l.append(42)
> return l
> ```

> [accordion] locals() should not be passed to a Django render() function
>
> Using the "locals()" function to pass context to a Django "render()" function can lead to security vulnerabilities and unexpected behavior. "locals()" returns a dictionary of the current local scope, including any sensitive information that may be present in the function’s local namespace. This means that if "locals()" is used to pass context to "render()", sensitive data such as passwords, keys, and other secrets could be leaked.
>
> Additionally, using "locals()" to pass context can make code more difficult to read and understand. It can also make it harder to maintain code over time.
>
> ```python Bad theme={"theme":"css-variables"}
> def my_view(request):
> username = "alice"
> password = "p@ssw0rd"
> context = locals()
> return render(request, "my_template.html", context)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def my_view(request):
> username = "alice"
> context = {"username": username}
> return render(request, "my_template.html", context)
> ```

> [accordion] Constructor attributes of date and time objects should be in the range of possible values
>
> Setting a date attribute value with a value which is out of the range of possible values will lead to a ValueError.
>
> ```python Bad theme={"theme":"css-variables"}
> def foo():
> dt = datetime(year=2024, day=66, month=1, hour=16, minute=1) # ValueError: day is out of range for month
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def foo():
> dt = datetime(year=2024, day=1, month=1, hour=16, minute=1)
> ```

> [accordion] Assertions should not be made at the end of blocks expecting an exception
>
> Using `pytest.raises or unittest.TestCase.assertRaises` will assert that an exception is raised in the following block. Ending such block in an assertion means that the test can succeed with that last assertion never being executed.
>
> ```python Bad theme={"theme":"css-variables"}
> import pytest
> def foo(): return 1 / 0
> def bar(): return 42
> def test_something():
> with pytest.raises(ZeroDivisionError):
> foo()
> assert bar() == 42  # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import pytest
> def foo(): return 1 / 0
> def bar(): return 42
> def test_something():
> with pytest.raises(ZeroDivisionError):
> foo()
> assert bar() == 42
> ```

> [accordion] Values assigned to variables should match their type annotations
>
> Type hints in Python allow you to specify the expected types of variables and function return values. While type hints are not enforced at runtime, they serve as documentation and can be checked using static type checkers to catch type-related errors during development.
>
> When an assigned value type is incompatible with the type hint of the assigning variable, it can lead to several issues:
>
> <ul>
>   <li>
>     **Type-related bugs:** Assigning a value of an incompatible type to a variable with a specific type hint may lead to unexpected behavior or errors at runtime.
>   </li>
>
>   <li>
>     **Readability and maintainability:** Type hints improve code readability by explicitly stating the intended types of variables and functions. When the assigned value type doesn’t match the hint, it can confuse other developers and make the code harder to maintain.
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> def my_function():
> my_int: int = "string"  # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def my_function():
> my_str: str = "string"
> ```

> [accordion] Non-existent dictionary keys should not be accessed
>
> Trying to access a dictionary key that does not exist will raise a KeyError exception.
>
> When trying to access or remove a key that may not be there, several solutions are possible:
>
> <ul>
>   <li>
>     Use the get() method instead of a subscription. It will return None for a missing key instead of raising a KeyError.
>   </li>
>
>   <li>
>     Use the setdefault() method to provide keys that may be missing with a default value.
>   </li>
>
>   <li>
>     Check that the key is present in the dictionary with the if key in dict: construct.
>   </li>
>
>   <li>
>     Use a try/except block and handle the potential KeyError exception.
>   </li>
>
>   <li>
>     Use a defaultdict instead of a regular dict object, and provide a default\_factory attribute.
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> def foo():
> my_dict = {'k1': 42}
> ...
> value = my_dict['k2']  # Noncompliant: the key "k2" does not exist.
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def foo():
> my_dict = {'k1': 42}
> ...
> if 'k2' in my_dict:
>     value = my_dict['k2']
> ```

> [accordion] Property getter, setter and deleter methods should have the expected number of parameters
>
> Creating property accessors and mutators is quite common in Object-Oriented Programming. Python provides two main ways of implementing getters, setters and deleters; either with the \`@property decorator, or with the property function.
>
> \`class WithPropertyDecorator(object):
> @property
> def foo(self)
> return self.\_foo
>
> @foo.setter
> def foo(self, value):
> self.\_foo = value
>
> @foo.deleter
> def foo(self):
> del self.\_foo
>
> class WithPropertyMethod(object):
> def get\_foo(self):
> return self.\_foo
>
> def set\_foo(self, value):
> self.\_foo = value
>
> def del\_foo(self):
> del self.\_foo
>
> foo = property(get\_foo, set\_foo, del\_foo, "'foo' property.")\`
>
> The following program illustrates how using the built-in operations will call the custom methods defined above.
>
> \`with\_decorator = WithPropertyDecorator()
> with\_decorator.foo = 1 # the method defined under @foo.setter will be called.
> some\_var = with\_decorator.foo # the method defined under @foo.getter will be called.
> del with\_decorator.foo # the method defined under @foo.deleter will be called.
>
> with\_method = WithPropertyMethod()
> with\_method.foo = 1 # the method set\_foo will be called.
> some\_var = with\_method.foo # the method get\_foo will be called.
> del with\_method.foo # the method del\_foo will be called.
> \`
>
> Defining a property this way allows for flexibility when refactoring the implementation of the getters, setters and deleters method, as all the accesses and modifications are done through the Python built-in operators (=,.) and keyword (del).
>
> Property getter, setter and deleter methods are called by the Python interpreter with a specific number of arguments:
>
> <ul>
>   <li>
>     Property getter and deleter methods only require a "self" argument.
>   </li>
>
>   <li>
>     Property setter methods require a "self" argument as well as a value.
>   </li>
> </ul>
>
> Adding any other parameters, or removing these mandatory parameters will throw a TypeError\` exception at runtime when trying to access or modify the property.
>
> ```python Bad theme={"theme":"css-variables"}
> class A:
> @property
> def foo(self, unexpected, unexpected2):  # Noncompliant: too many parameters.
>     return self._foo
>
> @foo.setter
> def foo(self):  # Noncompliant: a parameter is missing.
>     self._foo = 42
>
> @foo.deleter
> def foo(self, unexpected):  # Noncompliant: too many parameters.
>     del self._foo
>
> class B:
> def get_foo(self, unexpected):  # Noncompliant: too many parameters.
>     return self._foo
>
> def set_foo(self, value, unexpected):  # Noncompliant: too many parameters.
>     self._foo = value
>
> def del_foo(self, unexpected):  # Noncompliant: too many parameters.
>     del self._foo
>
> foo = property(get_foo, set_foo, del_foo, "'foo' property.")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class A:
> @property
> def foo(self):
>     return self._foo
>
> @foo.setter
> def foo(self, value):
>     self._foo = value
>
> @foo.deleter
> def foo(self):
>     del self._foo
>
> class B:
> def get_foo(self):
>     return self._foo
>
> def set_foo(self, value):
>     self._foo = value
>
> def del_foo(self):
>     del self._foo
>
> foo = property(get_foo, set_foo, del_foo, "'foo' property.")
> ```

> [accordion] Any should not be used as a type hint
>
> The type hint Any represents any possible Python type, on which all operations are possible. This conveys the information that all operations could be possible on a value annotated with Any, making the value dynamically-typed.
>
> Any as a type hint provides no information about the expected type of the variable or parameter, essentially losing the benefits of type hinting. This can make the code less clear and harder to understand and will reduce the code insight capabilities of IDEs and static analysis tools.
>
> ```python Bad theme={"theme":"css-variables"}
> def foo(arg: Any)  Any:
> if isinstance(arg, int):
>     return arg + 1
> else:
>     return arg.upper()
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def foo(arg: int | str)  int | str:
> if isinstance(arg, int):
>     return arg + 1
> else:
>     return arg.upper()
> ```

> [accordion] dtype parameter should be provided when using pandas.read\_csv or pandas.read\_table
>
> The pandas library provides an easy way to load data from documents hosted locally or remotely, for example with the `pandas.read_csv or pandas.read_table` functions:
>
> ```python Bad theme={"theme":"css-variables"}
> import pandas as pd
>
> df = pd.read_csv("my_file.csv")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import pandas as pd
>
> def foo():
> return pd.read_csv("my_file.csv") # Noncompliant: it is unclear which type of data the data frame holds.
> ```

> [accordion] Parameters should be passed in the correct order
>
> When the names of parameters in a function/method call match the names of the method arguments, it contributes to clearer, more readable code. However, when the names match, but are passed in a different order than the function/method arguments, it indicates a mistake in the parameter order which will likely lead to unexpected results.
>
> ```python Bad theme={"theme":"css-variables"}
> def move_point(coord, speed):
> new_x = coord[0] + speed[0]
> new_y = coord[1] + speed[1]
> return (new_x, new_y)
>
> coord = (3, 4)
> speed = (1, 2)
>
> move_point(speed, coord)  # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def move_point(coord, speed):
> new_x = coord[0] + speed[0]
> new_y = coord[1] + speed[1]
> return (new_x, new_y)
>
> coord = (3, 4)
> speed = (1, 2)
>
> move_point(coord, speed)
> ```

> [accordion] All except blocks should be able to catch exceptions
>
> Exceptions handlers (except) are evaluated in the order they are written. Once a match is found, the evaluation stops.
>
> In some contexts, an except block is dead code as it will never catch any exception:
>
> <ul>
>   <li>
>     If there is a handler for a base class followed by a handler for class derived from that base class, the second handler will never trigger: The handler for the base class will match the derived class, and will be the only executed handler.
>   </li>
>
>   <li>
>     When multiple except statements try to catch the same exception class, only the first one will be executed.
>   </li>
>
>   <li>
>     In Python 3, BaseException is the parent of every exception class. When a BaseException is caught by an except clause, none of the subsequent except statement will catch anything. This is true as well for the bare except statement (except:).
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> def foo():
> try:
>     raise FloatingPointError()
> except (ArithmeticError, RuntimeError) as e: 
>     print(e)
> except FloatingPointError as e: # Noncompliant: FloatingPointError is a subclass of ArithmeticError.
>     print("Never executed")
> except OverflowError as e: # Noncompliant: OverflowError is a subclass of ArithmeticError.
>     print("Never executed")
>
> try:
>     raise TypeError()
> except TypeError as e: 
>     print(e)
> except TypeError as e: # Noncompliant: duplicate except.
>     print("Never executed")
>
> try:
>     raise ValueError()
> except BaseException as e:  
>     print(e)
> except: # Noncompliant: this is equivalent to "except BaseException" block.
>     print("Never executed")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def foo():
> try:
>     raise FloatingPointError()
> except FloatingPointError as e:
>     print("Executed")
> except OverflowError as e:
>     print("Executed")
> except (ArithmeticError, RuntimeError) as e: 
>     print(e)
>
> try:
>     raise TypeError()
> except TypeError as e: 
>     print(e)
>
> try:
>     raise ValueError()
> except BaseException as e:  
>     print(e)
> ```

> [accordion] Unnecessary imports should be removed
>
> Importing names and not using them can be a source of confusion and lead to maintainability issues.
>
> Such imports should be removed.
>
> ```python Bad theme={"theme":"css-variables"}
> from mymodule import foo, bar, qix  # Noncompliant: bar is unused
>
> foo()
> qix()
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from mymodule import foo, qix
>
> foo()
> qix()
> ```

> [accordion] Allowing unrestricted outbound communications is security-sensitive
>
> utbound communications can lead to data leaks.
>
> A restrictive security group is an additional layer of protection that might
> prevent the abuse or exploitation of a resource. For example, it complicates the
> exfiltration of data in the case of a successfully exploited vulnerability.
>
> When deciding if outgoing connections should be limited, consider that limiting
> the connections results in additional administration and maintenance work.
>
> ```python Bad theme={"theme":"css-variables"}
> from aws_cdk import (
> aws_ec2 as ec2
> )
>
> ec2.SecurityGroup(  # Sensitive; allow_all_outbound is enabled by default
> self,
> "example",
> vpc=vpc
> )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from aws_cdk import (
> aws_ec2 as ec2
> )
>
> sg = ec2.SecurityGroup(
> self,
> "example",
> vpc=vpc,
> allow_all_outbound=False
> )
>
> sg.add_egress_rule(
> peer=ec2.Peer.ipv4("203.0.113.127/32"),
> connection=ec2.Port.tcp(443)
> )
> ```

> [accordion] Backticks should not be used
>
> In Python 2, backticks are a deprecated alias for `repr()`. The syntax was removed in Python 3. To make the transition to Python 3 easier, they should not be used anymore.
>
> ```python Bad theme={"theme":"css-variables"}
> return `num`  # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> return repr(num)
> ```

> [accordion] Implicit string and byte concatenations should not be confusing
>
> Python concatenates adjacent string or byte literals at compile time. It means that `"a" "b" is equivalent to "ab"`.
> This is sometimes used to split a long string on multiple lines. However an implicit string concatenation can also be very confusing.
> In the following contexts it might indicate that a comma was forgotten:
>
> <ul>
>   <li>
>     when the two strings are on the same line. This could be interpreted as an incorrectly formatted tuple (parentheses are not mandatory to create a tuple, only the comma is).
>   </li>
>
>   <li>
>     when the strings are in a list, a set or a tuple.
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> def func():
> return "item1" "item2"  # Noncompliant: a comma is missing to return a tuple.
>
> ["1"  # Noncompliant: a comma is missing.
> "2",
> "a very"  # Noncompliant: a "+" is missing.
> "long string"]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def func():
> return "item1", "item2"
>
> ["1",
> "2",
> "a very" +
> "long string"]
> ```

> [accordion] String formatting should be used correctly
>
> A format string is a string that contains placeholders, usually represented by special characters such as "%s" or "{}", depending on the technology in use. These placeholders are replaced by values when the string is printed or logged. Thus, it is required that a string is valid and arguments match replacement fields in this string.
>
> This applies to [the % operator](https://docs.python.org/3/tutorial/inputoutput.html#old-string-formatting), the [str.format](https://docs.python.org/3/tutorial/inputoutput.html#the-string-format-method) method, and loggers from the [logging](https://docs.python.org/3/library/logging.html) module. Internally, the latter use the %-formatting. The only difference is that they will log an error instead of raising an exception when the provided arguments are invalid.
>
> Formatted string literals (also called "f-strings"; available since Python 3.6) are generally simpler to use, and any syntax mistake will cause a failure at compile time. However, it is easy to forget curly braces, which will not lead to any detectable errors.
>
> This rule raises an issue when:
>
> <ul>
>   <li>
>     A string formatted with % will not return the expected text because some arguments are unused.
>   </li>
>
>   <li>
>     A string formatted with str.format will not return the expected string because some arguments are unused.
>   </li>
>
>   <li>
>     An "f-string" doesn’t contain any replacement field, which probably means some curly braces are missing.
>   </li>
>
>   <li>
>     Loggers will log an error because their message is not formatted properly.
>   </li>
> </ul>
>
> Rule S2275 covers cases where formatting a string will raise an exception.
>
> ```python Bad theme={"theme":"css-variables"}
> "Error %(message)s" % {"message": "something failed", "extra": "some dead code"}  # Noncompliant. Remove the unused argument "extra" or add a replacement field.
>
> "Error: User {} has not been able to access []".format("Alice", "MyFile")  # Noncompliant. Remove 1 unexpected argument or add a replacement field.
>
> user = "Alice"
> resource = "MyFile"
> message = f"Error: User [user] has not been able to access [resource]"  # Noncompliant. Add replacement fields or use a normal string instead of an f-string.
>
> import logging
> logging.error("Error: User %s has not been able to access %s", "Alice")  # Noncompliant. Add 1 missing argument.
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> "Error %(message)s" % {"message": "something failed"}
>
> "Error: User {} has not been able to access {}".format("Alice", "MyFile")
>
> user = "Alice"
> resource = "MyFile"
> message = f"Error: User {user} has not been able to access {resource}"
>
> import logging
> logging.error("Error: User %s has not been able to access %s", "Alice", "MyFile")
> ```

> [accordion] global should not be used
>
> Global variables are a useful construct, but they should not be abused. Functions access the global scope through the `global` keyword, but this practice considerably reduce the function’s readability and reusability. Instead, the global variable should be passed as a parameter to the function.
>
> ```python Bad theme={"theme":"css-variables"}
> NAME = 'Joe'
>
> def write_name();
> global NAME   # Noncompliant
> print NAME
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def write_name(name);
> print name
> ```

> [accordion] Dictionary definitions should not contain duplicate keys
>
> During dictionary use, it is normal that you might want to replace the value associated with one of the dictionary’s keys. But do so during the initial definition of a dictionary, and you’ve probably made an error.
>
> This rule raises an issue when the same key is used multiple times in the initial definition of a dictionary.
>
> ```python Bad theme={"theme":"css-variables"}
> fruit = {"apple":4, "pear":6, "quince":29, "apple": 8}  # Noncompliant; "apple" is used in positions 0 and 3
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> fruit = {"apple":4, "pear":6, "quince":29, "potato": 8}
> ```

> [accordion] Django signal handler functions should have the @receiver decorator on top of all other decorators
>
> In Django, the '@receiver' decorator is used to register signal handlers. These handlers are used to respond to events that occur in the application, such as a user logging in or a database record being saved.
>
> The order in which decorators are applied can have a significant impact on their behavior. In the case of the @receiver decorator, it is important that it is applied first, before any other decorators, in order to ensure that the signal handler is registered correctly.
>
> If the '@receiver' decorator is not applied first, the decorators placed above it will be ignored, which can result in unexpected behavior or even errors in the application.
>
> ```python Bad theme={"theme":"css-variables"}
> from django.dispatch import receiver
> from django.views.decorators.csrf import csrf_exempt
>
> @csrf_exempt
> @receiver(some_signal)
> def my_handler(sender, **kwargs):
> ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from django.dispatch import receiver
> from django.views.decorators.csrf import csrf_exempt
>
> @receiver(some_signal)
> @csrf_exempt
> def my_handler(sender, **kwargs):
> ...
> ```

> [accordion] The most specific unittest assertion should be used
>
> The \`unittest module provides assertion methods specific to common types and operations. Both versions will test the same things, but the dedicated one will provide a better error message, simplifying the debugging process.
>
> This rule reports an issue when an assertion can be simplified by using a more specific function. The array below gives a list of assertions on which an issue will be raised, and which function should be used instead:
>
> ```python Bad theme={"theme":"css-variables"}
> import unittest
> class SomeTest(unittest.TestCase):
> def test_something(self):
> x = foo()
> y = bar()
> self.assertFalse(x == y)  # Noncompliant
> self.assertTrue(x < y)  # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class SomeTest(unittest.TestCase):
> def test_something(self):
> x = foo()
> y = bar()
> self.assertNotEqual(x, y)
> self.assertLess(x, y)
> ```

> [accordion] True and False should not be used as identifiers
>
> Python interprets `False as a "false" boolean value, and True` as a "true" boolean value. Assigning them other values could lead to unexpected behaviors.
>
> This rule raises an issue when "True" and "False", with any case, are used as identifiers.
>
> ```python Bad theme={"theme":"css-variables"}
> True = "red"  # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> color = "red"  # Noncompliant
> ```

> [accordion] Variables, classes and functions should be defined before being used
>
> Variables, Classes and functions should be defined before they are used, otherwise the code will fail.
>
> ```python Bad theme={"theme":"css-variables"}
> def noncompliant():
> foo()  # Noncompliant
> foo = sum
>
> func()  # Noncompliant
> def func():
>     pass
>
> MyClass()  # Noncompliant
> class MyClass:
>     pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def compliant():
> foo = sum
> foo()
>
> def func():
>     pass
> func()
>
> class MyClass:
>     pass
> MyClass()
> ```

> [accordion] Attributes should not be accessed on None values
>
> None is a built-in object that represents the absence of a value.
> It is often used as a placeholder value for variables that only sometimes hold a
> value or as a return value for method calls that have no result.
>
> Attributes and methods of symbols that sometimes can be None should only be
> accessed in circumstances where it is certain that they are not set to None.
> Otherwise, an AttributeError is raised, and the program is interrupted.
> Hence, this issue indicates a logical error as it results from incorrect
> assumptions about the state of variables or the results of computations.
>
> ```python Bad theme={"theme":"css-variables"}
> def render(file_path):
> if os.path.isfile(file_path):
>     data = interpret_csv(file_path)
> else:
>     data = None
>
> # ...
>
> data.plot_graph() # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def render(file_path):
> if os.path.isfile(file_path):
>     data = interpret_csv(file_path)
> else:
>     data = None
>
> # ...
>
> if data is not None:
>     data.plot_graph()
> else:
>     print("No data available.")
> ```

> [accordion] Arguments given to functions should be of an expected type
>
> The CPython interpreter does not check types of arguments when functions are called.
> However, a function can express the type it expects for each argument in its documentation or
> by using [Type Hints](https://www.python.org/dev/peps/pep-0484/).
> While the code may initially work as intended, not respecting the contract of an API may lead to bugs later
> when its implementation evolves or when type checks are added (i.e. with isinstance).
>
> This rule also checks argument types for built-in functions.
>
> ```python Bad theme={"theme":"css-variables"}
> def func(var: str):
> pass
>
> func(42)  # Noncompliant: 42 is not of type str.
>
> round("not a number")  # Noncompliant: the builtin function round requires a number as first parameter.
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def func(var: str):
> pass
>
> func("42")
>
> round(1.2)
> ```

> [accordion] Calls should not use too many positional arguments
>
> You’re allowed to make function calls with positionally-identified parameters or with named parameters. In long parameter lists, explicitly naming your parameters both eliminates the risk of swapping parameter values and makes the call clearer to maintainers.
>
> ```python Bad theme={"theme":"css-variables"}
> def coordinateSurpriseParty(self, hostName, guestOfHonor, caterer, invitees, peopleNotToInvite):
> # ...
>
> host="John"
> guestOfHonor="Fred"
> caterer="Barry"
> invitees="Thea, Will, Mark, Mary"
> peopleToExclude="Susan, Alberta, Frank, Larry"
>
> coordinateSurpriseParty(caterer, host, guestOfHonor, peopleToExclude, invitees)  # Noncompliant; this party will be a train wreck!
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def coordinateSurpriseParty(self, hostName, guestOfHonor, caterer, invitees, peopleNotToInvite):
> # ...
>
> host="John"
> guestOfHonor="Fred"
> caterer="Barry"
> invitees="Thea, Will, Mark, Mary"
> peopleToExclude="Susan, Alberta, Frank, Larry"
>
> coordinateSurpriseParty(caterer=caterer, hostName=host, geustOfHonor=guestOfHonor, peopleNotToInvite=peopleToExclude, invitees=invitees)
> ```

> [accordion] The print statement should not be used
>
> The `print` statement was removed in Python 3.0. The built-in function should be used instead.
>
> ```python Bad theme={"theme":"css-variables"}
> print '1'  # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> print('1')
> ```

> [accordion] Functions should use return consistently
>
> Because it is dynamically typed, Python does not enforce a return type on a function. This means that different paths through a function can return different types of values, which can be very confusing to the user and significantly harder to maintain.
>
> In particular, it is consequently also possible to mix empty `return statements (implicitly returning None) with some returning an expression. This rule verifies that all the return` statements from a function are consistent.
>
> ```python Bad theme={"theme":"css-variables"}
> def foo(a): # Noncompliant, function will return "true" or None
> if a == 1:
> return True
> return
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def foo(a):
> if a == 1:
> return True
> return False
> ```

> [accordion] GraphQL queries should not be vulnerable to Denial of Service attacks
>
> When a server receives a deeply nested query, it attempts to resolve all the
> requested data. This process can consume a substantial amount of computational
> resources, leading to a slowdown in server response times.
>
> ```python Bad theme={"theme":"css-variables"}
> from graphql_server.flask import GraphQLView
>
> app.add_url_rule("/api",
> view_func=GraphQLView.as_view(  # Noncompliant
>     name="api",
>     schema=schema,
> )
> )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from graphql_server.flask import GraphQLView
> from graphene.validation import depth_limit_validator
>
> app.add_url_rule("/api",
> view_func=GraphQLView.as_view(
>     name="api",
>     schema=schema,
>     validation_rules=[
>        depth_limit_validator(10) # Choose a value that fits your application's requirements
>     ]
> )
> )
> ```

> [accordion] A reason should be provided when skipping a test
>
> When a test fails due, for example, to infrastructure issues, you might want to ignore it temporarily. But without some kind of notation about why the test is being ignored, it may never be reactivated. Such tests are difficult to address without comprehensive knowledge of the project, and end up polluting their projects.
>
> This rule raises an issue for each skipped test with "unittest.skip" or "pytest.mark.skip" without providing a reason argument.
>
> ```python Bad theme={"theme":"css-variables"}
> import unittest
> class MyTest(unittest.TestCase):
> @unittest.skip  # Noncompliant
> def test_something(self): ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import unittest
> class MyTest(unittest.TestCase):
> @unittest.skip("need to fix something")
> def test_something(self): ...
> ```

> [accordion] Break, continue and return statements should not occur in finally blocks
>
> Using \`return, break or continue in a finally block suppresses the propagation of any unhandled exception which was raised in the try, else or except blocks. It will also ignore their return statements.
>
> [SystemExit](https://docs.python.org/3/library/exceptions.html#SystemExit) is raised when sys.exit() is called. [KeyboardInterrupt](https://docs.python.org/3/library/exceptions.html#KeyboardInterrupt) is raised when the user asks the program to stop by pressing interrupt keys. Both exceptions are expected to propagate up until the application stops. It is ok to catch them when a clean-up is necessary but they should be raised again immediately. They should never be ignored.
>
> If you need to ignore every other exception you can simply catch the Exception class. However you should be very careful when you do this as it will ignore other important exceptions such as [MemoryError](https://docs.python.org/3/library/exceptions.html#MemoryError)
>
> In python 2 it is possible to raise old style classes. You can use a bare except: statement to catch every exception. Remember to still reraise SystemExit and KeyboardInterrupt.
>
> This rule raises an issue when a jump statement (break, continue, return\`) would force the control flow to leave a finally block.
>
> ```python Bad theme={"theme":"css-variables"}
> def find_file_which_contains(expected_content, paths):
> file = None
> for path in paths:
>     try:
>         # "open" will raise IsADirectoryError if the provided path is a directory but it will be stopped by the  "return" and "continue"
>         file = open(path, 'r')
>         actual_content = file.read()
>     except FileNotFoundError as exception:
>         # This exception will never pass the "finally" block because of "return" and "continue"
>         raise ValueError(f"'paths' should only contain existing files. File ${path} does not exist.")
>     finally:
>         file.close()
>         if actual_content != expected_content:
>             # Note that "continue" is allowed in a "finally" block only since python 3.8
>             continue  # Noncompliant. This will prevent exceptions raised by the "try" block and "except" block from raising.
>         else:
>             return path # Noncompliant. Same as for "continue"
> return None
>
> # This will return None instead of raising ValueError from the "except" block
> find_file_which_contains("some content", ["file_which_does_not_exist"])
>
> # This will return None instead of raising IsADirectoryError from the "try" block
> find_file_which_contains("some content", ["a_directory"])
>
> import sys
>
> while True:
> try:
>     sys.exit(1)
> except (SystemExit) as e:
>     print("Exiting")
>     raise
> finally:
>     break  # This will prevent SystemExit from raising
>
> def continue_whatever_happens_noncompliant():
> for i in range(10):
>     try:
>         raise ValueError()
>     finally:
>         continue  # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> # Note that using "with open(...) as" would be better. We keep the example as is just for demonstration purpose.
>
> def find_file_which_contains(expected_content, paths):
> file = None
> for path in paths:
>     try:
>         file = open(path, 'r')
>         actual_content = file.read()
>         if actual_content != expected_content:
>             continue
>         else:
>             return path
>     except FileNotFoundError as exception:
>         raise ValueError(f"'paths' should only contain existing files. File ${path} does not exist.")
>     finally:
>         if file:
>             file.close()
> return None
>
> # This raises ValueError
> find_file_which_contains("some content", ["file_which_does_not_exist"])
>
> # This raises IsADirectoryError
> find_file_which_contains("some content", ["a_directory"])
>
> import sys
>
> while True:
> try:
>     sys.exit(1)
> except (SystemExit) as e:
>     print("Exiting")
>     raise # SystemExit is re-raised
>
> import logging
>
> def continue_whatever_happens_compliant():
> for i in range(10):
>     try:
>         raise ValueError()
>     except Exception:
>         logging.exception("Failed")  # Ignore all "Exception" subclasses yet allow SystemExit and other important exceptions to pass
> ```

> [accordion] Type aliases should be declared with a type statement
>
> Since Python 3.12 the keyword type is used to defined type aliases.
> It replaces the following construct:
>
> ```python Bad theme={"theme":"css-variables"}
> from typing import TypeAlias, TypeVar
>
> _T = TypeVar("_T")
>
> MyTypeAlias: TypeAlias = set[_T]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> type MyTypeAlias[T] = set[T]
> ```

> [accordion] Unused scope-limited definitions should be removed
>
> When a class or function is defined in a parent function or method, it is only visible in this parent function or method’s scope.
> If the defined class or function is not used within this scope it is dead code (unnecessary, inoperative code) that should be removed.
>
> Cleaning out dead code decreases the size of the maintained codebase, making it easier to understand the program and preventing bugs from being introduced.
>
> ```python Bad theme={"theme":"css-variables"}
> def parent_function():
> def nested_function():  # Noncompliant: this function is never used in this scope.
>     print("nested_function")
>
> class NestedClass:  # Noncompliant: this class is never used in this scope.
>     def __init__(self):
>         print("NestedClass")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def parent_function():
> class NestedClass:
>     def __init__(self):
>         print("NestedClass")
>
> NestedClass()
> ```

> [accordion] pass should not be used needlessly
>
> The use of a pass statement where it is not required by the syntax is redundant. It makes the code less readable and its intent confusing.
>
> To fix this issue, remove pass statements that do not affect the behaviour of the program.
>
> ```python Bad theme={"theme":"css-variables"}
> def foo(arg):
> print(arg)
> pass # Noncompliant: the `pass` statement is not needed as it does not change the behaviour of the program.
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def foo(arg):
> print(arg)
> ```

> [accordion] The 12-hour format should be used with the AM/PM marker, otherwise the 24-hour format should be used
>
> The %p directive in the strftime method is used to represent the AM/PM marker in a time string. It is commonly used in conjunction with the %I directive, which represents the hour in a 12-hour clock.
>
> Using the 24-hour format directive with an AM/PM marker can lead to unwanted results e.g.:
>
> ```python Bad theme={"theme":"css-variables"}
> time_string = time(16,0).strftime("%H:%M %p")
> print(time_string)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> time_string = time(16,0).strftime("%I:%M")
> print(time_string)
> ```

> [accordion] Boolean checks should not be inverted
>
> It is needlessly complex to invert the result of a boolean comparison. The opposite comparison should be made instead.
>
> ```python Bad theme={"theme":"css-variables"}
> if not a == 2:        # Noncompliant
> b = not i < 10    # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> if a != 2 :
> b = i >= 10
> ```

> [accordion] Regular expressions should be syntactically valid
>
> Regular expressions have their own syntax that is understood by regular expression engines. Those engines will throw an exception at runtime if they are given a regular expression that does not conform to that syntax.
>
> To avoid syntax errors, special characters should be escaped with backslashes when they are intended to be matched literally and references to capturing groups should use the correctly spelled name or number of the group.
>
> ```python Bad theme={"theme":"css-variables"}
> re.compile(r"([")
> re.sub(r"([", input, "{")
> re.compile(r"(\w+-(\d+)")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> re.compile(r"\(\[")
> input.replace("([", "{")
> re.compile(r"(\w+)-(\d+)")
> ```

> [accordion] Using publicly writable directories is security-sensitive
>
> Operating systems have global directories where any user has write access. Those folders are mostly used as temporary storage areas like \`/tmp in Linux based systems. An application  manipulating files from these folders is exposed to race conditions on filenames: a malicious user can try to create a file with a predictable name before the application does. A successful attack can result in other files being accessed, modified, corrupted or deleted. This risk is even higher if the application runs with elevated permissions.
>
> In the past, it has led to the following vulnerabilities:
>
> <ul>
>   <li>
>     [CVE-2012-2451](https://nvd.nist.gov/vuln/detail/CVE-2012-2451)
>   </li>
>
>   <li>
>     [CVE-2015-1838](https://nvd.nist.gov/vuln/detail/CVE-2015-1838)
>   </li>
> </ul>
>
> This rule raises an issue whenever it detects a hard-coded path to a publicly writable directory like /tmp (see examples bellow). It also detects access to environment variables that point to publicly writable directories, e.g., TMP and TMPDIR.
>
> <ul>
>   <li>
>     /tmp
>   </li>
>
>   <li>
>     /var/tmp
>   </li>
>
>   <li>
>     /usr/tmp
>   </li>
>
>   <li>
>     /dev/shm
>   </li>
>
>   <li>
>     /dev/mqueue
>   </li>
>
>   <li>
>     /run/lock
>   </li>
>
>   <li>
>     /var/run/lock
>   </li>
>
>   <li>
>     /Library/Caches
>   </li>
>
>   <li>
>     /Users/Shared
>   </li>
>
>   <li>
>     /private/tmp
>   </li>
>
>   <li>
>     /private/var/tmp
>   </li>
>
>   <li>
>     \Windows\Temp
>   </li>
>
>   <li>
>     \Temp
>   </li>
>
>   <li>
>     \TMP\`
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> import tempfile
>
> file = tempfile.TemporaryFile(dir="/tmp/my_subdirectory", mode="w+") # Compliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] Non-capturing groups without quantifier should not be used
>
> Sub-patterns can be wrapped by parentheses to build a group. This enables to restrict alternations, back reference the group or apply quantifier to the sub-pattern.
>
> If this group should not be part of the match result or if no reference to this group is required, a non-capturing group can be created by adding ?: behind the opening parenthesis.
>
> However, if this non-capturing group does not have a quantifier, or does not wrap an alternation, then imaging this group is redundant.
>
> ```python Bad theme={"theme":"css-variables"}
> r"(?:number)\d{2}"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> r"number\d{2}"
> r"(?:number)?\d{2}"
> ```

> [accordion] Superfluous curly brace quantifiers should be avoided
>
> Curly brace quantifiers in regular expressions can be used to have a more fine-grained control over how many times the character or the sub-expression preceeding them should occur. They can be used to match an expression exactly n times with \`{n}, between n and m times with {n,m}, or at least n times with n. In some cases, using such a quantifier is superfluous for the semantic of the regular expression, and it can be removed to improve readability. This rule raises an issue when one of the following quantifiers is encountered:
>
> <ul>
>   <li>
>     {1,1} or 1: they match the expression exactly once. The same behavior can be achieved without the quantifier.
>   </li>
>
>   <li>
>     {0,0} or 0\`: they match the expression zero times. The same behavior can be achieved by removing the expression.
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> r"ab{1,1}c"
> r"ab{1}c"
> r"ab{0,0}c"
> r"ab{0}c"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> r"abc"
> r"ac"
> ```

> [accordion] Statements should be on separate lines
>
> Putting multiple statements on a single line lowers the code readability and makes debugging the code more complex.
>
> Unresolved directive in \<stdin> - include::{noncompliant}\[]
>
> Write one statement per line to improve readability.
>
> Unresolved directive in \<stdin> - include::{compliant}\[]
>
> ```python Bad theme={"theme":"css-variables"}
> if (True): print("hello") # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> if (True): 
> print("hello")
> ```

> [accordion] Policies authorizing public access to resources are security-sensitive
>
> Resource-based policies granting access to all users can lead to information leakage.
>
> ```python Bad theme={"theme":"css-variables"}
> from aws_cdk.aws_iam import PolicyStatement, AnyPrincipal, Effect
> from aws_cdk.aws_s3 import Bucket
>
> bucket = Bucket(self, "ExampleBucket")
>
> bucket.add_to_resource_policy(PolicyStatement(
> effect=Effect.ALLOW,
> actions=["s3:*"],
> resources=[bucket.arn_for_objects("*")],
> principals=[AnyPrincipal()] # Sensitive
> ))
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from aws_cdk.aws_iam import PolicyStatement, AccountRootPrincipal, Effect
> from aws_cdk.aws_s3 import Bucket
>
> bucket = Bucket(self, "ExampleBucket")
>
> bucket.add_to_resource_policy(PolicyStatement(
> effect=Effect.ALLOW,
> actions=["s3:*"],
> resources=[bucket.arn_for_objects("*")],
> principals=[AccountRootPrincipal()]
> ))
> ```

> [accordion] Disabling CSRF protections is security-sensitive
>
> A cross-site request forgery (CSRF) attack occurs when a trusted user of a web application can be forced, by an attacker, to perform sensitive actions that he didn’t intend, such as updating his profile or sending a message, more generally anything that can change the state of the application.
>
> The attacker can trick the user/victim to click on a link, corresponding to the privileged action, or to visit a malicious web site that embeds a hidden web request and as web browsers automatically include cookies, the actions can be authenticated and sensitive.
>
> ```python Bad theme={"theme":"css-variables"}
> MIDDLEWARE = [
> 'django.middleware.security.SecurityMiddleware',
> 'django.contrib.sessions.middleware.SessionMiddleware',
> 'django.middleware.common.CommonMiddleware',
> 'django.middleware.csrf.CsrfViewMiddleware', # Compliant
> 'django.contrib.auth.middleware.AuthenticationMiddleware',
> 'django.contrib.messages.middleware.MessageMiddleware',
> 'django.middleware.clickjacking.XFrameOptionsMiddleware',
> ]
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def example(request): # Compliant
> return HttpResponse("default")
> ```

> [accordion] Alternation in regular expressions should not contain empty alternatives
>
> Alternation is used to match a single regular expression out of several possible regular expressions. If one of the alternatives is empty it would match any input, which is most probably a mistake.
>
> ```python Bad theme={"theme":"css-variables"}
> re.search(r"Jack|Peter|", "John") # Noncompliant - will match an empty string
> re.search(r"Jack||Peter", "John") # Noncompliant - will match an empty string
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> re.search(r"Jack|Peter", "John") # returns false
> ```

> [accordion] Authorizing HTTP communications with S3 buckets is security-sensitive
>
> By default, S3 buckets can be accessed through HTTP and HTTPs protocols.
>
> As HTTP is a clear-text protocol, it lacks the encryption of transported data, as well as the capability to build an authenticated connection. It means that a malicious actor who is able to intercept traffic from the network can read, modify or corrupt the transported content.
>
> ```python Bad theme={"theme":"css-variables"}
> import aws_cdk.aws_s3 as s3
> import aws_cdk.aws_iam as iam
>
> bucket = s3.Bucket(self, "bucket") # Sensitive
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> bucket = s3.Bucket(self, "bucket")
> bucket.add_to_resource_policy(iam.PolicyStatement(     # Sensitive
> effect=iam.Effect.DENY,
> resources=[bucket.bucket_arn],
> actions=["s3:SomeAction"],
> principals=[roles],
> conditions=[{"Bool": {"aws:SecureTransport": False}}]
> )
> )
> ```

> [accordion] Searching OS commands in PATH is security-sensitive
>
> When executing an OS command and unless you specify the full path to the executable, then the locations in your application’s `PATH environment variable will be searched for the executable. That search could leave an opening for an attacker if one of the elements in PATH` is a directory under his control.
>
> ```python Bad theme={"theme":"css-variables"}
> params = ["/usr/bin/binary", "arg"]
> subprocess.call(params)  # Compliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] Having a permissive Cross-Origin Resource Sharing policy is security-sensitive
>
> Having a permissive Cross-Origin Resource Sharing policy is security-sensitive. It has led in the past to the following vulnerabilities:
>
> <ul>
>   <li>
>     [CVE-2018-0269](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-0269)
>   </li>
>
>   <li>
>     [CVE-2017-14460](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-14460)
>   </li>
> </ul>
>
> [Same origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy) in browsers prevents, by default and for security-reasons, a javascript frontend to perform a cross-origin HTTP request to a resource that has a different origin (domain, protocol, or port) from its own. The requested target can append additional HTTP headers in response, called [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS), that act like directives for the browser and change the access control policy / relax the same origin policy.
>
> ```python Bad theme={"theme":"css-variables"}
> origin = request.headers['ORIGIN']
> resp = Response()
> resp.headers['Access-Control-Allow-Origin'] = origin # Sensitive
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> CORS_ORIGIN_ALLOW_ALL = False # Compliant
> ```

> [accordion] Character classes in regular expressions should not contain only one character
>
> Character classes in regular expressions are a convenient way to match one of several possible characters by listing the allowed characters or ranges of characters. If a character class contains only one character, the effect is the same as just writing the character without a character class.
>
> Thus, having only one character in a character class is usually a simple oversight that remained after removing other characters of the class.
>
> ```python Bad theme={"theme":"css-variables"}
> r"a[b]c"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> r"abc"
> ```

> [accordion] Collection content should not be replaced unconditionally
>
> ```python Bad theme={"theme":"css-variables"}
> def swap(mylist, index1, index2):
> tmp = mylist[index2]
> mylist[index2] = mylist[index1]
> mylist[index2] = tmp  # Noncompliant
>
> list2 = [0,1,2,3,4,5,6,7,8,9]
> list2[3:5] = [42,42]
> list2[3:5] = [42,42]  # Noncompliant
>
> mymap = {'a': {}}
> mymap['a']['b'] = 42
> mymap['a']['b'] = 42  # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] Allowing public network access to cloud resources is security-sensitive
>
> Enabling public network access to cloud resources can affect an organization’s
> ability to protect its data or internal operations from data theft or
> disruption.
>
> Depending on the component, inbound access from the Internet can be enabled
> via:
>
> <ul>
>   <li>
>     a boolean value that explicitly allows access to the public network.
>   </li>
>
>   <li>
>     the assignment of a public IP address.
>   </li>
>
>   <li>
>     database firewall rules that allow public IP ranges.
>   </li>
> </ul>
>
> Deciding to allow public access may happen for various reasons such as for
> quick maintenance, time saving, or by accident.
>
> This decision increases the likelihood of attacks on the organization, such as:
>
> <ul>
>   <li>
>     data breaches.
>   </li>
>
>   <li>
>     intrusions into the infrastructure to permanently steal from it.
>   </li>
>
>   <li>
>     and various malicious traffic, such as DDoS attacks.
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> from aws_cdk import aws_ec2 as ec2
>
> ec2.Instance(
> self,
> "vpc_subnet_public",
> instance_type=nano_t2,
> machine_image=ec2.MachineImage.latest_amazon_linux(),
> vpc=vpc,
> vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC) # Sensitive
> )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from aws_cdk import aws_ec2 as ec2
>
> ec2.CfnInstance(
> self,
> "cfn_public_exposed",
> instance_type="t2.micro",
> image_id="ami-0ea0f26a6d50850c5",
> network_interfaces=[
>     ec2.CfnInstance.NetworkInterfaceProperty(
>         device_index="0",
>         associate_public_ip_address=True, # Sensitive
>         delete_on_termination=True,
>         subnet_id=vpc.select_subnets(subnet_type=ec2.SubnetType.PUBLIC).subnet_ids[0]
>     )
> ]
> )
> ```

> [accordion] Using unencrypted RDS DB resources is security-sensitive
>
> Using unencrypted RDS DB resources exposes data to unauthorized access.
> This includes database data, logs, automatic backups, read replicas, snapshots,
> and cluster metadata.
>
> This situation can occur in a variety of scenarios, such as:
>
> <ul>
>   <li>
>     A malicious insider working at the cloud provider gains physical access to the storage device.
>   </li>
>
>   <li>
>     Unknown attackers penetrate the cloud provider’s logical infrastructure and systems.
>   </li>
> </ul>
>
> After a successful intrusion, the underlying applications are exposed to:
>
> <ul>
>   <li>
>     theft of intellectual property and/or personal data
>   </li>
>
>   <li>
>     extortion
>   </li>
>
>   <li>
>     denial of services and security bypasses via data corruption or deletion
>   </li>
> </ul>
>
> AWS-managed encryption at rest reduces this risk with a simple switch.
>
> ```python Bad theme={"theme":"css-variables"}
> from aws_cdk import (
> aws_rds as rds
> )
>
> class DatabaseStack(Stack):
> def __init__(self, scope: Construct, construct_id: str, **kwargs)  None:
>     super().__init__(scope, construct_id, **kwargs)
>     rds.DatabaseCluster( # Sensitive, unencrypted by default
>         self,
>         "example"
>     )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from aws_cdk import (
> aws_rds as rds
> )
>
> class DatabaseStack(Stack):
> def __init__(self, scope: Construct, construct_id: str, **kwargs)  None:
>     super().__init__(scope, construct_id, **kwargs)
>     rds.CfnDBCluster( # Sensitive, unencrypted by default
>         self,
>         "example"
>     )
> ```

> [accordion] General except clauses should not be used
>
> A general `catch` block seems like an efficient way to handle multiple possible exceptions. Unfortunately, it traps all exception types, casting too broad a net, and perhaps mishandling extraordinary cases. Instead, specific exception sub-types should be caught.
>
> ```python Bad theme={"theme":"css-variables"}
> try:
> result = do_the_thing(a)
> except:  #Noncompliant; no specific exception caught
> result = None
>
> try:
> result = do_the_thing(a)
> except Exception:  #Noncompliant; too generic to be the only exception type caught
> result = None
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> try:
> result = do_the_thing(a)
> except ZeroDivisionError:
> result = None
> except TypeError:
> result = -1
> ```

> [accordion] Delivering code in production with debug features activated is security-sensitive
>
> Development tools and frameworks usually have options to make debugging easier for developers. Although these features are useful during development, they should never be enabled for applications deployed in production. Debug instructions or error messages can leak detailed information about the system, like the application’s path or file names.
>
> ```python Bad theme={"theme":"css-variables"}
> from django.conf import settings
>
> settings.configure(DEBUG=True)  # Sensitive when set to True
> settings.configure(DEBUG_PROPAGATE_EXCEPTIONS=True)  # Sensitive when set to True
>
> def custom_config(config):
> settings.configure(default_settings=config, DEBUG=True)  # Sensitive
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> DEBUG = True  # Sensitive
> DEBUG_PROPAGATE_EXCEPTIONS = True  # Sensitive
> ```

> [accordion] Using unencrypted SageMaker notebook instances is security-sensitive
>
> Amazon SageMaker is a managed machine learning service in a hosted production-ready environment. To train machine learning models, SageMaker instances can process potentially sensitive data, such as personal information that should not be stored unencrypted. In the event that adversaries physically access the storage media, they cannot decrypt encrypted data.
>
> ```python Bad theme={"theme":"css-variables"}
> from aws_cdk import (
> aws_sagemaker as sagemaker
> )
>
> class CfnSagemakerStack(Stack):
> def __init__(self, scope: Construct, construct_id: str, **kwargs)  None:
>     super().__init__(scope, construct_id, **kwargs)
>
>     sagemaker.CfnNotebookInstance(
>         self, "Sensitive",
>         instance_type="instanceType",
>         role_arn="roleArn"
>     )  # Sensitive, no KMS key is set by default; thus, encryption is disabled
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from aws_cdk import (
> aws_sagemaker as sagemaker,
> aws_kms as kms
> )
>
> class CfnSagemakerStack(Stack):
> def __init__(self, scope: Construct, construct_id: str, **kwargs)  None:
>     super().__init__(scope, construct_id, **kwargs)
>
>     my_key = kms.Key(self, "Key")
>     sagemaker.CfnNotebookInstance(
>         self, "Compliant",
>         instance_type="instanceType",
>         role_arn="roleArn",
>         kms_key_id=my_key.key_id
>     )
> ```

> [accordion] Exceptions should not be ignored
>
> When exceptions occur, it is usually a bad idea to simply ignore them. Instead, it is better to handle them properly, or at least to log them.
>
> ```python Bad theme={"theme":"css-variables"}
> # pass
> try:
> # ...
> except:
> pass # Noncompliant
>
> # continue
> for i in tab:
> try:
>      # ...
> except:
>     continue # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def can_raise_exception():
> try:
>     # ...
> except:
>     raise # Compliant
> ```

> [accordion] Expanding archive files without controlling resource consumption is security-sensitive
>
> Successful Zip Bomb attacks occur when an application expands untrusted archive files without controlling the size of the expanded data, which can lead to denial of service. A Zip bomb is usually a malicious archive file of a few kilobytes of compressed data but turned into gigabytes of uncompressed data. To achieve this extreme [compression ratio](https://en.wikipedia.org/wiki/Data_compression_ratio), attackers will compress irrelevant data (eg: a long string of repeated bytes).
>
> ```python Bad theme={"theme":"css-variables"}
> import tarfile
>
> THRESHOLD_ENTRIES = 10000      
> THRESHOLD_SIZE = 1000000000
> THRESHOLD_RATIO = 10 
>
> totalSizeArchive = 0;
> totalEntryArchive = 0;
>
> tfile = tarfile.open("TarBomb.tar") 
> for entry in tfile:
> tarinfo = tfile.extractfile(entry)
>
> totalEntryArchive += 1
> sizeEntry = 0
> result = b''
> while True:
> sizeEntry += 1024
> totalSizeArchive += 1024
>
> ratio = sizeEntry / entry.size
> if ratio > THRESHOLD_RATIO:
>   # ratio between compressed and uncompressed data is highly suspicious, looks like a Zip Bomb Attack
>   break
>
> chunk = tarinfo.read(1024)
> if not chunk:
>   break
>
> result += chunk
>
> if totalEntryArchive > THRESHOLD_ENTRIES:
> # too much entries in this archive, can lead to inodes exhaustion of the system
> break 
>
> if totalSizeArchive > THRESHOLD_SIZE:
> # the uncompressed data size is too much for the application resource capacity
> break 
>
> tfile.close()
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import zipfile
>
> THRESHOLD_ENTRIES = 10000      
> THRESHOLD_SIZE = 1000000000
> THRESHOLD_RATIO = 10 
>
> totalSizeArchive = 0;
> totalEntryArchive = 0;
>
> zfile = zipfile.ZipFile('ZipBomb.zip', 'r')
> for zinfo in zfile.infolist():
> print('File', zinfo.filename)
> data = zfile.read(zinfo)
>
> totalEntryArchive += 1
>
> totalSizeArchive = totalSizeArchive + len(data)
> ratio = len(data) / zinfo.compress_size
> if ratio > THRESHOLD_RATIO:
>   # ratio between compressed and uncompressed data is highly suspicious, looks like a Zip Bomb Attack
>   break
>
> if totalSizeArchive > THRESHOLD_SIZE:
>   # the uncompressed data size is too much for the application resource capacity
>   break
>
> if totalEntryArchive > THRESHOLD_ENTRIES:
>   # too much entries in this archive, can lead to inodes exhaustion of the system
>   break
>
> zfile.close()
> ```

> [accordion] Allowing both safe and unsafe HTTP methods is security-sensitive
>
> An HTTP method is safe when used to perform a read-only operation, such as retrieving information. In contrast, an unsafe HTTP method is used to change the state of an application, for instance to update a user’s profile on a web application.
>
> Common safe HTTP methods are  GET, HEAD, or OPTIONS.
>
> Common unsafe HTTP methods are  POST, PUT and DELETE.
>
> Allowing both safe and unsafe HTTP methods to perform a specific operation on a web application could impact its security, for example CSRF protections are most of the time only protecting operations performed by unsafe HTTP methods.
>
> ```python Bad theme={"theme":"css-variables"}
> @require_http_methods(["POST"])
> def view(request):
> return HttpResponse("...")
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> @require_POST
> def view(request):
> return HttpResponse("...")
> ```

> [accordion] Policies granting all privileges are security-sensitive
>
> A policy that grants all permissions may indicate an improper access control, which violates [the principle of least privilege](https://en.wikipedia.org/wiki/Principle_of_least_privilege). Suppose an identity is granted full permissions to a resource even though it only requires read permission to work as expected. In this case, an unintentional overwriting of resources may occur and therefore result in loss of information.
>
> ```python Bad theme={"theme":"css-variables"}
> from aws_cdk.aws_iam import PolicyStatement, Effect
>
> PolicyStatement(
> effect=Effect.ALLOW,
> actions=["*"], # Sensitive
> resources=["arn:aws:iam:::user/*"]
> )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from aws_cdk.aws_iam import PolicyStatement, Effect
>
> PolicyStatement(
> effect=Effect.ALLOW,
> actions=["iam:GetAccountSummary"],
> resources=["arn:aws:iam:::user/*"]
> )
> ```

> [accordion] Mergeable if statements should be combined
>
> Nested code - blocks of code inside blocks of code - is eventually necessary, but increases complexity. This is why keeping the code as flat as possible, by avoiding unnecessary nesting, is considered a good practice.
>
> Merging if statements when possible will decrease the nesting of the code and improve its readability.
>
> ```python Bad theme={"theme":"css-variables"}
> if condition1:
> if condition2:             # Noncompliant
>     # ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> if condition1 and condition2:  # Compliant
> # ...
> ```

> [accordion] Functions and methods should not be empty
>
> An empty {operationName} is generally considered bad practice and can lead to confusion, readability, and maintenance issues.
> Empty {operationName}s bring no functionality and are misleading to others as they might think the {operationName} implementation fulfills a specific and identified requirement.
>
> There are several reasons for a {operationName} not to have a body:
>
> <ul>
>   <li>
>     It is an unintentional omission, and should be fixed to prevent an unexpected behavior in production.
>   </li>
>
>   <li>
>     It is not yet, or never will be, supported. In this case an exception should be thrown.
>   </li>
>
>   <li>
>     The method is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override.
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> import abc
>
> class MyAbstractClass(abc.ABC):
> @abc.abstractproperty
> def myproperty(self):
>     pass
>
> @abc.abstractclassmethod
> def myclassmethod(cls):
>     pass
>
> @abc.abstractmethod
> def mymethod(self):
>     pass
>
> @abc.abstractstaticmethod
> def mystaticmethod():
>     pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def shouldNotBeEmpty():  # Noncompliant - method is empty
> pass
>
> def notImplemented():  # Noncompliant - method is empty
> pass
>
> def emptyOnPurpose():  # Noncompliant - method is empty
> pass
> ```

> [accordion] Disabling versioning of S3 buckets is security-sensitive
>
> S3 buckets can be in three states related to versioning:
>
> <ul>
>   <li>
>     unversioned (default one)
>   </li>
>
>   <li>
>     enabled
>   </li>
>
>   <li>
>     suspended
>   </li>
> </ul>
>
> When the S3 bucket is unversioned or has versioning suspended it means that a new version of an object overwrites an existing one in the S3 bucket.
>
> It can lead to unintentional or intentional information loss.
>
> ```python Bad theme={"theme":"css-variables"}
> bucket = s3.Bucket(self, "bucket",
> versioned=False       # Sensitive
> )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> bucket = s3.Bucket(self, "bucket",
> versioned=True
> )
> ```

> [accordion] Regex lookahead assertions should not be contradictory
>
> Lookahead assertions are a regex feature that makes it possible to look ahead in the input without consuming it. It is often used at the end of regular expressions to make sure that substrings only match when they are followed by a specific pattern.
>
> For example, the following pattern will match an "a" only if it is directly followed by a "b". This does not consume the "b" in the process:
>
> Unresolved directive in \<stdin> - include::{lookahead}\[]
>
> However, lookaheads can also be used in the middle (or at the beginning) of a regex. In that case there is the possibility that what comes after the lookahead contradicts the pattern inside the lookahead. Since the lookahead does not consume input, this makes the lookahead impossible to match and is a sign that there’s a mistake in the regular expression that should be fixed.
>
> ```python Bad theme={"theme":"css-variables"}
> r"(?=a)b" # Noncompliant, the same character can't be equal to 'a' and 'b' at the same time
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> r"(?<=a)b"
> r"a(?=b)"
> ```

> [accordion] Using clear-text protocols is security-sensitive
>
> Clear-text protocols such as \`ftp, telnet, or http lack
> encryption of transported data, as well as the capability to build an
> authenticated connection. It means that an attacker able to sniff traffic from
> the network can read, modify, or corrupt the transported content. These
> protocols are not secure as they expose applications to an extensive range of
> risks:
>
> <ul>
>   <li>
>     sensitive data exposure
>   </li>
>
>   <li>
>     traffic redirected  to a malicious endpoint
>   </li>
>
>   <li>
>     malware-infected software update or installer
>   </li>
>
>   <li>
>     execution of client-side code
>   </li>
>
>   <li>
>     corruption of critical information
>   </li>
> </ul>
>
> Even in the context of isolated networks like offline environments or segmented
> cloud environments, the insider threat exists. Thus, attacks involving
> communications being sniffed or tampered with can still happen.
>
> For example, attackers could successfully compromise prior security layers by:
>
> <ul>
>   <li>
>     bypassing isolation mechanisms
>   </li>
>
>   <li>
>     compromising a component of the network
>   </li>
>
>   <li>
>     getting the credentials of an internal IAM account (either from a service
>     account or an actual person)
>   </li>
> </ul>
>
> In such cases, encrypting communications would decrease the chances of attackers
> to successfully leak data or steal credentials from other network components.
> By layering various security practices (segmentation and encryption, for
> example), the application will follow the *defense-in-depth* principle.
>
> Note that using the http\` protocol is being deprecated by
> [major web browsers](https://blog.mozilla.org/security/2015/04/30/deprecating-non-secure-http).
>
> In the past, it has led to the following vulnerabilities:
>
> <ul>
>   <li>
>     [CVE-2019-6169](https://nvd.nist.gov/vuln/detail/CVE-2019-6169)
>   </li>
>
>   <li>
>     [CVE-2019-12327](https://nvd.nist.gov/vuln/detail/CVE-2019-12327)
>   </li>
>
>   <li>
>     [CVE-2019-11065](https://nvd.nist.gov/vuln/detail/CVE-2019-11065)
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> url = "http://example.com" # Sensitive
> url = "ftp://anonymous@example.com" # Sensitive
> url = "telnet://anonymous@example.com" # Sensitive
>
> import telnetlib
> cnx = telnetlib.Telnet("towel.blinkenlights.nl") # Sensitive
>
> import ftplib
> cnx = ftplib.FTP("ftp.example.com") # Sensitive
>
> import smtplib
> smtp = smtplib.SMTP("smtp.example.com", port=587) # Sensitive
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from aws_cdk import (
> aws_elasticloadbalancingv2 as elbv2,
> )
>
> lb = elbv2.ApplicationLoadBalancer(
> self,
> "LB",
> vpc=vpc,
> internet_facing=True
> )
>
> lb.add_listener(
> "Listener-default",
> port=80, # Sensitive
> open=True
> )
> lb.add_listener(
> "Listener-http-explicit",
> protocol=elbv2.ApplicationProtocol.HTTP, # Sensitive
> port=8080,
> open=True
> )
> ```

> [accordion] Track lack of copyright and license headers
>
> Each source file should start with a header stating file ownership and the license which must be used to distribute the application.
>
> This rule must be fed with the header text that is expected at the beginning of every file.
>
> ```python Bad theme={"theme":"css-variables"}
> #
> # SonarQube, open source software quality management tool.
> # Copyright (C) 2008-2018 SonarSource
> # mailto:contact AT sonarsource DOT com
> #
> # SonarQube is free software; you can redistribute it and/or
> # modify it under the terms of the GNU Lesser General Public
> # License as published by the Free Software Foundation; either
> # version 3 of the License, or (at your option) any later version.
> #
> # SonarQube is distributed in the hope that it will be useful,
> # but WITHOUT ANY WARRANTY; without even the implied warranty of
> # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
> # Lesser General Public License for more details.
> #
> # You should have received a copy of the GNU Lesser General Public License
> # along with this program; if not, write to the Free Software Foundation,
> # Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
> #
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] Creating cookies without the HttpOnly flag is security-sensitive
>
> When a cookie is configured with the `HttpOnly attribute set to true, the browser guaranties that no client-side script will be able to read it. In most cases, when a cookie is created, the default value of HttpOnly is false and it’s up to the developer to decide whether or not the content of the cookie can be read by the client-side script. As a majority of Cross-Site Scripting (XSS) attacks target the theft of session-cookies, the HttpOnly` attribute can help to reduce their impact as it won’t be possible to exploit the XSS vulnerability to steal session-cookies.
>
> ```python Bad theme={"theme":"css-variables"}
> from flask import Response
>
> @app.route('/')
> def index():
> response = Response()
> response.set_cookie('key', 'value', httponly=True) # Compliant
> return response
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] Reluctant quantifiers in regular expressions should be followed by an expression that cant match the empty string
>
> When a reluctant (or lazy) quantifier is followed by a pattern that can match the empty string or directly by the end of the regex, it will always match zero times for \*? or one time for +?. If a reluctant quantifier is followed directly by the end anchor (\$), it  behaves indistinguishably from a greedy quantifier while being less efficient.
>
> This is likely a sign that the regex does not work as intended.
>
> ```python Bad theme={"theme":"css-variables"}
> re.replace(r"start\w*?(end)?", "x", "start123endstart456") # Noncompliant. In contrast to what one would expect, the result is not "xx"
>
> re.match(r"^\d*?$", "123456789") # Noncompliant. Matches the same as "/^\d*$/", but will backtrack in every position.
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> re.replace(r"start\w*?(end|$)", "x", "start123endstart456") # Result is "xx"
>
> re.match(r"^\d*$", "123456789")
> ```

> [accordion] Regular expression quantifiers and character classes should be used concisely
>
> A regular expression is a sequence of characters that specifies a match pattern in text. Among the most important concepts are:
>
> <ul>
>   <li>
>     Character classes: defines a set of characters, any one of which can occur in an input string for a match to succeed.
>   </li>
>
>   <li>
>     Quantifiers: used to specify how many instances of a character, group, or character class must be present in the input for a match.
>   </li>
>
>   <li>
>     Wildcard (.): matches all characters except line terminators (also matches them if the s flag is set).
>   </li>
> </ul>
>
> Many of these features include shortcuts of widely used expressions, so there is more than one way to construct a regular expression to achieve the same results.
> For example, to match a two-digit number, one could write \[0-9]{2,2} or \d2. The latter is not only shorter but easier to read and thus to maintain.
>
> This rule recommends replacing some quantifiers and character classes with more concise equivalents:
>
> <ul>
>   <li>
>     \d for \[0-9] and \D for \[^0-9]
>   </li>
>
>   <li>
>     \w for \[A-Za-z0-9\_] and \W for \`\[^A-Za-z0-9\_]
>   </li>
>
>   <li>
>     . for character classes matching everything (e.g. \[\w\W], \[\d\D], or \[\s\S] with s flag)
>   </li>
>
>   <li>
>     x? for x0,1, x\* for x0, x+ for x1, xN for xN,N
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> r"[0-9]"        # Noncompliant - same as r"\d"
> r"[^0-9]"       # Noncompliant - same as r"\D"
> r"[A-Za-z0-9_]" # Noncompliant - same as r"\w"
> r"[\w\W]"       # Noncompliant - same as r"."
> r"a{0,}"        # Noncompliant - same as r"a*"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> r"\d"
> r"\D"
> r"\w"
> r"."
> r"a*"
> ```

> [accordion] Disabling server-side encryption of S3 buckets is security-sensitive
>
> Server-side encryption (SSE) encrypts an object (not the metadata) as it is written to disk (where the S3 bucket resides) and decrypts it as it is read from disk. This doesn’t change the way the objects are accessed, as long as the user has the necessary permissions, objects are retrieved as if they were unencrypted. Thus, SSE only helps in the event of disk thefts, improper disposals of disks and other attacks on the AWS infrastructure itself.
>
> There are three SSE options:
>
> <ul>
>   <li>
>     Server-Side Encryption with Amazon S3-Managed Keys (SSE-S3)
>
>     <ul>
>       <li>
>         AWS manages encryption keys and the encryption itself (with AES-256) on its own.
>       </li>
>     </ul>
>   </li>
>
>   <li>
>     Server-Side Encryption with Customer Master Keys (CMKs) Stored in AWS Key Management Service (SSE-KMS)
>
>     <ul>
>       <li>
>         AWS manages the encryption (AES-256) of objects and encryption keys provided by the AWS KMS service.
>       </li>
>     </ul>
>   </li>
>
>   <li>
>     Server-Side Encryption with Customer-Provided Keys (SSE-C)
>
>     <ul>
>       <li>
>         AWS manages only the encryption (AES-256) of objects with encryption keys provided by the customer. AWS doesn’t store the customer’s encryption keys.
>       </li>
>     </ul>
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> bucket = s3.Bucket(self,"bucket",
> encryption=s3.BucketEncryption.UNENCRYPTED       # Sensitive
> )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> bucket = s3.Bucket(self,"bucket",
> encryption=s3.BucketEncryption.S3_MANAGED
> )
>
> # Alternatively with a KMS key managed by the user.
>
> bucket = s3.Bucket(self,"bucket",
> encryptionKey=access_key
> )
> ```

> [accordion] Using shell interpreter when executing OS commands is security-sensitive
>
> Arbitrary OS command injection vulnerabilities are more likely when a shell is spawned rather than a new process, indeed shell meta-chars can be used (when parameters are user-controlled for instance) to inject OS commands.
>
> ```python Bad theme={"theme":"css-variables"}
> # by default shell=False, a shell is not spawn
> subprocess.run(cmd)  # Compliant
> subprocess.Popen(cmd)  # Compliant
> subprocess.call(cmd)  # Compliant
> subprocess.check_call(cmd)  # Compliant
> subprocess.check_output(cmd)  # Compliant
>
> # always in a subprocess:
> os.spawnl(mode, path, *cmd)  # Compliant
> os.spawnle(mode, path, *cmd, env)  # Compliant
> os.spawnlp(mode, file, *cmd)  # Compliant
> os.spawnlpe(mode, file, *cmd, env)  # Compliant
> os.spawnv(mode, path, cmd)  # Compliant
> os.spawnve(mode, path, cmd, env)  # Compliant
> os.spawnvp(mode, file, cmd)  # Compliant
> os.spawnvpe(mode, file, cmd, env)  # Compliant
>
> (child_stdout) = os.popen(cmd, mode, 1)  # Compliant
> (_, output) = subprocess.getstatusoutput(cmd)  # Compliant
> out = subprocess.getoutput(cmd)  # Compliant
> os.startfile(path)  # Compliant
> os.execl(path, *cmd)  # Compliant
> os.execle(path, *cmd, env)  # Compliant
> os.execlp(file, *cmd)  # Compliant
> os.execlpe(file, *cmd, env)  # Compliant
> os.execv(path, cmd)  # Compliant
> os.execve(path, cmd, env)  # Compliant
> os.execvp(file, cmd)  # Compliant
> os.execvpe(file, cmd, env)  # Compliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> cmdsargs = ("use", "a", "sequence", "to", "directly", "start", "a", "subprocess")
>
> (_, child_stdout) = os.popen2(cmdsargs)  # Compliant
> (_, child_stdout, _) = os.popen3(cmdsargs)  # Compliant
> (_, child_stdout) = os.popen4(cmdsargs)  # Compliant
>
> (child_stdout, _) = popen2.popen2(cmdsargs)  # Compliant
> (child_stdout, _, _) = popen2.popen3(cmdsargs)  # Compliant
> (child_stdout, _) = popen2.popen4(cmdsargs)  # Compliant
> ```

> [accordion] Related if/else if statements should not have the same condition
>
> A chain of if/else if statements is evaluated from top to bottom. At most, only one branch will be executed: the first one with a condition that evaluates to true.
>
> Therefore, duplicating a condition automatically leads to dead code. Usually, this is due to a copy/paste error. At best, it’s simply dead code and at worst, it’s a bug that is likely to induce further bugs as the code is maintained, and obviously it could lead to unexpected behavior.
>
> ```python Bad theme={"theme":"css-variables"}
> if param == 1:
> openWindow()
> elif param == 2:
> closeWindow()
> elif param == 1:            # Noncompliant
> moveWindowToTheBackground()
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> if param == 1:
> openWindow()
> elif param == 2:
> closeWindow()
> elif param == 3:        
> moveWindowToTheBackground()
> ```

> [accordion] Using unencrypted SNS topics is security-sensitive
>
> Amazon Simple Notification Service (SNS) is a managed messaging service for application-to-application (A2A) and application-to-person (A2P) communication. SNS topics allows publisher systems to fanout messages to a large number of subscriber systems. Amazon SNS allows to encrypt messages when they are received. In the case that adversaries gain physical access to the storage medium or otherwise leak a message they are not able to access the data.
>
> ```python Bad theme={"theme":"css-variables"}
> from aws_cdk import (
> aws_sns as sns
> )
>
> class TopicStack(Stack):
> def __init__(self, scope: Construct, construct_id: str, **kwargs)  None:
>     super().__init__(scope, construct_id, **kwargs)
>     sns.Topic( # Sensitive, unencrypted by default
>         self,
>         "example"
>     )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from aws_cdk import (
> aws_sns as sns
> )
>
> class TopicStack(Stack):
> def __init__(self, scope: Construct, construct_id: str, **kwargs)  None:
>     super().__init__(scope, construct_id, **kwargs)
>     sns.CfnTopic( # Sensitive, unencrypted by default
>         self,
>         "example"
>     )
> ```

> [accordion] Regex boundaries should not be used in a way that can never be matched
>
> In regular expressions the boundaries \`^ and A can only match at the beginning of the input (or, in case of ^ in combination with the MULTILINE flag, the beginning of the line) and \$, \Z and \z only at the end.
>
> These patterns can be misused, by accidentally switching ^ and \$\` for example, to create a pattern that can never match.
>
> ```python Bad theme={"theme":"css-variables"}
> # This can never match because $ and ^ have been switched around
> r"$[a-z]+^" # Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> r"^[a-z]+$"
> ```

> [accordion] Alternatives in regular expressions should be grouped when used with anchors
>
> In regular expressions, anchors (`^, , alt1 would be anchored to the beginning, alt3 to the end and alt2` wouldn’t be anchored at all. Usually the intended behavior is that all alternatives are anchored at both ends. To achieve this, a non-capturing group should be used around the alternatives.
>
> In cases where it is intended that the anchors only apply to one alternative each, adding (non-capturing) groups around the anchors and the parts that they apply to will make it explicit which parts are anchored and avoid readers misunderstanding the precedence or changing it because they mistakenly assume the precedence was not intended.
>
> ```python Bad theme={"theme":"css-variables"}
> r"^a|b|c$"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> r"^(?:a|b|c)$"
> ```

> [accordion] Formatting SQL queries is security-sensitive
>
> Formatted SQL queries can be difficult to maintain, debug and can increase the risk of SQL injection when concatenating untrusted values into the query. However, this rule doesn’t detect SQL injections (unlike rule S3649), the goal is only to highlight complex/formatted queries.
>
> ```python Bad theme={"theme":"css-variables"}
> cursor = connection.cursor(prepared=True)
> sql_insert_query = """ select col from sometable here mycol = %s and othercol = %s """
>
> select_tuple = (1, value)
>
> cursor.execute(sql_insert_query, select_tuple) # Compliant, the query is parameterized
> connection.commit()
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] Unused function parameters should be removed
>
> A typical code smell known as unused function parameters refers to parameters declared in a function but not used anywhere within the function’s body.
> While this might seem harmless at first glance, it can lead to confusion and potential errors in your code.
> Disregarding the values passed to such parameters, the function’s behavior will be the same, but the programmer’s intention won’t be clearly expressed anymore.
> Therefore, removing function parameters that are not being utilized is considered best practice.
>
> ```python Bad theme={"theme":"css-variables"}
> class C(B):
> def do_something(self, a, b): # no issue reported on b
> return self.compute(a)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def do_something(a, _): # no issue reported on _
> return compute(a)
> ```

> [accordion] Unicode Grapheme Clusters should be avoided inside regex character classes
>
> When placing Unicode [Grapheme Clusters](https://unicode.org/glossary/#grapheme_cluster) (characters which require to be encoded in multiple [Code Points](https://unicode.org/glossary/#code_point)) inside a character class of a regular expression, this will likely lead to unintended behavior.
>
> For instance, the grapheme cluster `c̈ requires two code points: one for 'c', followed by one for the umlaut modifier . If placed within a character class, such as [c̈], the regex will consider the character class being the enumeration instead. It will, therefore, match every 'c'` and every *umlaut* that isn’t expressed as a single codepoint, which is extremely unlikely to be the intended behavior.
>
> This rule raises an issue every time Unicode Grapheme Clusters are used within a character class of a regular expression.
>
> ```python Bad theme={"theme":"css-variables"}
> re.sub(r"[c̈d̈]", "X", "cc̈d̈d") # Noncompliant, print "XXXXXX" instead of expected "cXXd".
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> re.sub(r"c̈|d̈", "X", "cc̈d̈d") # print "cXXd"
> ```

> [accordion] Class names should comply with a naming convention
>
> Shared naming conventions allow teams to collaborate efficiently.
>
> This rule raises an issue when a class name does not match a provided regular expression.
>
> ```python Bad theme={"theme":"css-variables"}
> class myClass:  # Noncompliant
> ...
>
> class my_CONTEXT_manager:  # Noncompliant
> def __enter__(self):
>     pass
> def __exit__(self, type, value, traceback):
>     pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyClass:
> ...
>
> class my_context_manager:
> def __enter__(self):
>     pass
> def __exit__(self, type, value, traceback):
>     pass
> ```

> [accordion] Repeated patterns in regular expressions should not match the empty string
>
> A regex should never include a repetitive pattern whose body would match the empty string. This is usually a sign that a part of the regex is redundant or does not do what the author intended.
>
> ```python Bad theme={"theme":"css-variables"}
> r"(?:)*"      # same as the empty regex, the '*' accomplishes nothing
> r"(?:|x)*"    # same as the empty regex, the alternative has no effect
> r"(?:x|)*"    # same as 'x*', the empty alternative has no effect
> r"(?:x*|y*)*" # same as 'x*', the first alternative would always match, y* is never tried
> r"(?:x?)*"    # same as 'x*'
> r"(?:x?)+"    # same as 'x*'
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> r"x*"
> ```

> [accordion] Constructing arguments of system commands from user input is security-sensitive
>
> Constructing arguments of system commands from user input is security-sensitive. It has led in the past to the following vulnerabilities:
>
> <ul>
>   <li>
>     [CVE-2016-9920](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-9920)
>   </li>
>
>   <li>
>     [CVE-2021-29472](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-29472)
>   </li>
> </ul>
>
> Arguments of system commands are processed by the executed program. The arguments are usually used to configure and influence the behavior of the programs.
> Control over a single argument might be enough for an attacker to trigger dangerous features like executing arbitrary commands or writing files into specific directories.
>
> ```python Bad theme={"theme":"css-variables"}
> import subprocess
> input = request.get('input')
> if input in allowed:
> subprocess.run(["/usr/bin/find", input])
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] Signaling processes is security-sensitive
>
> Signaling processes or process groups can seriously affect the stability of
> this application or other applications on the same system.
>
> Accidentally setting an incorrect PID or signal or allowing untrusted
> sources to assign arbitrary values to these parameters may result in a denial
> of service.
>
> Also, the system treats the signal differently if the destination PID is less
> than or equal to 0. This different behavior may affect multiple processes with
> the same (E)UID simultaneously if the call is left uncontrolled.
>
> ```python Bad theme={"theme":"css-variables"}
> import os
>
> @app.route("/kill-pid/<pid>")
> def send_signal(pid):
> os.kill(pid, 9)  # Sensitive
>
> @app.route("/kill-pgid/<pgid>")
> def send_signal(pgid):
> os.killpg(pgid, 9)  # Sensitive
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import os
>
> @app.route("/kill-pid/<pid>")
> def send_signal(pid):
> # Validate the untrusted PID,
> # With a pre-approved list or authorization checks
> if is_valid_pid(pid):
>     os.kill(pid, 9)
>
> @app.route("/kill-pgid/<pgid>")
> def send_signal(pgid):
> # Validate the untrusted PGID,
> # With a pre-approved list or authorization checks
> if is_valid_pgid(pgid):
>     os.kill(pgid, 9)
> ```

> [accordion] Variables should not be self-assigned
>
> There is no reason to re-assign a variable to itself. Either this statement is redundant and should be removed, or the re-assignment is a mistake and some other value or variable was intended for the assignment instead.
>
> ```python Bad theme={"theme":"css-variables"}
> name = name
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> name = other.name
> ```

> [accordion] Disabling auto-escaping in template engines is security-sensitive
>
> To reduce the risk of cross-site scripting attacks, templating systems, such as \`Twig,  Django,  Smarty,  Groovy's template engine, allow configuration of automatic variable escaping before rendering templates. When escape occurs, characters that make sense to the browser (eg: \<a>) will be transformed/replaced with escaped/sanitized values (eg: & lt;a& gt; ).
>
> Auto-escaping is not a magic feature to annihilate all cross-site scripting attacks, it depends on [the strategy applied](https://twig.symfony.com/doc/3.x/filters/escape.html) and the context, for example a "html auto-escaping" strategy  (which only transforms html characters into [html entities](https://developer.mozilla.org/en-US/docs/Glossary/Entity)) will not be relevant when variables are used in a [html attribute](https://en.wikipedia.org/wiki/HTML_attribute) because ':’ character is not escaped and thus an attack as below is possible:
>
> `&lt;a href="{{ myLink }}"&gt;link&lt;/a&gt; // myLink = javascript:alert(document.cookie)
>         &lt;a href="javascript:alert(document.cookie)"&gt;link&lt;/a&gt; // JS injection (XSS attack)`
>
> ```python Bad theme={"theme":"css-variables"}
> from jinja2 import Environment
> env = Environment(autoescape=True) # Compliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] Regular expressions should not contain multiple spaces
>
> Multiple spaces in a regular expression can make it hard to tell how many spaces should be matched. It’s more readable to use only one space and then indicate with a quantifier how many spaces are expected.
>
> ```python Bad theme={"theme":"css-variables"}
> r"Hello,   world!"
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> r"Hello, {3}world!"
> ```

> [accordion] HTTP response headers should not be vulnerable to injection attacks
>
> User-provided data, such as URL parameters, POST data payloads, or cookies, should always be considered untrusted and tainted. Applications constructing HTTP response headers based on tainted data could allow attackers to change security sensitive headers like Cross-Origin Resource Sharing headers.
>
> Web application frameworks and servers might also allow attackers to inject new line characters in headers to craft malformed HTTP response. In this case the application would be vulnerable to a larger range of attacks like HTTP Response Splitting/Smuggling. Most of the time this type of attack is mitigated by default modern web application frameworks but there might be rare cases where older versions are still vulnerable.
>
> As a best practice, applications that use user-provided data to construct the response header should always validate the data first. Validation should be based on a whitelist.
>
> ```python Bad theme={"theme":"css-variables"}
> from flask import Response, request
> from werkzeug.datastructures import Headers
>
> @app.route('/route')
> def route():
> content_type = request.args["Content-Type"]
> response = Response()
> headers = Headers()
> headers.add("Content-Type", content_type) # Noncompliant
> response.headers = headers
> return response
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import django.http
>
> def route(request):
> content_type = request.GET.get("Content-Type")
> response = django.http.HttpResponse()
> response.__setitem__('Content-Type', content_type) # Noncompliant
> return response
> ```

> [accordion] Using unencrypted EBS volumes is security-sensitive
>
> Amazon Elastic Block Store (EBS) is a block-storage service for Amazon Elastic Compute Cloud (EC2). EBS volumes can be encrypted, ensuring the security of both data-at-rest and data-in-transit between an instance and its attached EBS storage. In the case that adversaries gain physical access to the storage medium they are not able to access the data. Encryption can be enabled for specific volumes or for [all new volumes and snapshots](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-by-default). Volumes created from snapshots inherit their encryption configuration. A volume created from an encrypted snapshot will also be encrypted by default.
>
> ```python Bad theme={"theme":"css-variables"}
> from aws_cdk.aws_ec2 import Volume
>
> class EBSVolumeStack(Stack):
>
> def __init__(self, scope: Construct, construct_id: str, **kwargs)  None:
>     super().__init__(scope, construct_id, **kwargs)
>     Volume(self,
>         "unencrypted-explicit",
>         availability_zone="eu-west-1a",
>         size=Size.gibibytes(1),
>         encrypted=False  # Sensitive
>     )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from aws_cdk.aws_ec2 import Volume
>
> class EBSVolumeStack(Stack):
>
> def __init__(self, scope: Construct, construct_id: str, **kwargs)  None:
>     super().__init__(scope, construct_id, **kwargs)
>     Volume(self,
>         "unencrypted-implicit",
>         availability_zone="eu-west-1a",
>         size=Size.gibibytes(1)
>     ) # Sensitive as encryption is disabled by default
> ```

> [accordion] Creating cookies without the secure flag is security-sensitive
>
> When a cookie is protected with the `secure` attribute set to *true* it will not be send by the browser over an unencrypted HTTP request and thus cannot be observed by an unauthorized person during a man-in-the-middle attack.
>
> ```python Bad theme={"theme":"css-variables"}
> from flask import Response
>
> @app.route('/')
> def index():
> response = Response()
> response.set_cookie('key', 'value', secure=True) # Compliant
> return response
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] Using unencrypted EFS file systems is security-sensitive
>
> Amazon Elastic File System (EFS) is a serverless file system that does not require provisioning or managing storage. Stored files can be automatically encrypted by the service. In the case that adversaries gain physical access to the storage medium or otherwise leak a message they are not able to access the data.
>
> ```python Bad theme={"theme":"css-variables"}
> from aws_cdk import (
> aws_efs as efs
> )
>
> efs.FileSystem(
> self,
> "example",
> encrypted=False  # Sensitive
> )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from aws_cdk import (
> aws_efs as efs
> )
>
> efs.FileSystem(
> self,
> "example",
> encrypted=True
> )
> ```

> [accordion] Functions should not contain too many return statements
>
> Having too many return statements in a function increases the function’s essential complexity because the flow of execution is broken each time a return statement is encountered. This makes it harder to read and understand the logic of the function.
>
> ```python Bad theme={"theme":"css-variables"}
> def fun():          # Noncompliant as there are 4 return statements
> if condition1:
> return True
> elif condition2:
> return False
> else:
> return True
> return False
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] Non-empty statements should change control flow or have at least one side-effect
>
> When writing code, it is important to ensure that each statement serves a purpose and
> contributes to the overall functionality of the program. When they have no side effects or do not change the control flow, they can either indicate a programming error or be redundant:
>
> <ol>
>   <li>
>     The code does not behave as intended: The statements are
>     expected to have an effect but they do not. This can be
>     caused by mistyping, copy-and-paste errors, etc.
>   </li>
>
>   <li>
>     The statements are residual after a refactoring.
>   </li>
> </ol>
>
> ```python Bad theme={"theme":"css-variables"}
> def foo():
> bar()
> """Some comment"""  # Compliant by default. Noncompliant with "reportOnStrings" set to "true"
> qix()
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def process(p, beam):
> """
> Apache Beam redefines "|" and ">>" operators and they have a side effect.
> Thus for Apache Beam projects "ignoredOperators"should be set to "|,>>"
> """
> p | "create" >> beam.Create()  # Noncompliant by default
> ```

> [accordion] Creating public APIs is security-sensitive
>
> Creating APIs without authentication unnecessarily increases the attack surface on
> the target infrastructure.
>
> Unless another authentication method is used, attackers have the
> opportunity to attempt attacks against the underlying API.
> This means attacks both on the functionality provided by the API and its
> infrastructure.
>
> ```python Bad theme={"theme":"css-variables"}
> from aws_cdk import (
> aws_apigateway as apigateway
> )
>
> resource = api.root.add_resource("example")
> resource.add_method(
> "GET",
> authorization_type=apigateway.AuthorizationType.NONE  # Sensitive
> )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from aws_cdk import (
> aws_apigatewayv2 as apigateway
> )
>
> apigateway.CfnRoute(
> self,
> "no-auth",
> api_id=api.ref,
> route_key="GET /test",
> authorization_type="NONE"  # Sensitive
> )
> ```

> [accordion] HTTP response headers should not be vulnerable to response splitting attacks
>
> Without proper validation or sanitation, an attacker with control over a header’s content could insert line return characters in it and inject arbitrary content in the HTTP response. This includes headers, their content, and the response body.
>
> ```python Bad theme={"theme":"css-variables"}
> from http.server import BaseHTTPRequestHandler
> from urllib.parse import urlparse, parse_qs
>
> class ReqHandler(BaseHTTPRequestHandler):
> def do_GET(self):
>     parsed = urlparse(self.path)
>     params = parse_qs(parsed.query)
>     self.send_response(200)
>     self.send_header("Content-Type", params.get('accept')[0]) # Noncompliant
>     self.end_headers()
>     self.wfile.write(bytes("Hello World!", "utf-8"))
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from http.server import BaseHTTPRequestHandler
> from urllib.parse import urlparse, parse_qs, quote
>
> class ReqHandler(BaseHTTPRequestHandler):
> def do_GET(self):
>     parsed = urlparse(self.path)
>     params = parse_qs(parsed.query)
>     self.send_response(200)
>     self.send_header("Content-Type", quote(params.get('accept')[0])) # Compliant
>     self.end_headers()
>     self.wfile.write(bytes("Hello World!", "utf-8"))
> ```

> [accordion] String literals should not be duplicated
>
> Duplicated string literals make the process of refactoring complex and error-prone, as any change would need to be propagated on all occurrences.
>
> ```python Bad theme={"theme":"css-variables"}
> def run():
> prepare("action1")  # Noncompliant - "action1" is duplicated 3 times
> execute("action1")
> release("action1")
>
> @app.route("/api/users/", methods=['GET', 'POST', 'PUT'])
> def users():
> pass
>
> @app.route("/api/projects/", methods=['GET', 'POST', 'PUT'])  # Compliant - strings inside decorators are ignored
> def projects():
> pass
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ACTION_1 = "action1"
>
> def run():
> prepare(ACTION_1)
> execute(ACTION_1)
> release(ACTION_1)
> ```

> [accordion] Neither DES (Data Encryption Standard) nor DESede (3DES) should be used
>
> According to the US National Institute of Standards and Technology (NIST), the Data Encryption Standard (DES) is no longer considered secure:
>
> > Adopted in 1977 for federal agencies to use in protecting sensitive, unclassified information, the DES is being withdrawn because it no longer provides the security that is needed to protect federal government information.
> >
> > Federal agencies are encouraged to use the Advanced Encryption Standard, a faster and stronger algorithm approved as FIPS 197 in 2001.
>
> For similar reasons, RC2 should also be avoided.
>
> ```python Bad theme={"theme":"css-variables"}
> from pyDes import *
>
> data = "content to be encrypted"
> k = des("DESCRYPT", CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5) // Noncompliant
> d = k.encrypt(data)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import hashlib
>
> m = hashlib.sha256() // Compliant
> m.update(data)
>
> d = m.hexdigest()
> ```

> [accordion] Granting access to S3 buckets to all or authenticated users is security-sensitive
>
> Predefined permissions, also known as [canned ACLs](https://docs.aws.amazon.com/AmazonS3/latest/userguide/acl-overview.html#canned-acl), are an easy way to grant large privileges to predefined groups or users.
>
> The following canned ACLs are security-sensitive:
>
> <ul>
>   <li>
>     \`PublicRead, PublicReadWrite grant respectively "read" and "read and write" privileges to everyone in the world (AllUsers group).
>   </li>
>
>   <li>
>     AuthenticatedRead grants "read" privilege to all authenticated users (AuthenticatedUsers\` group).
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> bucket = s3.Bucket(self, "bucket",
> access_control=s3.BucketAccessControl.PUBLIC_READ_WRITE     # Sensitive
> )
>
> s3deploy.BucketDeployment(self, "DeployWebsite",
> access_control=s3.BucketAccessControl.PUBLIC_READ_WRITE     # Sensitive
> )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> bucket = s3.Bucket(self, "bucket",
> access_control=s3.BucketAccessControl.PRIVATE       # Compliant
> )
>
> # Another example
> s3deploy.BucketDeployment(self, "DeployWebsite",
> access_control=s3.BucketAccessControl.PRIVATE       # Compliant
> )
> ```

> [accordion] SHA-1 and Message-Digest hash algorithms should not be used in secure contexts
>
> The MD5 algorithm and its successor, SHA-1, are no longer considered secure, because it is too easy to create hash collisions with them. That is, it takes too little computational effort to come up with a different input that produces the same MD5 or SHA-1 hash, and using the new, same-hash value gives an attacker the same access as if he had the originally-hashed value. This applies as well to the other Message-Digest algorithms: MD2, MD4, MD6, HAVAL-128, HMAC-MD5, DSA (which uses SHA-1), RIPEMD, RIPEMD-128, RIPEMD-160, HMACRIPEMD160.
>
> Consider using safer alternatives, such as SHA-256, SHA-512 or SHA-3.
>
> ```python Bad theme={"theme":"css-variables"}
> import hashlib
> m = hashlib.md5() // Noncompliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import hashlib
> m = hashlib.sha1() // Noncompliant
> ```

> [accordion] A field should not duplicate the name of its containing class
>
> It’s confusing to have a class member with the same name (case differences aside) as its enclosing class. This is particularly so when you consider the common practice of naming a class instance for the class itself.
>
> Best practice dictates that any field or member with the same name as the enclosing class be renamed to be more descriptive of the particular aspect of the class it represents or holds.
>
> ```python Bad theme={"theme":"css-variables"}
> class Foo: 
> foo = '' 
>
> def getFoo(self):
> ...
>
> foo = Foo()
> foo.getFoo() # what does this return?
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class Foo:
> name = ''
>
> def getName(self):
> ...
>
> foo = Foo()
> foo.getName()
> ```

> [accordion] Comments should not be located at the end of lines of code
>
> This rule verifies that single-line comments are not located at the ends of lines of code. The main idea behind this rule is that in order to be really readable, trailing comments would have to be properly written and formatted (correct alignment, no interference with the visual structure of the code, not too long to be visible) but most often, automatic code formatters would not handle this correctly: the code would end up less readable. Comments are far better placed on the previous empty line of code, where they will always be visible and properly formatted.
>
> ```python Bad theme={"theme":"css-variables"}
> a = b + c   # This is a trailing comment that can be very very long
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> # This very long comment is better placed before the line of code
> a = b + c
> ```

> [accordion] Function names should comply with a naming convention
>
> Shared coding conventions allow teams to collaborate efficiently. This rule checks that all function names match a provided regular expression.
>
> ```python Bad theme={"theme":"css-variables"}
> def MyFunction(a,b):
> ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def my_function(a,b):
> ...
> ```

> [accordion] Functions and methods should not have identical implementations
>
> Two {func_name}s having the same implementation are suspicious.
> It might be that something else was intended. Or the duplication is intentional, which becomes a maintenance burden.
>
> ```python Bad theme={"theme":"css-variables"}
> class MyClass:
> code = "secret"
>
> def calculate_code(self):
>     self.do_the_thing()
>     return self.__class__.code
>
> def get_name(self):  # Noncompliant: duplicates calculate_code
>     self.do_the_thing()
>     return self.__class__.code
>
> def do_the_thing(self):
>     pass  # on purpose
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyClass:
> code = "secret"
>
> def calculate_code(self):
>     self.do_the_thing()
>     return self.__class__.code
>
> def get_name(self):  # Intent is clear
>     return self.calculate_code()
>
> def do_the_thing(self):
>     pass  # on purpose
> ```

> [accordion] Using hardcoded IP addresses is security-sensitive
>
> Hardcoding IP addresses is security-sensitive. It has led in the past to the following vulnerabilities:
>
> <ul>
>   <li>
>     [CVE-2006-5901](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-5901)
>   </li>
>
>   <li>
>     [CVE-2005-3725](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2005-3725)
>   </li>
> </ul>
>
> Today’s services have an ever-changing architecture due to their scaling and redundancy needs. It is a mistake to think that a service will always have the same IP address. When it does change, the hardcoded IP will have to be modified too. This will have an impact on the product development, delivery, and deployment:
>
> <ul>
>   <li>
>     The developers will have to do a rapid fix every time this happens, instead of having an operation team change a configuration file.
>   </li>
>
>   <li>
>     It misleads to use the same address in every environment (dev, sys, qa, prod).
>   </li>
> </ul>
>
> Last but not least it has an effect on application security. Attackers might be able to decompile the code and thereby discover a potentially sensitive address. They can perform a Denial of Service attack on the service, try to get access to the system, or try to spoof the IP address to bypass security checks. Such attacks can always be possible, but in the case of a hardcoded IP address solving the issue will take more time, which will increase an attack’s impact.
>
> ```python Bad theme={"theme":"css-variables"}
> ip = config.get(section, ipAddress)
> sock = socket.socket()
> sock.bind((ip, 9090))
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] Creating cookies with broadly defined domain flags is security-sensitive
>
> A cookie’s domain specifies which websites should be able to read it. Left blank, browsers are supposed to only send the cookie to sites that exactly match the sending domain. For example, if a cookie was set by *lovely.dream.com*, it should only be readable by that domain, and not by *nightmare.com* or even *strange.dream.com*. If you want to allow sub-domain access for a cookie, you can specify it by adding a dot in front of the cookie’s domain, like so: *.dream.com*. But cookie domains should always use at least two levels.
>
> Cookie domains can be set either programmatically or via configuration. This rule raises an issue when any cookie domain is set with a single level, as in *.com*.
>
> ```python Bad theme={"theme":"css-variables"}
> import http.cookies
>
> setCookie = http.cookies.SimpleCookie()
> setCookie['restricted_cookie'] = 'cookie_value'
> setCookie['restricted_cookie']['domain'] = '.sonarsource.com'   # Compliant
> setCookie['restricted_cookie']['path'] = '/'
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from flask import app, make_response, render_template
>
>
> @app.route('/')
> def index():
> http_response = make_response(render_template())
> http_response.set_cookie(
>     "restricted_cookie",
>     domain='sonarsource.com',  # Compliant
>     path='/'
> )
>
> return http_response
> ```

> [accordion] Track uses of TODO tags
>
> Developers often use TODO tags to mark areas in the code where additional work or improvements are needed but are not implemented immediately.
> However, these TODO tags sometimes get overlooked or forgotten, leading to incomplete or unfinished code.
> This rule aims to identify and address unattended TODO tags to ensure a clean and maintainable codebase.
> This description explores why this is a problem and how it can be fixed to improve the overall code quality.
>
> ```python Bad theme={"theme":"css-variables"}
> def doSomething:
> # TODO : Complete function
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] Policies granting access to all resources of an account are security-sensitive
>
> A policy that allows identities to access all resources in an AWS account may violate [the principle of least privilege](https://en.wikipedia.org/wiki/Principle_of_least_privilege). Suppose an identity has permission to access all resources even though it only requires access to some non-sensitive ones. In this case, unauthorized access and disclosure of sensitive information will occur.
>
> ```python Bad theme={"theme":"css-variables"}
> from aws_cdk.aws_iam import Effect, PolicyDocument, PolicyStatement
>
> PolicyDocument(
> statements=[
>     PolicyStatement(
>         effect=Effect.ALLOW,
>         actions="iam:CreatePolicyVersion",
>         resources=["*"] # Sensitive
>     )
> ]
> )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from aws_cdk import Aws
> from aws_cdk.aws_iam import Effect, PolicyDocument, PolicyStatement
>
> PolicyDocument(
> statements=[
>     PolicyStatement(
>         effect=Effect.ALLOW,
>         actions="iam:CreatePolicyVersion",
>         resources=[f"arn:aws:iam::{Aws.ACCOUNT_ID}:policy/team1/*"]
>     )
> ]
> )
> ```

> [accordion] Character classes in regular expressions should not contain the same character twice
>
> Character classes in regular expressions are a convenient way to match one of several possible characters by listing the allowed characters or ranges of characters. If the same character is listed twice in the same character class or if the character class contains overlapping ranges, this has no effect.
>
> Thus duplicate characters in a character class are either a simple oversight or a sign that a range in the character class matches more than is intended or that the author misunderstood how character classes work and wanted to match more than one character. A common example of the latter mistake is trying to use a range like \[0-99] to match numbers of up to two digits, when in fact it is equivalent to \[0-9]. Another common cause is forgetting to escape the - character, creating an unintended range that overlaps with other characters in the character class.
>
> ```python Bad theme={"theme":"css-variables"}
> r"[0-99]" # Noncompliant, this won't actually match strings with two digits
> r"[0-9.-_]" # Noncompliant, .-_ is a range that already contains 0-9 (as well as various other characters such as capital letters)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> r"[0-9]{1,2}"
> r"[0-9.\\-_]"
> ```

> [accordion] Regex alternatives should not be redundant
>
> If an alternative in a regular expression only matches things that are already matched by another alternative, that alternative is redundant and serves no purpose.
>
> In the best case this means that the offending subpattern is merely redundant and should be removed. In the worst case it’s a sign that this regex does not match what it was intended to match and should be reworked.
>
> ```python Bad theme={"theme":"css-variables"}
> r"[ab]|a"   # Noncompliant: the "|a" is redundant because "[ab]" already matches "a"
> r".*|a"     # Noncompliant: .* matches everything, so any other alternative is redundant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> r"[ab]"
> r".*"
> ```

> [accordion] Field names should comply with a naming convention
>
> A naming convention in software development is a set of guidelines for naming code elements like variables, functions, and classes.
>
> The goal of a naming convention is to make the code more readable and understandable, which makes it easier to maintain and debug.
> It also ensures consistency in the code, especially when multiple developers are working on the same project.
>
> This rule checks that field names match a provided regular expression.
>
> ```python Bad theme={"theme":"css-variables"}
> class MyClass:
> myField = 1
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> class MyClass:
> my_field = 1
> ```

> [accordion] Setting loose POSIX file permissions is security-sensitive
>
> In Unix file system permissions, the "`others`" category refers to all
> users except the owner of the file system resource and the members of the group
> assigned to this resource.
>
> Granting permissions to this category can lead to unintended access to files or
> directories that could allow attackers to obtain sensitive information, disrupt
> services or elevate privileges.
>
> ```python Bad theme={"theme":"css-variables"}
> os.umask(0o777)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> os.chmod("/tmp/fs", stat.S_IRWXU)
> os.lchmod("/tmp/fs", stat.S_IRWXU)
> os.fchmod(fd, stat.S_IRWXU)
> ```

> [accordion] Using weak hashing algorithms is security-sensitive
>
> Cryptographic hash algorithms such as `MD2, MD4, MD5, MD6, HAVAL-128, HMAC-MD5, DSA (which uses SHA-1), RIPEMD, RIPEMD-128, RIPEMD-160, HMACRIPEMD160 and SHA-1 are no longer considered secure, because it is possible to have collisions` (little computational effort is enough to find two or more different inputs that produce the same hash).
>
> ```python Bad theme={"theme":"css-variables"}
> import hashlib
> m = hashlib.sha512() // Compliant
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] Regex patterns following a possessive quantifier should not always fail
>
> Possessive quantifiers in Regex patterns like below improve performance by eliminating needless backtracking:
>
> <pre>?+ , \*+ , ++ , n+ , n,+ , n,m+</pre>
>
> But because possessive quantifiers do not keep backtracking positions and never give back, the following sub-patterns should not match only similar characters. Otherwise, possessive quantifiers consume all characters that could have matched the following sub-patterns and nothing remains for the following sub-patterns.
>
> ```python Bad theme={"theme":"css-variables"}
> import re
> pattern1 = re.compile(r"a++abc", re.DOTALL) # Noncompliant, the second 'a' never matches
> pattern2 = re.compile(r"\d*+[02468]", re.DOTALL) # Noncompliant, the sub-pattern "[02468]" never matches
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> import re
> pattern1 = re.compile(r"aa++bc", re.DOTALL) # Compliant, for example it can match "aaaabc"
> pattern2 = re.compile(r"\d*+(?<=[02468])", re.DOTALL) # Compliant, for example, it can match an even number like "1234"
> ```

> [accordion] Using unencrypted SQS queues is security-sensitive
>
> Amazon Simple Queue Service (SQS) is a managed message queuing service for application-to-application (A2A) communication. Amazon SQS can store messages encrypted as soon as they are received. In the case that adversaries gain physical access to the storage medium or otherwise leak a message from the file system, for example through a vulnerability in the service, they are not able to access the data.
>
> ```python Bad theme={"theme":"css-variables"}
> from aws_cdk import (
> aws_sqs as sqs
> )
>
> class QueueStack(Stack):
> def __init__(self, scope: Construct, construct_id: str, **kwargs)  None:
>     super().__init__(scope, construct_id, **kwargs)
>     sqs.Queue( # Sensitive, unencrypted by default
>         self,
>         "example"
>     )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from aws_cdk import (
> aws_sqs as sqs
> )
>
> class CfnQueueStack(Stack):
> def __init__(self, scope: Construct, construct_id: str, **kwargs)  None:
>     super().__init__(scope, construct_id, **kwargs)
>     sqs.CfnQueue( # Sensitive, unencrypted by default
>         self,
>         "example"
>     )
> ```

> [accordion] Allowing public ACLs or policies on a S3 bucket is security-sensitive
>
> By default S3 buckets are private, it means that only the bucket owner can access it.
>
> This access control can be relaxed with ACLs or policies.
>
> To prevent permissive policies to be set on a S3 bucket the following settings can be configured:
>
> <ul>
>   <li>
>     \`BlockPublicAcls: to block or not public ACLs to be set to the S3 bucket.
>   </li>
>
>   <li>
>     IgnorePublicAcls: to consider or not existing public ACLs set to the S3 bucket.
>   </li>
>
>   <li>
>     BlockPublicPolicy: to block or not public policies to be set to the S3 bucket.
>   </li>
>
>   <li>
>     RestrictPublicBuckets: to restrict or not the access to the S3 endpoints of public policies to the principals within the bucket owner account.
>   </li>
> </ul>
>
> ```python Bad theme={"theme":"css-variables"}
> bucket = s3.Bucket(self,
> "bucket"        # Sensitive
> )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> bucket = s3.Bucket(self,
> "bucket",
> block_public_access=s3.BlockPublicAccess(
>     block_public_acls=False,       # Sensitive
>     ignore_public_acls=True,
>     block_public_policy=True,
>     restrict_public_buckets=True
> )
> )
> ```

> [accordion] Regular expressions should not contain empty groups
>
> There are several reasons to use a group in a regular expression:
>
> <ul>
>   <li>
>     to change the precedence (e.g. do(g|or) will match 'dog' and 'door')
>   </li>
>
>   <li>
>     to remember parenthesised part of the match in the case of capturing group
>   </li>
>
>   <li>
>     to improve readability
>   </li>
> </ul>
>
> In any case, having an empty group is most probably a mistake. Either it is a leftover after refactoring and should be removed, or the actual parentheses were intended and were not escaped.
>
> ```python Bad theme={"theme":"css-variables"}
> r"foo()" # Noncompliant, will match only 'foo'
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> r"foo\(\)" # Matches 'foo()'
> ```

> [accordion] Hard-coded credentials are security-sensitive
>
> Because it is easy to extract strings from an application source code or binary, credentials should not be hard-coded. This is particularly true for applications that are distributed or that are open-source.
>
> In the past, it has led to the following vulnerabilities:
>
> <ul>
>   <li>
>     [CVE-2019-13466](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-13466)
>   </li>
>
>   <li>
>     [CVE-2018-15389](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-15389)
>   </li>
> </ul>
>
> Credentials should be stored outside of the code in a configuration file, a database, or a management service for secrets.
>
> This rule flags instances of hard-coded credentials used in database and LDAP connections. It looks for hard-coded credentials in connection strings, and for variable names that match any of the patterns from the provided list.
>
> It’s recommended to customize the configuration of this rule with additional credential words such as "oauthToken", "secret", …​
>
> ```python Bad theme={"theme":"css-variables"}
> import os
>
> username = os.getenv("username") # Compliant
> password = os.getenv("password") # Compliant
> usernamePassword = 'user=%s&password=%s' % (username, password) # Compliant{code}
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> ```

> [accordion] Track TODO and FIXME comments that do not contain a reference to a person
>
> TODO and FIXME comments are typically intended to be short-lived; they are placeholders and reminders that programmers leave for themselves. Unfortunately, even with the best of intentions, those comments are not always acted on and removed in a timely manner. Thus, they can become mysterious, lingering cruft in a code base, reducing both readability and understand-ability.
>
> This rule flags all FIXME and TODO comments that do not have an attribution matching the specified regular expression immediately after the FIXME or TODO. Ideally, such comments will also contain information about what needs to be fixed or done, but this rule does not enforce that.
>
> ```python Bad theme={"theme":"css-variables"}
> # TODO
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> # TODO(ganncamp) per the business partners, more checks needed
> ```

> [accordion] Administration services access should be restricted to specific IP addresses
>
> Cloud platforms such as AWS, Azure, or GCP support virtual firewalls that can be used to restrict access to services by controlling inbound and outbound traffic.
> Any firewall rule allowing traffic from all IP addresses to standard network ports on which administration services traditionally listen, such as 22 for SSH, can expose these services to exploits and unauthorized access.
>
> ```python Bad theme={"theme":"css-variables"}
> from aws_cdk import aws_ec2 as ec2
>
> instance = ec2.Instance(
> self,
> "my_instance",
> instance_type=nano_t2,
> machine_image=ec2.MachineImage.latest_amazon_linux(),
> vpc=vpc
> )
>
> instance.connections.allow_from( 
> ec2.Peer.any_ipv4(), # Noncompliant
> ec2.Port.tcp(22),
> description="Allows SSH from all IPv4"
> )
> instance.connections.allow_from_any_ipv4( # Noncompliant
> ec2.Port.tcp(3389), 
> description="Allows Terminal Server from all IPv4"
> )
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> from aws_cdk import aws_ec2 as ec2
> security_group = ec2.SecurityGroup(
> self,
> "custom-security-group",
> vpc=vpc
> )
>
> security_group.add_ingress_rule(
> ec2.Peer.any_ipv4(), # Noncompliant
> ec2.Port.tcp_range(1, 1024)
> )
> ```

> [accordion] Unused local variables should be removed
>
> An unused local variable is a variable that has been declared but is not used anywhere in the block of code where it is defined. It is dead code, contributing to unnecessary complexity and leading to confusion when reading the code. Therefore, it should be removed from your code to maintain clarity and efficiency.
>
> ```python Bad theme={"theme":"css-variables"}
> for _ in range(10):     
> do_something()
> username, login, _ = auth
> do_something_else(username, login)
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def hello(name):
> message = "Hello " + name # Noncompliant - message is unused
> print(name)
> for i in range(10): # Noncompliant - i is unused
> foo()
> ```

> [accordion] Loop boundaries should not be vulnerable to injection attacks
>
> Loop boundary injections occur in an application when the application retrieves
> data from a user or a third-party service and inserts it into a loop or a
> function acting as a loop, without sanitizing it first.
>
> If an application contains a loop that is vulnerable to injections,
> it is exposed to attacks that target its availability where that loop is used.
>
> A user with malicious intent carefully performs actions whose goal is to cause
> the loop to run for more iterations than the developer intended, resulting in
> unexpected behavior or even a crash of the program.
>
> After creating the malicious request, the attacker can attack the servers
> affected by this vulnerability without relying on any prerequisites.
>
> ```python Bad theme={"theme":"css-variables"}
> def example():
> limit = int(request.args.get('limit'))
>
> for _ in range(limit):
>     # ...
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def example():
> limit = int(request.args.get('limit'))
> restricted_limit = min(10, limit)
>
> for _ in range(restricted_limit):
>     # ...
> ```

> [accordion] Unused assignments should be removed
>
> Dead stores refer to assignments made to local variables that are subsequently never used or immediately overwritten. Such assignments are unnecessary and don’t contribute to the functionality or clarity of the code. They may even negatively impact performance. Removing them enhances code cleanliness and readability.
> Even if the unnecessary operations do not do any harm in terms of the program’s correctness, they are - at best - a waste of computing resources.
>
> ```python Bad theme={"theme":"css-variables"}
> def func(a, b, compute):
> i = a + b  # Noncompliant; calculation result not used before value is overwritten
> i = compute()
> return i
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def func(a, b, compute):
> i = a + b
> i += compute()
> return i
> ```

> [accordion] Cognitive Complexity of functions should not be too high
>
> Cognitive Complexity is a measure of how hard it is to understand the control flow of a unit of code.
> Code with high cognitive complexity is hard to read, understand, test, and modify.
>
> As a rule of thumb, high cognitive complexity is a sign that the code should be refactored into smaller, easier-to-manage pieces.
>
> ```python Bad theme={"theme":"css-variables"}
> def process_eligible_users(users):
> for user in users:             # +1 (for)
>     if ((user.is_active and    # +1 (if) +1 (nested) +1 (multiple conditions)
>         user.has_profile) or   # +1 (mixed operator)
>         user.age > 18 ): 
>         user.process()
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def process_eligible_users(users):
> for user in users:             # +1 (for)
>     if is_eligible_user(user): # +1 (if) +1 (nested)
>         user.process()
>
> def is_eligible_user(user):
> return ((user.is_active and user.has_profile) or user.age > 18) # +1 (multiple conditions) +1 (mixed operators)
> ```

> [accordion] Boolean expressions should not be gratuitous
>
> Control flow constructs like if-statements allow the programmer to direct the
> flow of a program depending on a boolean expression.
> However, if the condition is always true or always false, only one of the
> branches will ever be executed.
> In that case, the control flow construct and the condition no longer serve a
> purpose; they become *gratuitous*.
>
> ```python Bad theme={"theme":"css-variables"}
> def f(b):
> a = True
> if a:  # Noncompliant
>     do_something()
>
> if a and b:  # Noncompliant; "a" is always "True"
>     do_something_else()
> ```
>
> ```python Fix theme={"theme":"css-variables"}
> def f(b):
> do_something()
>
> if b:
>     do_something_else()
> ```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.