Skip to main content
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.

step 1

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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.

Step 2

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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Flags suspicious chained comparisons that use semantically incompatible operators, which might indicate a logic error or misunderstanding of comparison chaining in Python.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Suggests using a ternary conditional expression for simpler conditional assignments or return statements, enhancing readability and conciseness of the code.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Highlights the use of duplicate arguments in string formatting, suggesting the use of named arguments for clarity and to prevent errors in formatting expressions.
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.
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.
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.
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.
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.
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.
Highlights FIXME comments, which indicate areas of the code that are acknowledged by the developer as needing improvement or correction.

Step 3

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.
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.
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.
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.
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.
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.
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.
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.
Flags a module that imports itself, which is generally unnecessary and can lead to confusion or cyclic dependencies, detracting from code clarity and structure.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.

step 4

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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Indicates missing type documentation in older versions of Python, where specifying parameter and return types can improve readability, type checking, and overall code quality.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Suggests rephrasing expressions that use unnecessary negation to their positive counterparts, enhancing readability and reducing cognitive load by simplifying conditional logic.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Advises using augmented assignment operators (+=, -=, *=, etc.) when possible, simplifying expressions and potentially improving performance by modifying variables in place where applicable.

step 6

Recommends using dictionary comprehensions for constructing dictionaries from iterables, a concise and readable approach that leverages Python’s expressive syntax for collections.
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.
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.
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.
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..
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Identifies ‘if’ expressions that can be simplified, enhancing code readability and maintainability by reducing unnecessary complexity and making the code more concise.
Flags ‘if’ statements that can be streamlined into more concise expressions, improving readability and efficiency by eliminating redundant logic structures.
Points out complex boolean expressions that can be simplified, making the code easier to understand and maintain by clarifying logical operations and conditions.
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.
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.
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.
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.
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.
Highlights functions or methods with more arguments than recommended, suggesting refactoring to reduce parameter count, which can enhance readability and usability.
Flags ‘if’ statements containing more boolean expressions than recommended, suggesting simplification to improve logic clarity and reduce cognitive load.
Points out functions with too many conditional branches, recommending refactoring to simplify control flow and enhance the function’s readability and maintainability.
Indicates classes with more instance attributes than recommended, suggesting potential for simplifying class design by reevaluating the class’s responsibilities and structure.
Flags functions with a high number of local variables, recommending refactoring to reduce complexity, potentially by splitting the function into smaller, more focused functions.
Warns about excessive nesting in code blocks, which can make code difficult to follow. Flattening these structures can enhance readability and simplify logic.
Indicates classes with more public methods than recommended, suggesting a review of the class’s design for potential simplification by splitting responsibilities.
Highlights functions with more return statements than recommended, suggesting that simplifying the function’s logic could improve readability and flow.
Flags functions containing more statements than recommended, indicating potential for refactoring to break down complex functions into smaller, more manageable pieces.
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.
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.
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.
Flags unnecessary retrieval of list items by index in contexts where a simpler approach could be used, suggesting improvements for code simplicity and performance.
Recommends using a generator expression instead of a more verbose construct for creating iterators, improving memory efficiency and code readability by lazily generating items.
Suggests using the dictionary literal instead of the dict() constructor for initializing dictionaries, enhancing code conciseness and clarity.
Advises using the list literal [] over list() for creating empty lists, promoting code clarity and aligning with Pythonic best practices for simplicity.
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.
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.
Flags configuration options that are set to ineffective or redundant values, suggesting a review and cleanup of configuration settings for clarity and effectiveness.
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.
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.
Flags if statements in older code that can be simplified, recommending more concise and readable alternatives to improve code maintainability and clarity.
Warns about excessive nesting in older code, suggesting refactoring to reduce complexity and improve readability by flattening deeply nested structures.
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.
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.

step 7

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.
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.
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.
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.
Flags variables that are declared but not used, helping to identify potential errors or unnecessary code, improving code readability and efficiency.
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.
Encourages the use of let or const instead of var to improve code readability and reduce scope-related errors by using block-scoped variables.
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.
Identifies unnecessary string concatenations, promoting the use of template literals or simpler expressions for better readability and performance.
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.
Favors arrow functions as callbacks to utilize their concise syntax and lexical this binding, leading to cleaner and more understandable code.
Enforces sorting of import statements to improve code readability and maintainability by making it easier to visually inspect and manage dependencies.
Flags ternary operators that could be simplified to simpler expressions, promoting cleaner and more direct code by avoiding unnecessary complexity.
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.
Ensures that callback functions for array methods like map, filter, and reduce return a value, preventing unexpected behavior and bugs in array transformations.
Encourages the use of logical assignment operators to concisely perform logical operations and assignments in one step, enhancing code brevity and readability.
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.
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.
Discourages unnecessary use of await inside return statements, which can lead to extra microtask queue jumps and potentially affect performance, simplifying asynchronous control flow.
Disallows initializing variables to undefined, as it is unnecessary and can lead to confusion, promoting cleaner and more intentional variable declarations.
Disallows renaming import, export, and destructured assignments to the same name, reducing redundancy and improving code readability and maintainability.
Enforces the correct usage of useState hook, ensuring state is managed consistently and effectively in React functional components.
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.

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:

  • `| - when multiple | operators are used together, the subsequent ones only increase the complexity by 1

  • Quantifiers (*, +, ?, etc.)

  • Non-capturing groups that set flags (such as (?i:some_pattern) or (?i)some_pattern`)

  • Lookahead and lookbehind assertions

Additionally, each use of the following features increase the complexity by 1 regardless of nesting:

  • character classes

  • back references

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.

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:

  • The method is called directly from another method.

  • The method overrides an existing one in unittest.TestCase (example: a tearDown` method).

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 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.

The `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.

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.

Data science and machine learning tasks make extensive use of random number generation. It may, for example, be used for:

  • Model initialization

    • 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.

  • Regularization techniques

    • 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.

  • Cross-validation and bootstrapping

    • 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.

  • Hyperparameter tuning

    • 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.

  • Simulation and synthetic data generation

    • Randomness is often used in techniques such as data augmentation and synthetic data generation to generate diverse and realistic datasets.

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.

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:

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:

Prior to Python 3.12, generic type aliases were defined as follows:

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, the execution of side effects will depend on the input values of the function and will execute only once per tracing.

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.

for-in loops, yield from and iterable unpacking only work with iterable objects. In order to be iterable, an object should have either an `iter method or a getitem method implementing the 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`:

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.

Objects can be used as sequence indexes to access a specific element from the sequence, through the following syntax:

Variables, Classes and functions should not be undefined, otherwise the code will fail with a NameError.

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:

they are unrelated builtin types such as string and integer.
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).

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.

Dictionary unpacking allows you to pass the key-value pairs of a dictionary as keyword arguments to a function or merge dictionaries:

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.

Through PEP 701, 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:

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.

The raise a, b syntax is deprecated in Python 3, and should no longer be used.

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 for more information.

To fix this issue, make sure that the object you’re attempting to raise inherits from BaseException`.

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:

  1. 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.

  2. 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.

  3. 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.

  4. 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.

Using a def statements rather than assigning lambdas to variable is also recommended by PEP8.

Operators `in and not in, also called “membership test operators”, 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.

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:

Deprecated nameEquivalent built-in type

numpy.bool

bool

numpy.int

int

numpy.float

float

numpy.complex

complex

numpy.object

object

numpy.str

str

numpy.long

int

numpy.unicode

str

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.

Methods enter and exit make it possible to implement objects which can be used as the expression of a with statement:

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:

  • 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.

  • 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.

  • 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.

  • 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.

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, comparison operators.

Exception chaining enables users to see if an exception is the direct consequence of another exception (see PEP-3134). This is useful to propagate the original context of the error.

Exceptions are chained using either of the following syntax:

  • With the from keyword

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.

Through PEP 695, 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:

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:

  • lt(self, other)

  • le(self, other)

  • eq(self, other)

  • ne(self, other)

  • gt(self, other)

  • ge(self, other)

  • add(self, other)

  • sub(self, other)

  • mul(self, other)

  • matmul(self, other)

  • truediv(self, other)

  • floordiv(self, other)

  • mod(self, other)

  • divmod(self, other)

  • pow(self, other[, modulo])

  • lshift(self, other)

  • rshift(self, other)

  • and(self, other)

  • xor(self, other)

  • or(self, other)

  • radd(self, other)

  • rsub(self, other)

  • rmul(self, other)

  • rmatmul(self, other)

  • rtruediv(self, other)

  • rfloordiv(self, other)

  • rmod(self, other)

  • rdivmod(self, other)

  • rpow(self, other[, modulo])

  • rlshift(self, other)

  • rrshift(self, other)

  • rand(self, other)

  • rxor(self, other)

  • ror(self, other)

  • iadd(self, other)

  • isub(self, other)

  • imul(self, other)

  • imatmul(self, other)

  • itruediv(self, other)

  • ifloordiv(self, other)

  • imod(self, other)

  • ipow(self, other[, modulo])

  • ilshift(self, other)

  • irshift(self, other)

  • iand(self, other)

  • ixor(self, other)

  • ior(self, other)

  • length_hint(self)`

Operators is and 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.

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`.

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 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.

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.

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:

  • it makes the code difficult to understand.

  • 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.

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.

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.

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.

The NumPy function np.where provides a way to execute operations on an array under a certain condition:

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.

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.

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.

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.

Creating a new Exception without actually raising it has no effect and is probably due to a mistake.

In Python, using the isinstance() function is generally preferred over direct type comparison for several reasons:

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

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 style guide.

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.

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)

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`.

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)

Using the startswith and endswith methods in Python instead of string slicing offers several advantages:

  1. 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.

  2. 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.

  3. 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.

  4. 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.

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 style guide.

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.

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.

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.

Parentheses can disambiguate the order of operations in complex expressions and make the code easier to understand.

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.

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.

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:

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

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:

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.

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.

`SystemExit is raised when sys.exit() is called. 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 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, user-defined exceptions are not supposed to inherit directly from BaseException. They should instead inherit from Exception` or one of its subclasses.

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

The iterator protocol specifies that an iterator object should have

  • a `next method retrieving the next value or raising StopIteration when there are no more values left.

  • an iter method which should always return self. This enables iterators to be used as sequences in for-loops and other places.

This rule raises an issue when a class has a next method and either:

  • it doesn’t have an iter method.

  • or its iter` method does not return “self”.

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.

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.

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.

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

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.

”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”:

  • 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.

  • ”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.

This rule raises an issue when a private nested class (either with one or two leading underscores) is never used inside its parent class.

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:

  • The parameter how specifies the type of merge (left, inner, outer, etc..).

  • The parameter on specifies the column(s) on which the merge will be performed.

  • The parameter validate` specifies a way to verify if the merge result is what was expected.

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:

  1. As an array of 7 1 or 0 values, e.g. [1, 1, 1, 1, 1, 0, 0]

  2. As a string of 7 1 or 0 characters, e.g. “1111100”

  3. 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”

Setting an incorrect weekmask leads to ValueError.

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:

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.

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.

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.

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.

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.

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.

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.

A `SystemExit exception is raised when 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, i.e. an except block without any exception class, is equivalent to except 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 exception. Similarly to SystemExit,KeyboardInterrupt` is used to signal the interpreter to exit. Not re-raising such exception could also lead to undesired behaviour.

Using inplace=True when modifying a Pandas DataFrame means that the method will modify the DataFrame in place, rather than returning a new object:

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:

  • comparing unrelated builtin types such as string and integer.

  • 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`).

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:

  • an `assert statement or a unittest’s assertTrue or assertFalse method is called with a value which will be always True or always False.

  • a unittest’s assertIsNotNone or assertIsNone method is called with a value which will always be None or never be None.

  • a unittest’s assertIsNot or assertIs method is called with a literal expression creating a new object every time (ex: [1, 2, 3]`).

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.

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.

An 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 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 and generator expressions have both next and iter` methods generated automatically.

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 has no real private attribute. Every attribute is accessible. There are however two conventions indicating that an attribute is not meant to be “public”:

  • 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.

  • ”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.

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.

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.

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.

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 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.

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:

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.

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.

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:

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.

The repetition of a prefix operator (not or ~) is usually a typo. The second operator invalidates the first one:

Checking that variable X has type T with type annotations 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.”). 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.

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:

  • referenced while not defined;

  • defined but called elsewhere in the code by their number instead.

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.

Nested conditionals are hard to read and can make the order of operations complex to understand.

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.

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.

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.

An except clause that only rethrows the caught exception has the same effect as omitting the except altogether and letting it bubble up automatically.

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:

Legacy function name

numpy.random.Generator alternative

numpy.random.RandomState.seed

numpy.random.default_rng

numpy.random.RandomState.rand

numpy.random.Generator.random

numpy.random.RandomState.randn

numpy.random.Generator.standard_normal

numpy.random.RandomState.randint

numpy.random.Generator.integers

numpy.random.RandomState.random_integers

numpy.random.Generator.integers

numpy.random.RandomState.random_sample

numpy.random.Generator.random

numpy.random.RandomState.choice

numpy.random.Generator.choice

numpy.random.RandomState.bytes

numpy.random.Generator.bytes

numpy.random.RandomState.shuffle

numpy.random.Generator.shuffle

numpy.random.RandomState.permutation

numpy.random.Generator.permutation

numpy.random.RandomState.beta

numpy.random.Generator.beta

numpy.random.RandomState.binomial

numpy.random.Generator.binomial

numpy.random.RandomState.chisquare

numpy.random.Generator.chisquare

numpy.random.RandomState.dirichlet

numpy.random.Generator.dirichlet

numpy.random.RandomState.exponential

numpy.random.Generator.exponential

numpy.random.RandomState.f

numpy.random.Generator.f

numpy.random.RandomState.gamma

numpy.random.Generator.gamma

numpy.random.RandomState.geometric

numpy.random.Generator.geometric

numpy.random.RandomState.gumbel

numpy.random.Generator.gumbel

numpy.random.RandomState.hypergeometric

numpy.random.Generator.hypergeometric

numpy.random.RandomState.laplace

numpy.random.Generator.laplace

numpy.random.RandomState.logistic

numpy.random.Generator.logistic

numpy.random.RandomState.lognormal

numpy.random.Generator.lognormal

numpy.random.RandomState.logseries

numpy.random.Generator.logseries

numpy.random.RandomState.multinomial

numpy.random.Generator.multinomial

numpy.random.RandomState.multivariate_normal

numpy.random.Generator.multivariate_normal

numpy.random.RandomState.negative_binomial

numpy.random.Generator.negative_binomial

numpy.random.RandomState.noncentral_chisquare

numpy.random.Generator.noncentral_chisquare

numpy.random.RandomState.noncentral_f

numpy.random.Generator.noncentral_f

numpy.random.RandomState.normal

numpy.random.Generator.normal

numpy.random.RandomState.pareto

numpy.random.Generator.pareto

numpy.random.RandomState.poisson

numpy.random.Generator.poisson

numpy.random.RandomState.power

numpy.random.Generator.power

numpy.random.RandomState.rayleigh

numpy.random.Generator.rayleigh

numpy.random.RandomState.standard_cauchy

numpy.random.Generator.standard_cauchy

numpy.random.RandomState.standard_exponential

numpy.random.Generator.standard_exponential

numpy.random.RandomState.standard_gamma

numpy.random.Generator.standard_gamma

numpy.random.RandomState.standard_normal

numpy.random.Generator.standard_normal

numpy.random.RandomState.standard_t

numpy.random.Generator.standard_t

numpy.random.RandomState.triangular

numpy.random.Generator.triangular

numpy.random.RandomState.uniform

numpy.random.Generator.uniform

numpy.random.RandomState.vonmises

numpy.random.Generator.vonmises

numpy.random.RandomState.wald

numpy.random.Generator.wald

numpy.random.RandomState.weibull

numpy.random.Generator.weibull

numpy.random.RandomState.zipf

numpy.random.Generator.zipf

numpy.random.beta

numpy.random.Generator.beta

numpy.random.binomial

numpy.random.Generator.binomial

numpy.random.bytes

numpy.random.Generator.bytes

numpy.random.chisquare

numpy.random.Generator.chisquare

numpy.random.choice

numpy.random.Generator.choice

numpy.random.dirichlet

numpy.random.Generator.dirichlet

numpy.random.exponential

numpy.random.Generator.exponential

numpy.random.f

numpy.random.Generator.f

numpy.random.gamma

numpy.random.Generator.gamma

numpy.random.geometric

numpy.random.Generator.geometric

numpy.random.gumbel

numpy.random.Generator.gumbel

numpy.random.hypergeometric

numpy.random.Generator.hypergeometric

numpy.random.laplace

numpy.random.Generator.laplace

numpy.random.logistic

numpy.random.Generator.logistic

numpy.random.lognormal

numpy.random.Generator.lognormal

numpy.random.logseries

numpy.random.Generator.logseries

numpy.random.multinomial

numpy.random.Generator.multinomial

numpy.random.multivariate_normal

numpy.random.Generator.multivariate_normal

numpy.random.negative_binomial

numpy.random.Generator.negative_binomial

numpy.random.noncentral_chisquare

numpy.random.Generator.noncentral_chisquare

numpy.random.noncentral_f

numpy.random.Generator.noncentral_f

numpy.random.normal

numpy.random.Generator.normal

numpy.random.pareto

numpy.random.Generator.pareto

numpy.random.permutation

numpy.random.Generator.permutation

numpy.random.poisson

numpy.random.Generator.poisson

numpy.random.power

numpy.random.Generator.power

numpy.random.rand

numpy.random.Generator.random

numpy.random.randint

numpy.random.Generator.integers

numpy.random.randn

numpy.random.Generator.standard_normal

numpy.random.random

numpy.random.Generator.random

numpy.random.random_integers

numpy.random.Generator.integers

numpy.random.random_sample

numpy.random.Generator.random

numpy.random.ranf

numpy.random.Generator.random

numpy.random.rayleigh

numpy.random.Generator.rayleigh

numpy.random.sample

numpy.random.Generator.random

numpy.random.seed

numpy.random.default_rng

numpy.random.shuffle

numpy.random.Generator.shuffle

numpy.random.standard_cauchy

numpy.random.Generator.standard_cauchy

numpy.random.standard_exponential

numpy.random.Generator.standard_exponential

numpy.random.standard_gamma

numpy.random.Generator.standard_gamma

numpy.random.standard_normal

numpy.random.Generator.standard_normal

numpy.random.standard_t

numpy.random.Generator.standard_t

numpy.random.triangular

numpy.random.Generator.triangular

numpy.random.uniform

numpy.random.Generator.uniform

numpy.random.vonmises

numpy.random.Generator.vonmises

numpy.random.wald

numpy.random.Generator.wald

numpy.random.weibull

numpy.random.Generator.weibull

numpy.random.zipf

numpy.random.Generator.zipf

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.

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. 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.

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!

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.

Raising instances of `Exception and 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.

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.

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.

Prior to Python 3.12 functions using generic types were created as follows:

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.

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.

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’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:

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:

  • Security Risks: Executing code from a string opens up the possibility of code injection attacks.

  • 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.

  • Performance Implications: The use of exec statement can have performance implications since the code is compiled and executed at runtime.

  • 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.

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.

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.

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.

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.

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:

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.

In order to be callable, a Python class should implement the `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.

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 asserts.

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:

  • An argument is provided by value and position at the same time.

  • An argument is provided twice, once via unpacking and once by value or position.

The with statement is used to wrap the execution of a block with methods defined by a context manager. The context manager 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:

Importing every public name from a module using a wildcard (from mymodule import *) is a bad idea because:

  • It could lead to conflicts between names defined locally and the ones imported.

  • It reduces code readability as developers will have a hard time knowing where names come from.

  • It clutters the local namespace, which makes debugging more difficult.

Remember that imported names can change when you update your dependencies. A wildcard import that works today might be broken tomorrow.

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.

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.

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 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:

  • bool method should return bool

  • index method should return integer

  • repr method should return string

  • str method should return string

  • bytes method should return bytes

  • hash method should return integer

  • format method should return string

  • getnewargs method should return tuple

  • getnewargs_ex` method should return something which is of the form tuple(tuple, dict)

Getting, setting and deleting items using square brackets requires the accessed object to have special methods:

  • Getting items such as `my_variable[key] requires my_variable to have the getitem method, or the class_getitem method if my_variable is a class.

  • Setting items such as my_variable[key] = 42 requires my_variable to have the setitem method.

  • Deleting items such as del my_variable[key] requires my_variable to have the delitem method.

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.

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.

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.

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.

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.

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.

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.

The walrus operator := (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:

  • 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.

  • 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.

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.

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.

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. Specifically, an overriding method should be callable with the same parameters as the overriden one.

The following modifications are OK:

  • Adding an optional parameter, i.e. with a default value, as long as they don’t change the order of positional parameters.

  • Renaming a positional-only parameter.

  • Reordering keyword-only parameters.

  • Adding a default value to an existing parameter.

  • Changing the default value of an existing parameter.

  • 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.

  • Adding a vararg parameter (`*args).

  • Adding a keywords parameter (**kwargs).

The following modifications are not OK:

  • Removing parameters, even when they have default values.

  • Adding mandatory parameters, i.e. without a default value.

  • Removing the default value of a parameter.

  • Reordering parameters, except when they are keyword-only parameters.

  • 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.

  • Removing a vararg parameter (*args).

  • Removing a keywords parameter (**kwargs`).

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.

Having all branches of an if chain with the same implementation indicates a problem.

In the following code:

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.

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:

  • If your intention is to test the first value of the tuple and use the second value as a message, simply remove the parentheses.

  • If your intention is to check that every element of the tuple is True`, test each value separately.

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’.

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 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.

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.

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”:

  • 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.

  • ”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.

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.

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.

* 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.

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. 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 <[^>]+>.

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:

  • should contain only one of the following characters: r (read), w (write), a (append), x (create).

  • should contain zero or one of the following characters: t (text), b (binary).

  • should contain zero or one + character (open for updating)

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)

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:

  • Forced redirection

  • Modify presentation of content

  • User accounts takeover after disclosure of sensitive information like session cookies or passwords

This rule supports the following libraries:

A bare raise statement, i.e. a raise with no exception provided, will re-raise the last active exception in the current scope:

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.

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.

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.

Setting a date attribute value with a value which is out of the range of possible values will lead to a ValueError.

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.

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:

  • 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.

  • 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.

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:

  • Use the get() method instead of a subscription. It will return None for a missing key instead of raising a KeyError.

  • Use the setdefault() method to provide keys that may be missing with a default value.

  • Check that the key is present in the dictionary with the if key in dict: construct.

  • Use a try/except block and handle the potential KeyError exception.

  • Use a defaultdict instead of a regular dict object, and provide a default_factory attribute.

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._fooclass WithPropertyMethod(object): def get_foo(self): return self._foodef set_foo(self, value): self._foo = valuedef del_foo(self): del self._foofoo = 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:

  • Property getter and deleter methods only require a “self” argument.

  • Property setter methods require a “self” argument as well as a value.

Adding any other parameters, or removing these mandatory parameters will throw a TypeError` exception at runtime when trying to access or modify the property.

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.

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:

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.

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:

  • 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.

  • When multiple except statements try to catch the same exception class, only the first one will be executed.

  • 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:).

Importing names and not using them can be a source of confusion and lead to maintainability issues.

Such imports should be removed.

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.

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 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:

  • 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).

  • when the strings are in a list, a set or a tuple.

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, the str.format method, and loggers from the logging 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:

  • A string formatted with % will not return the expected text because some arguments are unused.

  • A string formatted with str.format will not return the expected string because some arguments are unused.

  • An “f-string” doesn’t contain any replacement field, which probably means some curly braces are missing.

  • Loggers will log an error because their message is not formatted properly.

Rule S2275 covers cases where formatting a string will raise an exception.

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.

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.

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.

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 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.

Variables, Classes and functions should be defined before they are used, otherwise the code will fail.

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.

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. 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.

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.

The print statement was removed in Python 3.0. The built-in function should be used instead.

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.

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.

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.

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 is raised when sys.exit() is called. 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

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.

Since Python 3.12 the keyword type is used to defined type aliases. It replaces the following construct:

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.

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.

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.:

It is needlessly complex to invert the result of a boolean comparison. The opposite comparison should be made instead.

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.

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:

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.

  • /tmp

  • /var/tmp

  • /usr/tmp

  • /dev/shm

  • /dev/mqueue

  • /run/lock

  • /var/run/lock

  • /Library/Caches

  • /Users/Shared

  • /private/tmp

  • /private/var/tmp

  • \Windows\Temp

  • \Temp

  • \TMP`

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.

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 `, between n and m times with , 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:

  • or : they match the expression exactly once. The same behavior can be achieved without the quantifier.

  • or `: they match the expression zero times. The same behavior can be achieved by removing the expression.

Putting multiple statements on a single line lowers the code readability and makes debugging the code more complex.

Unresolved directive in <stdin> - include::[]

Write one statement per line to improve readability.

Unresolved directive in <stdin> - include::[]

Resource-based policies granting access to all users can lead to information leakage.

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.

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.

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.

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.

Having a permissive Cross-Origin Resource Sharing policy is security-sensitive. It has led in the past to the following vulnerabilities:

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, that act like directives for the browser and change the access control policy / relax the same origin policy.

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.

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:

  • a boolean value that explicitly allows access to the public network.

  • the assignment of a public IP address.

  • database firewall rules that allow public IP ranges.

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:

  • data breaches.

  • intrusions into the infrastructure to permanently steal from it.

  • and various malicious traffic, such as DDoS attacks.

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:

  • A malicious insider working at the cloud provider gains physical access to the storage device.

  • Unknown attackers penetrate the cloud provider’s logical infrastructure and systems.

After a successful intrusion, the underlying applications are exposed to:

  • theft of intellectual property and/or personal data

  • extortion

  • denial of services and security bypasses via data corruption or deletion

AWS-managed encryption at rest reduces this risk with a simple switch.

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.

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.

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.

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.

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, attackers will compress irrelevant data (eg: a long string of repeated bytes).

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.

A policy that grants all permissions may indicate an improper access control, which violates the 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.

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.

An empty is generally considered bad practice and can lead to confusion, readability, and maintenance issues. Empty s bring no functionality and are misleading to others as they might think the implementation fulfills a specific and identified requirement.

There are several reasons for a not to have a body:

  • It is an unintentional omission, and should be fixed to prevent an unexpected behavior in production.

  • It is not yet, or never will be, supported. In this case an exception should be thrown.

  • The method is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override.

S3 buckets can be in three states related to versioning:

  • unversioned (default one)

  • enabled

  • suspended

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.

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::[]

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.

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:

  • sensitive data exposure

  • traffic redirected to a malicious endpoint

  • malware-infected software update or installer

  • execution of client-side code

  • corruption of critical information

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:

  • bypassing isolation mechanisms

  • compromising a component of the network

  • getting the credentials of an internal IAM account (either from a service account or an actual person)

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.

In the past, it has led to the following vulnerabilities:

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.

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.

A regular expression is a sequence of characters that specifies a match pattern in text. Among the most important concepts are:

  • Character classes: defines a set of characters, any one of which can occur in an input string for a match to succeed.

  • Quantifiers: used to specify how many instances of a character, group, or character class must be present in the input for a match.

  • Wildcard (.): matches all characters except line terminators (also matches them if the s flag is set).

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] or \d. 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:

  • \d for [0-9] and \D for [^0-9]

  • \w for [A-Za-z0-9_] and \W for `[^A-Za-z0-9_]

  • . for character classes matching everything (e.g. [\w\W], [\d\D], or [\s\S] with s flag)

  • x? for x0,1, x* for x0, x+ for x1, xN for xN,N

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:

  • Server-Side Encryption with Amazon S3-Managed Keys (SSE-S3)

    • AWS manages encryption keys and the encryption itself (with AES-256) on its own.

  • Server-Side Encryption with Customer Master Keys (CMKs) Stored in AWS Key Management Service (SSE-KMS)

    • AWS manages the encryption (AES-256) of objects and encryption keys provided by the AWS KMS service.

  • Server-Side Encryption with Customer-Provided Keys (SSE-C)

    • 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.

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.

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.

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.

In regular expressions, anchors (^, ,A,Zandz)havehigherprecedencethanthe∣operator.Soinaregularexpressionlikealt1∣alt2∣alt3, A, Z and z) have higher precedence than the | operator. So in a regular expression like ^alt1|alt2|alt3, 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.

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.

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.

When placing Unicode Grapheme Clusters (characters which require to be encoded in multiple Code Points) 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.

Shared naming conventions allow teams to collaborate efficiently.

This rule raises an issue when a class name does not match a provided regular expression.

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.

Constructing arguments of system commands from user input is security-sensitive. It has led in the past to the following vulnerabilities:

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.

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.

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.

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 and the context, for example a “html auto-escaping” strategy (which only transforms html characters into html entities) will not be relevant when variables are used in a 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)

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.

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.

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. Volumes created from snapshots inherit their encryption configuration. A volume created from an encrypted snapshot will also be encrypted by default.

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.

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.

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.

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:

  1. 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.

  2. The statements are residual after a refactoring.

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.

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.

Duplicated string literals make the process of refactoring complex and error-prone, as any change would need to be propagated on all occurrences.

According to the US National Institute of Standards and Technology (NIST), the Data Encryption Standard (DES) is no longer considered secure:

For similar reasons, RC2 should also be avoided.

Predefined permissions, also known as canned ACLs, are an easy way to grant large privileges to predefined groups or users.

The following canned ACLs are security-sensitive:

  • `PublicRead, PublicReadWrite grant respectively “read” and “read and write” privileges to everyone in the world (AllUsers group).

  • AuthenticatedRead grants “read” privilege to all authenticated users (AuthenticatedUsers` group).

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.

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.

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.

Shared coding conventions allow teams to collaborate efficiently. This rule checks that all function names match a provided regular expression.

Two 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.

Hardcoding IP addresses is security-sensitive. It has led in the past to the following vulnerabilities:

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:

  • The developers will have to do a rapid fix every time this happens, instead of having an operation team change a configuration file.

  • It misleads to use the same address in every environment (dev, sys, qa, prod).

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.

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.

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.

A policy that allows identities to access all resources in an AWS account may violate the 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.

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.

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.

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.

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.

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).

Possessive quantifiers in Regex patterns like below improve performance by eliminating needless backtracking:

?+ , *+ , ++ , n+ , n,+ , n,m+

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.

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.

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:

  • `BlockPublicAcls: to block or not public ACLs to be set to the S3 bucket.

  • IgnorePublicAcls: to consider or not existing public ACLs set to the S3 bucket.

  • BlockPublicPolicy: to block or not public policies to be set to the S3 bucket.

  • RestrictPublicBuckets: to restrict or not the access to the S3 endpoints of public policies to the principals within the bucket owner account.

There are several reasons to use a group in a regular expression:

  • to change the precedence (e.g. do(g|or) will match ‘dog’ and ‘door’)

  • to remember parenthesised part of the match in the case of capturing group

  • to improve readability

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.

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:

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”, …​

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.

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.

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.

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.

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.

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.

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.