Cleanup
Composite Recipes
Recipes that include further recipes, often including the individual recipes below.
Recipes
- Apply De Morgan's law to
any(not ...)/all(not ...) - Chain exceptions with
raise ... fromin except blocks - Collapse boolean ternary to bare condition
- Collapse for-yield loop into
yield from - Collapse nested
ifinto a singleandcondition - Collapse self-cancelling
^/-with duplicate operands to0 - Compare string to
""instead of checkinglen() - Compare to
Nonewith identity operators (is/is not) - Consolidate repeated
==withorintoin - Convert
and/orternary trick to conditional expression - Convert
apply('name')to a direct method invocation - Convert
else: iftoelif - Convert
int(a / b)to floor division - Convert one-item
dict.update()to bracket assignment - Deduplicate repeated elements in set literals
- Deduplicate repeated keys in dict literals
- Delete
ifblocks whose body is onlypass - Delete no-op
assert Truestatements - Delete unnecessary
passin non-empty blocks - Drop default-value slice boundaries
- Drop
elseafter early-exitifbranch - Drop
exists()check beforeis_dir()/is_file() - Drop
fprefix from strings without placeholders - Drop
pass-onlyelifby negating its condition - Drop
pass-onlyifbody by inverting the guard - Drop redundant
.keys()on dict iteration - Drop unnecessary
0start argument fromrange() - Drop unnecessary step
1argument fromrange() - Eliminate boolean literal from
and/or - Eliminate
inplace=Truein favor of reassignment - Flatten
for/elsewhen the loop has nobreak - Flatten negated logic via De Morgan's identities
- Flatten redundant collection constructor wrapping a literal
- Flip empty
if-body by negating the condition - Fold constants and flatten nested f-strings
- Fold same-literal
==/!=comparisons to boolean constants - Guard mutable default arguments with
Nonesentinel - Iterate over file objects directly, not via
readlines() - Merge
isinstance()calls - Migrate deprecated
.append()topd.concat() - Narrow bare
except:toexcept Exception: - Pass iterable directly to
any()/all()instead of identity generator - Prefer set literals in
inmembership tests - Prefer
startswith/endswithover slice comparison - Remove
break/continueoutside loop - Remove explicit True/False comparisons
- Remove redundant
Nonedefault fromdict.get() - Remove redundant ternary condition
- Remove
return/yieldoutside function - Reorder comparisons to put literals on the right
- Replace
.find()check within/not in - Replace
len()emptiness check with truthiness - Replace self-referencing ternary with
or - Replace string slicing with
removeprefix/removesuffix - Replace
try/except: passwithcontextlib.suppress() - Rewrite
any(v == literal ...)asliteral in collection - Rewrite self-multiplication as
** 2 - Shorten assignment to compound operator form
- Simplify identity comprehension to
list()/set()call - Simplify negated
eliftoelse - Simplify
sum(1 for x in items if cond)tosum(bool(cond) for x in items) - Simplify temp-variable swap to tuple unpacking
- Standardize
@classmethodfirst parameter tocls - Standardize instance method first parameter to
self - Strip dead code after terminal statements
- Strip
str()from f-string placeholders - Strip trailing
continuefrom loop body - Substitute constant collection condition with boolean
- Swap
not all()/not any()by negating the comparison - Swap ternary branches to drop negated condition
- Unwrap one-element exception tuple in
except - Unwrap
str()fromprint()arguments - Unwrap unnecessary
dict()from union operands - Use
()literal instead oftuple()constructor - Use
.isna()instead of== np.nancomparisons - Use
[]literal instead oflist()constructor - Use bracket access for
re.Matchgroups - Use chained comparison syntax
- Use comprehension syntax instead of
list()/set()around generators - Use
datetime.now()instead ofdatetime.today() - Use dict union operator instead of double-star unpacking
- Use generator expression instead of list comprehension in iterable-accepting calls
- Use inline conditional for simple
if/elseassignment - Use negative index instead of
len()offset - Use truthiness instead of empty-container equality
- Use
\{\}literal instead ofdict()constructor