Definition
Recipes78
78 recipes
- Use
{}literal instead ofdict()constructor - Use
[]literal instead oflist()constructor - Use
()literal instead oftuple()constructor - Prefer set literals in
inmembership tests - Flatten redundant collection constructor wrapping a literal
- Drop unnecessary
0start argument fromrange() - Drop unnecessary step
1argument fromrange() - Compare to
Nonewith identity operators (is/is not) - Fold same-literal
==/!=comparisons to boolean constants - Collapse self-cancelling
^/-with duplicate operands to0 - Rewrite self-multiplication as
** 2 - Remove explicit True/False comparisons
- Collapse boolean ternary to bare condition
- Eliminate boolean literal from
and/or - Replace
len()emptiness check with truthiness - Compare string to
""instead of checkinglen() - Substitute constant collection condition with boolean
- Flatten negated logic via De Morgan's identities
- Reorder comparisons to put literals on the right
- Replace
.find()check within/not in - Consolidate repeated
==withorintoin - Merge
isinstance()calls - Replace self-referencing ternary with
or - Swap ternary branches to drop negated condition
- Shorten assignment to compound operator form
- Remove redundant ternary condition
- Collapse nested `
ifinto a singleand` condition - Convert `
else: iftoelif - Flip empty `
if`-body by negating the condition - Drop `
pass-onlyelif` by negating its condition - Simplify negated `
eliftoelse - Drop `
elseafter early-exitif` branch - Use inline conditional for simple `
if/else` assignment - Remove redundant pass statements
- Strip trailing `
continue` from loop body - Drop `
exists()check beforeis_dir()/is_file() - Delete no-op
assert Truestatements - Strip dead code after terminal statements
- Delete
ifblocks whose body is onlypass - Unwrap `
str()fromprint()` arguments - Remove redundant
Nonedefault fromdict.get() - Drop `
f` prefix from strings without placeholders - Strip `
str()` from f-string placeholders - Prefer `
startswith/endswith` over slice comparison - Use bracket access for `
re.Match` groups - Fold constants and flatten nested f-strings
- Replace string slicing with
removeprefix/removesuffix - Drop redundant
.keys()on dict iteration - Convert one-item
dict.update()to bracket assignment - Use dict union operator instead of double-star unpacking
- Unwrap unnecessary
dict()from union operands - Deduplicate repeated keys in dict literals
- Deduplicate repeated elements in set literals
- Iterate over file objects directly, not via
readlines() - Flatten
for/elsewhen the loop has nobreak - Collapse for-yield loop into
yield from - Use comprehension syntax instead of
list()/set()around generators - Pass iterable directly to
any()/all()instead of identity generator - Use generator expression instead of list comprehension in iterable-accepting calls
- Simplify identity comprehension to
list()/set()call - Swap
not all()/not any()by negating the comparison - Apply De Morgan's law to
any(not ...)/all(not ...) - Rewrite
any(v == literal ...)asliteral in collection - Simplify
sum(1 for x in items if cond)tosum(bool(cond) for x in items) - Narrow bare
except:toexcept Exception: - Unwrap one-element exception tuple in
except - Chain exceptions with
raise ... fromin except blocks - Replace
try/except: passwithcontextlib.suppress() - Standardize
@classmethodfirst parameter tocls - Eliminate
inplace=Truein favor of reassignment - Convert
apply('name')to a direct method invocation - Use
.isna()instead of== np.nancomparisons - Convert
and/orternary trick to conditional expression - Guard mutable default arguments with
Nonesentinel - Simplify temp-variable swap to tuple unpacking
- Remove
break/continueoutside loop - Remove
return/yieldoutside function - Use
datetime.now()instead ofdatetime.today()
Usage
Run this recipe
In order to run Python recipes, you will need to use the Moderne CLI.
Once the CLI is installed, you can install this Python recipe package by running the following command:
Install the recipe package
mod config recipes pip install openrewrite-static-analysis
Then, you can run the recipe via:
Run the recipe
mod run . --recipe org.openrewrite.python.cleanup.PythonBestPractices