Getting rules right for every possible case is hard. I don't want to disturb
peoples workflows. For this reason, flake8-simplify introduces new rules with
the SIM9 prefix. Every new rule will start with SIM9 and stay there for at
least 6 months. In this time people can give feedback. Once the rule is stable,
the code will change to another number.
Current experimental rules:
SIM901: Use comparisons directly instead of wrapping them in a bool(...) call (example)
SIM904: Assign values to dictionary directly at initialization (example)
SIM905: Split string directly if only constants are used (example)
SIM911: Avoid using zip(dict.keys(), dict.values()) (example)
Disabling Rules
You might have good reasons to
ignore some flake8 rules.
To do that, use the standard Flake8 configuration. For example, within the setup.cfg file:
[flake8]
ignore = SIM106, SIM113, SIM119, SIM9
Examples
SIM101
# Bad
isinstance(a, int) or isinstance(a, float)
# Good
isinstance(a, (int, float))
SIM102
# Bad
if a:
if b:
c
# Good
if a and b:
c
SIM105
# Bad
try:
foo()
except ValueError:
pass
# Good
from contextlib import suppress
with suppress(ValueError):
foo()
Please note that contextlib.suppress is roughly 3x slower than try/except
(source).
SIM107
# Bad: This example returns 3!
def foo():
try:
1 / 0
return "1"
except:
return "2"
finally:
return "3"
# Good
def foo():
return_value = None
try:
1 / 0
return_value = "1"
except:
return_value = "2"
finally:
return_value = "3" # you might also want to check if "except" happened
return return_value
SIM108
# Bad
if a:
b = c
else:
b = d
# Good
b = c if a else d
SIM109
# Bad
if a == b or a == c:
d
# Good
if a in (b, c):
d
SIM110
# Bad
for x in iterable:
if check(x):
return True
return False
# Good
return any(check(x) for x in iterable)
SIM111
# Bad
for x in iterable:
if check(x):
return False
return True
# Good
return all(not check(x) for x in iterable)
SIM112
# Bad
os.environ["foo"]
os.environ.get("bar")
# Good
os.environ["FOO"]
os.environ.get("BAR")
SIM113
Using enumerate in simple cases like the loops below is a tiny bit easier to read as the reader does not have to figure out where / when the loop variable is incremented (or if it is incremented in multiple places).
# Bad
idx = 0
for el in iterable:
...
idx += 1
# Good
for idx, el in enumerate(iterable):
...
SIM114
# Bad
if a:
b
elif c:
b
# Good
if a or c:
b
SIM115
# Bad
f = open(...)
... # (do something with f)
f.close()
# Good
with open(...) as f:
... # (do something with f)
SIM116
# Bad
if a == "foo":
return "bar"
elif a == "bar":
return "baz"
elif a == "boo":
return "ooh"
else:
return 42
# Good
mapping = {"foo": "bar", "bar": "baz", "boo": "ooh"}
return mapping.get(a, 42)
SIM117
# Bad
with A() as a:
with B() as b:
print("hello")
# Good
with A() as a, B() as b:
print("hello")
pyproject-flake8Pythie’s Index: 18pyproject-flake8 (`pflake8`), a monkey patching wrapper to connect flake8 with pyproject.toml configuration310.1K downloads/mo