Refactorings
Documentation Index
Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt
Use this file to discover all available pages before exploring further.
These are the built-in rules for Sourcery’s original refactoring tool, which suggests automatic code improvements. The tool is still available, and each page shows what a rule looks for and the change it suggests. There are 212 rules today.
These are distinct from review rules, which your team writes to guide code review.
Python
Section titled “Python”- Assign If Expression – Replaces conditional assignment to a variable with an if expression
- Augmented Assign – Replaces assignments with augmented assignments
- Avoid Builtin Shadow – Don’t assign to builtin variables, such as list.
- Aware datetime For UTC – For getting the current time in UTC, use an aware datetime object with the timezone explicitly set to UTC.
- Binary Operator Identity – Replaces binary operations between a value and itself with known identities:
- Boolean If Expression Identity – Simplifies boolean if expressions by removing unnecessary explicit references to True or False states
- Break-Or-Continue-Outside-Loop – Remove break or continue statement found outside for or while loop
- Chain Compares – Combine two compares on same value into a chained compare
- Class Extract Method – Extracts duplicate pieces of code in different functions in a class into their own methods
- Class Method First Parameter Should Be
cls– Suggests that class methods should rename their first parameter to cls. - Collection to Comprehension – Use list, set or dictionary comprehensions directly instead of calling list(), dict() or set()
- Collection Into Set – Use set when checking membership of a collection of literals
- Collection to Bool – Replace constant collection with boolean in boolean contexts
- Compare Via Equals – Use == or != to compare str, bytes, int, and float.
- Comprehension to Generator – Replace unneeded comprehension with generator
- Convert Any to In – Converts any() functions to simpler in statements
- Convert to Enumerate – Replaces manual loop counter with call to enumerate
- DataFrame Append to Concat – Use pandas.concat() instead of the deprecated DataFrame.append().
- De Morgan’s Laws – Simplifies conditional logic using De Morgan’s laws
- Default Get – Simplify dictionary access by using the default get method
- Default Mutable Arguments – Replaces use of default mutable arguments in a function
- Del Comprehension – Replaces cases where deletions are made via for loops with comprehensions
- Dict Assign-Update to Union – Changes dictionary assignments and updates to use the union operator.
- Dictionary Comprehension – Replaces dictionaries created with for loops with dictionary comprehensions
- Dict-Literal – Replace
dict()with{} - Do Not Use Bare Except – Use except: Exception rather than bare except
- Dont-Import-Test-Modules – Don’t import test modules.
- Ensure File Closed – Use with when opening file to ensure closure
- Equality Identity – Simplify equality comparisons that are always True or False
- Extract Duplicate Method – Identifies duplicate sections of code in a function and extracts these into their own method
- Extract Method – Extracts complex pieces of functions into their own methods
- Flatten Nested Try – Merge nested try-statement into a single try
- Flip Comparison – Moves variables from the right side to the left side of comparisons
- For Append To Extend – Replace a for append loop with list extend
- For Index Replacement – Replace item lookups in loops using the index with direct reference to the items
- Replace For Index with Underscore – Replaces an unused index in a for loop or comprehension with an underscore
- Guard – Adds in guard clause to a conditional
- Hoist If from If – Moves if statements that match a conditional out of that conditional
- Hoist Loop from If – Moves loops that occur in all cases of an if statement outside of the conditional
- Hoist Repeated If Condition – Move a repeated condition to a parent if block.
- Hoist Similar Statements from If – Hoist nested repeated code outside conditional statements
- Hoist Statements from If – Moves statements that occur in all cases of an if statement outside of the conditional
- Hoist Statement from Loop – Moves statements that are constant across all cases of a loop outside of the loop
- Identity Comprehensions – Convert list/set/tuple comprehensions that do not change the input elements into
- Inline Immediately Returned Variables – Inlines a variable to a return in the case when the variable being declared is immediately returned
- Inline Immediately Yielded Variable – Inline variable that is immediately yielded
- Inline Variable – Inline variable that is only used once
- Instance Method First Parameter Should Be
self– Suggests that instance methods should rename their first parameter to self. - Introduce Default Else – Move default state of variable into else branch
- Invert Any/All in Body – Simplifies any and all statements that can be inverted
- Invert Any/All – Switches not any or not all statements to all or any statements respectively
- Last if statement guard – Convert the final conditional into a guard clause
- Lift Duplicated Conditional – Lift repeated conditional into its own if statement
- Lift Return into If – Lift return into if
- List Comprehension – Converts a for loop into a list comprehension
- List Literal – Replaces lists created with list() with []
- Low Code Quality – Low code quality found in function.
- Max/min Default – Use max/min default argument instead of if statement
- Merge Assignment and Augmented Assignment – Replaces an assignment and an augmented assignment with a single assignment.
- Merge Comparisons – Consolidates multiple comparisons into a single comparison
- Merge Dictionary Assignments – Declare the dictionary with values rather than creating an empty one and assigning to it
- Merge Duplicate Blocks – Restructure conditional to merge duplicate branches together
- Merge Else If Into Elif – Merge else clause’s nested if statement into elif
- Merge Exception Handlers – Merge exception handlers with the same body into a single except handler.
- Merge isinstance – Combines together multiple isinstance functions
- Merge List Append – Create the list with values instead of creating an empty list and appending to it
- Merge List Appends Into Extend – Merge consecutive list appends into a single extend.
- Merge List Extend – Create the list with values instead of creating an empty list and extending it with another list
- Merge-Nested-Ifs – Merge nested if conditions
- Merge Repeated Ifs – Merges together the interior contents of if statements with identical conditions
- Merge Set Add – Create the set with values instead of declaring an empty set and adding to it
- Method_chaining – Chaining methods improves readability
- Min/Max identity – Replaces duplicate conditionals looking for the minimum or maximum value of multiple variables with a min or max function
- Missing Dict Items – Add missing .items() call when unpacking a dictionary
- Move Assign In Block – Moves assignment of variables closer to their usage within a block
- Move Assign – Moves assignment of variables closer to their usage
- No-Conditionals-In-Tests – Avoid conditionals in tests.
- No-Loop-In-Tests – Avoid loops in tests.
- Non Equal Comparison – Simplify comparison of non equal values
- None Compare – Replaces == with is when comparing to None
- Or-If-Exp-Identity – Replace if-expression with
or - Pandas: Avoid inplace – Don’t use inplace for methods that always create a copy under the hood.
- pathlib.Path Read – Simplify basic file reads with pathlib.
- Raise From Previous Error – Suggests raising from a previously-raised exception.
- Raise-Specific-Error – Raise a specific error instead of the general
ExceptionorBaseException - Reintroduce Else – Lift code into else after break in control flow
- Remove Assert True – Remove assert True statements
- Remove Dict Items – Remove unnecessary calls to dict.items when the values are not used.
- Remove Dictionary Keys – Removes unnecessary call to keys() when iterating over a dictionary
- Remove Duplicate Dict Key – Remove duplicate keys when instantiating dicts.
- Remove Duplicate Set Key – Remove duplicate keys when instantiating sets.
- Remove Empty Nested Block – Remove nested block which has no effect
- Remove-None-From-Default-Get – Replace
dict.get(x, None)withdict.get(x) - Remove Pass From Body – Removes a pass from the body of a conditional by inverting it
- Remove Pass From Elif – Removes a pass from the elif section of a conditional
- Remove Redundant Boolean – Removes redundant booleans from tests.
- Remove Redundant Condition – Remove a redundant condition used during variable assignment
- Remove Redundant Constructor in Dict Union
- Remove Redundant Continue – Remove redundant continue statement
- Remove Redundant Except Handler – Removes exception handlers that can never trigger (as the exceptions have already been caught)
- Remove Redundant Exception – Remove redundant exceptions from an except clause.
- Remove Redundant f-string – If an f-string has no replacements turn it into a regular string.
- Remove Redundant If Statements – Removes conditional tests where the conditional is always True or False
- Remove Redundant Pass – Removes unnecessary pass statements
- Remove-Redundant-Path-Exists – Remove unnecessary
path.exists()check. - Remove Redundant Slice Index – Removes unnecessary slice indices.
- Remove Str From Fstring – Remove unnecessary calls to str() within formatted values in f-strings
- Remove str() from call to print() – Removes unnecessary calls to str() from within print()
- Remove-Unit-Step-From-Range – Replace range(x, y, 1) with range(x, y)
- Remove Unnecessary Cast – Remove unnecessary casts to int, str, float and bool
- Remove Unnecessary Else – Remove unnecessary else after guard condition
- Remove Unreachable Code – Removes code that will never be executed
- Remove Unused Enumerate – Remove unnecessary calls to enumerate when the index variable is not used.
- Remove-Zero-From-Range – Replace range(0, x) with range(x)
- Replace
applyWith Method Call – Replace .apply with a call to a DataFrame’s or Series’s method. - Replace apply With NumPy Operation – Replace apply with a NumPy operation.
- Replace Dict Items with Values – Replace calls to dict.items with dict.values when the keys are not used.
- Replace Interpolation With Fstring – Replace usage of string interpolation % operator with f-strings
- Return or Yield Outside Function – Remove return or yield statements found outside function definitions.
- Set Comprehension – Replaces sets created with for loops with set comprehensions
- Simplify Boolean Comparison – Removes unnecessarily verbose boolean comparisons
- Simplify-Constant-Sum – Simplify constant sum() call
- Simplify Dictionary Update – Add single value to dictionary directly rather than using update()
- Simplify Division – Use Python’s built-in feature for succinct division syntax.
- Simplify Empty Collection Comparison – Replace an empty collection comparison with a more idiomatic unary operator.
- Simplify f-string Formatting – Simplify the formatting of replacements within an f-string.
- Simplify Generator – An identity generator (a for a in coll) can be replaced directly with the collection coll
- Simplify Length Comparison – Removes unnecessarily verbose length comparisons
- Simplify Negative Index – Replaces a[len(a)-1] with negative index lookup a[-1]
- Simplify Numeric Comparison – Consolidates any mathematical operations in a numeric comparison so there is a direct comparison of variable to number
- Simplify Single Exception Tuple – Replace length-one exception tuple with exception.
- Simplify String Length Comparison – Changes an indirect comparison of a string’s length to 0 into a direct comparison of the string to the empty string.
- Simplify substring search – Simplify finding if substrings are present in strings by using in
- Skip Sorted List Construction – Removes an unnecessary intermediate construction call for a sorted list, in favour of the sorted builtin.
- Split or ifs – Splits out conditions combined with an or in an if statement into their own if statement.
- Square Identity – Replaces cases of a variable being multiplied by itself with squaring that variable
- Str Prefix Suffix – Replace explicit str prefix/suffix check with call to startswith/endswith.
- Sum Comprehension – Replaces summed values created with for loops with sum comprehensions
- Swap If Else Branches – Swaps if and else branches of conditionals
- Swap-If-Expression – Swap if/else branches of if expression to remove negation
- Swap Nested Ifs – Swaps the order of nested if statements
- Swap Variable – Swap variable values with tuple assignment
- Switch – Simplify conditionals into a form more like a switch statement
- Ternary to If Expression – Replace boolean ternary with inline if expression.
- Tuple-Literal – Replace
tuple()with() - Unwrap Iterable Construction – Unwrap an iterable constructor into a literal iterable.
- Use Any – Use any rather than a for loop
- Use Assigned Variable – Uses a variable that was previously defined in the function instead of repeating what was defined in the variable
- Use
contextlib.suppress– Use contextlib’s suppress method to silence a specific error, instead of passing in an exception handler. This refactoring will add an import for… - Use Count – Replaces sum() with count() where appropriate
- Use Datetime Now Not Today – Replace calls to datetime.datetime.today() with datetime.datetime.now(). They are functionally equivalent, but now is a more expressive name.
- Use Dictionary Items – Use dictionary.items() in for loops to access both key and value at same time
- Use Dictionary Union – Replace a sequence of unpacked dictionaries with a use of the dictionary union operator.
- Use File Iterator – Use the in-built file iterator rather than calling readlines()
- Use Fstring For Concatenation – Use f-strings for concatenating strings instead of ’+’
- Use FString For Formatting – Replace calls to string.format() with f-strings.
- Use Getitem For Re Match Groups – Access groups in re.Match objects using getitem
- Use-Isna – Use
.isna()or.isnull()instead of== np.nanfor detecting missing values. - Use
itertools.product– Replaces a nested for loop over independent iterables with itertools.product. This refactoring won’t be activated if either iterable is a literal such as… - Use str.join() – Use str.join() instead of for loop
- Use len() – Replaces sum() with len where appropriate
- Use Named Expression – Merge assignment followed by conditional check using a named expression.
- Use Next – Use the built-in function next instead of a for-loop.
- Use-Or-For-Fallback – Use
orfor providing a fallback value - Use String Remove Affix – Replaces string slicing with the Python 3.9 features removesuffix and removeprefix.
- Use_iloc – Use the
.ilocattribute for index-based selection - Useless-Else-On-Loop – Loop’s else clause is always executed - move code to same level as loop
- While-Guard-To-Condition – Move a guard clause in a while statement’s body into its test
- Replace while with for – Replaces a while loop with a counter by a for loop
- Yield from – Replaces yield as part of for loops with yield from
JavaScript
Section titled “JavaScript”- Assignment-Operator – Replace assignment with assignment operator
- Avoid-Function-Declarations-In-Blocks – Avoid function declarations, favouring function assignment expressions, inside blocks.
- Avoid-Infinite-Loops – Avoid loops with missing or constant end conditions.
- Avoid-Jumping-In-Finally – Avoid the use of jump statements in
finallyblocks. - Avoid-Using-Var – Use
constorletinstead ofvar. - Binary-Operator-Identity – Simplify binary operation
- Combine-Object-Destructuring – Combine destructure assignments.
- Dont-Concatenate-String-Literals – Do not concatenate string literals
- Dont-Negate-Is-Instanceof-Operands –
inandinstanceofhave lower precedence than negation operators. - Dont-Reassign-Caught-Exceptions – Don’t reassign the bound exception ${exc}
- Dont-Reassign-Foreach-Variables – Don’t reassign the for-each variable ${var}
- Dont-Reassign-Parameters – Don’t reassign parameter - ${param}
- Dont-Self-Assign-Variables – Assigning a variable to itself has no effect.
- Dont-Shadow-Arguments – Don’t shadow
arguments. - Dont-Use-With – Avoid using
withstatements. - Dont-Use-Wrappers-For-Builtins – Don’t use
newsyntax withString,NumberandBooleanobjects - Flatten-Nested-Try – Merge nested try-statement into a single try
- Flip-Comparison – Moves variables from the right side to the left side of comparisons
- Generators-Should-Yield – Avoid writing generators that don’t
yieldany values. - Inline-Immediately-Returned-Variable – Inline variable that is immediately returned
- Invert-Ternary – Invert ternary operator to remove negation
- Max-Min-Identity – Use max/min instead of if statement
- Merge-Else-If – Merge else clause’s nested if statement into
else if - Merge-Nested-Ifs – Merge nested if conditions
- Misplaced-Break-Or-Continue – This
breakorcontinuedoes not refer to any valid loop or statement. - No-Eval – Never use
eval() - No-New-Function – Never use the
Functionconstructor. - No-New-Symbol – An instance of
Symbolcan only be created usingSymbolas a function - Only-Delete-Object-Properties – Delete should only be used for object properties.
- Possible-Incorrect-Bitwise-Operator – Flags possibly incorrect use of bitwise operators
|and&. - Remove-Redundant-Boolean – Remove unnecessary boolean value
- Remove-Redundant-If-Statement – Remove an
ifstatement where the condition istrue. - Remove-Redundant-Slice-Index – Remove a redundant index from the array
.slice()method. - Remove-Unreachable-Code – Remove unreachable code.
- Return-Outside-Function – Cannot use
returnoutside a function definition - Simplify-Ternary – Avoid unneeded ternary statements
- Throw-New-Errors – New errors should not be created without being thrown.
- Use-Array-Literal – Use literal syntax for array creation.
- Use-Object-Destructuring – Prefer object destructuring when accessing and using properties.
- Use-Ternary-Operator – Replace if statement with ternary operator
- While-Guard-To-Condition – Move a guard clause in a while statement’s body into its test
- Yield-Outside-Generator – Cannot use
yieldoutside a generator function