Python cleanup suite
Recipe ID
org.openrewrite.python.cleanup.PythonBestPracticesArtifactopenrewrite-static-analysisRun every Python cleanup recipe in one pass -- literal simplification, boolean and comparison tidying, dead code removal, naming fixes, pandas modernization, and more.
Composite recipepythoncleanupbest-practicesProprietary
Usage
This recipe has no required configuration options. You’ll need the Moderne CLI configured before running the command below.
mod run . --recipe org.openrewrite.python.cleanup.PythonBestPracticesIf the recipe isn’t available locally, install it with:
mod config recipes pip install openrewrite-static-analysisDefinition
This recipe runs the following recipes in order.
- Use
{}literal instead ofdict()constructororg.openrewrite.python.cleanup.DictLiteral - Use
[]literal instead oflist()constructororg.openrewrite.python.cleanup.ListLiteral - Use
()literal instead oftuple()constructororg.openrewrite.python.cleanup.TupleLiteral - Prefer set literals in
inmembership testsorg.openrewrite.python.cleanup.CollectionIntoSet - Flatten redundant collection constructor wrapping a literal
org.openrewrite.python.cleanup.UnwrapIterableConstruction - Drop unnecessary
0start argument fromrange()org.openrewrite.python.cleanup.RemoveZeroFromRange - Drop unnecessary step
1argument fromrange()org.openrewrite.python.cleanup.RemoveUnitStepFromRange - Compare to
Nonewith identity operators (is/is not)org.openrewrite.python.cleanup.NoneCompare - Fold same-literal
==/!=comparisons to boolean constantsorg.openrewrite.python.cleanup.EqualityIdentity - Collapse self-cancelling
^/-with duplicate operands to0org.openrewrite.python.cleanup.BinOpIdentity - Rewrite self-multiplication as
** 2org.openrewrite.python.cleanup.SquareIdentity - Remove explicit True/False comparisons
org.openrewrite.python.cleanup.SimplifyBooleanComparison - Collapse boolean ternary to bare condition
org.openrewrite.python.cleanup.BooleanIfExpIdentity - Eliminate boolean literal from
and/ororg.openrewrite.python.cleanup.RemoveRedundantBoolean - Replace
len()emptiness check with truthinessorg.openrewrite.python.cleanup.SimplifyLenComparison - Compare string to
""instead of checkinglen()org.openrewrite.python.cleanup.SimplifyStrLenComparison - Substitute constant collection condition with boolean
org.openrewrite.python.cleanup.CollectionToBool - Flatten negated logic via De Morgan's identities
org.openrewrite.python.cleanup.DeMorgan - Reorder comparisons to put literals on the right
org.openrewrite.python.cleanup.FlipComparison - Replace
.find()check within/not inorg.openrewrite.python.cleanup.SimplifySubstringSearch - Consolidate repeated
==withorintoinorg.openrewrite.python.cleanup.MergeComparisons - Merge
isinstance()callsorg.openrewrite.python.cleanup.MergeIsinstance - Replace self-referencing ternary with
ororg.openrewrite.python.cleanup.OrIfExpIdentity - Swap ternary branches to drop negated condition
org.openrewrite.python.cleanup.SwapIfExpression - Shorten assignment to compound operator form
org.openrewrite.python.cleanup.AugAssign - Remove redundant ternary condition
org.openrewrite.python.cleanup.RemoveRedundantCondition - Collapse nested `
ifinto a singleand` conditionorg.openrewrite.python.cleanup.MergeNestedIfs - Convert `
else: iftoeliforg.openrewrite.python.cleanup.MergeElseIfIntoElif - Flip empty `
if`-body by negating the conditionorg.openrewrite.python.cleanup.SwapIfElseBranches - Drop `
pass-onlyelif` by negating its conditionorg.openrewrite.python.cleanup.RemovePassElif - Simplify negated `
eliftoelseorg.openrewrite.python.cleanup.RemoveRedundantIf - Drop `
elseafter early-exitif` branchorg.openrewrite.python.cleanup.RemoveUnnecessaryElse - Use inline conditional for simple `
if/else` assignmentorg.openrewrite.python.cleanup.AssignIfExp - Remove redundant pass statements
org.openrewrite.python.RemovePass - Strip trailing `
continue` from loop bodyorg.openrewrite.python.cleanup.RemoveRedundantContinue - Drop `
exists()check beforeis_dir()/is_file()org.openrewrite.python.cleanup.RemoveRedundantPathExists - Delete no-op
assert Truestatementsorg.openrewrite.python.cleanup.RemoveAssertTrue - Strip dead code after terminal statements
org.openrewrite.python.cleanup.RemoveUnreachableCode - Delete
ifblocks whose body is onlypassorg.openrewrite.python.cleanup.RemoveEmptyNestedBlock - Unwrap `
str()fromprint()` argumentsorg.openrewrite.python.cleanup.RemoveStrFromPrint - Remove redundant
Nonedefault fromdict.get()org.openrewrite.python.cleanup.RemoveNoneFromDefaultGet - Drop `
f` prefix from strings without placeholdersorg.openrewrite.python.cleanup.RemoveRedundantFstring - Strip `
str()` from f-string placeholdersorg.openrewrite.python.cleanup.RemoveStrFromFstring - Prefer `
startswith/endswith` over slice comparisonorg.openrewrite.python.cleanup.StrPrefixSuffix - Use bracket access for `
re.Match` groupsorg.openrewrite.python.cleanup.UseGetitemForReMatchGroups - Fold constants and flatten nested f-strings
org.openrewrite.python.cleanup.SimplifyFstringFormatting - Replace string slicing with
removeprefix/removesuffixorg.openrewrite.python.cleanup.UseStringRemoveAffix - Drop redundant
.keys()on dict iterationorg.openrewrite.python.cleanup.RemoveDictKeys - Convert one-item
dict.update()to bracket assignmentorg.openrewrite.python.cleanup.SimplifyDictionaryUpdate - Use dict union operator instead of double-star unpacking
org.openrewrite.python.cleanup.UseDictionaryUnion - Unwrap unnecessary
dict()from union operandsorg.openrewrite.python.cleanup.RemoveRedundantConstructorInDictUnion - Deduplicate repeated keys in dict literals
org.openrewrite.python.cleanup.RemoveDuplicateDictKey - Deduplicate repeated elements in set literals
org.openrewrite.python.cleanup.RemoveDuplicateSetKey - Iterate over file objects directly, not via
readlines()org.openrewrite.python.cleanup.UseFileIterator - Flatten
for/elsewhen the loop has nobreakorg.openrewrite.python.cleanup.UselessElseOnLoop - Collapse for-yield loop into
yield fromorg.openrewrite.python.cleanup.YieldFrom - Use comprehension syntax instead of
list()/set()around generatorsorg.openrewrite.python.cleanup.CollectionBuiltinToComprehension - Pass iterable directly to
any()/all()instead of identity generatororg.openrewrite.python.cleanup.SimplifyGenerator - Use generator expression instead of list comprehension in iterable-accepting calls
org.openrewrite.python.cleanup.ComprehensionToGenerator - Simplify identity comprehension to
list()/set()callorg.openrewrite.python.cleanup.IdentityComprehension - Swap
not all()/not any()by negating the comparisonorg.openrewrite.python.cleanup.InvertAnyAll - Apply De Morgan's law to
any(not ...)/all(not ...)org.openrewrite.python.cleanup.InvertAnyAllBody - Rewrite
any(v == literal ...)asliteral in collectionorg.openrewrite.python.cleanup.ConvertAnyToIn - Simplify
sum(1 for x in items if cond)tosum(bool(cond) for x in items)org.openrewrite.python.cleanup.SimplifyConstantSum - Narrow bare
except:toexcept Exception:org.openrewrite.python.cleanup.DoNotUseBareExcept - Unwrap one-element exception tuple in
exceptorg.openrewrite.python.cleanup.SimplifySingleExceptionTuple - Chain exceptions with
raise ... fromin except blocksorg.openrewrite.python.cleanup.RaiseFromPreviousError - Replace
try/except: passwithcontextlib.suppress()org.openrewrite.python.cleanup.UseContextlibSuppress - Standardize
@classmethodfirst parameter toclsorg.openrewrite.python.cleanup.ClassMethodFirstArgName - Eliminate
inplace=Truein favor of reassignmentorg.openrewrite.python.cleanup.PandasAvoidInplace - Convert
apply('name')to a direct method invocationorg.openrewrite.python.cleanup.ReplaceApplyWithMethodCall - Use
.isna()instead of== np.nancomparisonsorg.openrewrite.python.cleanup.UseIsna - Convert
and/orternary trick to conditional expressionorg.openrewrite.python.cleanup.TernaryToIfExpression - Guard mutable default arguments with
Nonesentinelorg.openrewrite.python.cleanup.DefaultMutableArg - Simplify temp-variable swap to tuple unpacking
org.openrewrite.python.cleanup.SwapVariable - Remove
break/continueoutside looporg.openrewrite.python.cleanup.BreakOrContinueOutsideLoop - Remove
return/yieldoutside functionorg.openrewrite.python.cleanup.ReturnOrYieldOutsideFunction - Use
datetime.now()instead ofdatetime.today()org.openrewrite.python.cleanup.UseDatetimeNowNotToday