Skip to main content

PyPI version Code on Github Actions Status Code style: black

flake8-simplify

A flake8 plugin that helps you simplify your code.

Installation

Install with pip:

pip install flake8-simplify

Python 3.6 to 3.8 are supported.

Usage

Just call flake8 . in your package or flake your.py:

$ flake8 .
./foo/__init__.py:690:12: SIM101 Multiple isinstance-calls which can be merged into a single call for variable 'other'

Rules

Python-specific rules:

Simplifying Comparations:

  • SIM201: Use 'a != b' instead of 'not a == b' (example)
  • SIM202: Use 'a == b' instead of 'not a != b' (example)
  • SIM203: Use 'a not in b' instead of 'not (a in b)' (example)
  • SIM204: Use 'a >= b' instead of 'not (a < b)' (example)
  • SIM205: Use 'a > b' instead of 'not (a <= b)' (example)
  • SIM206: Use 'a <= b' instead of 'not (a > b)' (example)
  • SIM207: Use 'a < b' instead of 'not (a <= b)' (example)
  • SIM208: Use 'a' instead of 'not (not a)' (example)
  • SIM210: Use 'bool(a)' instead of 'True if a else False' (example)
  • SIM211: Use 'not a' instead of 'False if a else True' (example)
  • SIM212: Use 'a if a else b' instead of 'b if not a else a' (example)
  • SIM220: Use 'False' instead of 'a and not a' (example)
  • SIM221: Use 'True' instead of 'a or not a' (example)
  • SIM222: Use 'True' instead of '... or True' (example)
  • SIM223: Use 'False' instead of '... and False' (example)
  • SIM224: Reserved for SIM901 once it's stable
  • SIM300: Use 'age == 42' instead of '42 == age' (example)

Simplifying usage of dictionaries:

  • SIM401: Use 'a_dict.get(key, "default_value")' instead of an if-block (example)
  • SIM118: Use 'key in dict' instead of 'key in dict.keys()' (example)

General Code Style:

Experimental rules:

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)

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")

Thank you for pointing this one out, Aaron Gokaslan!

SIM118

# Bad
key in a_dict.keys()

# Good
key in a_dict

Thank you for pointing this one out, Aaron Gokaslan!

SIM119

Dataclasses were introduced with PEP 557 in Python 3.7. The main reason not to use dataclasses is to support legacy Python versions.

Dataclasses create a lot of the boilerplate code for you:

  • __init__
  • __eq__
  • __hash__
  • __str__
  • __repr__

A lot of projects use them:

SIM120

# Bad
class FooBar(object):
    ...

# Good
class FooBar:
    ...

Both notations are equivalent in Python 3, but the second one is shorter.

SIM201

# Bad
not a == b

# Good
a != b

SIM202

# Bad
not a != b

# Good
a == b

SIM203

# Bad
not a in b

# Good
a not in b

SIM204

# Bad
not a < b

# Good
a >= b

SIM205

# Bad
not a <= b

# Good
a > b

SIM206

# Bad
not a > b

# Good
a <= b

SIM207

# Bad
not a >= b

# Good
a < b

SIM208

# Bad
not (not a)

# Good
a

SIM210

# Bad
True if a else False

# Good
bool(a)

SIM211

# Bad
False if a else True

# Good
not a

SIM212

# Bad
b if not a else a

# Good
a if a else b

SIM220

# Bad
a and not a

# Good
False

SIM221

# Bad
a or not a

# Good
True

SIM222

# Bad
... or True

# Good
True

SIM223

# Bad
... and False

# Good
False

SIM300

# Bad; This is called a "Yoda-Condition"
42 == age

# Good
age == 42

SIM401

# Bad
if key in a_dict:
    value = a_dict[key]
else:
    value = "default_value"

# Good
thing = a_dict.get(key, "default_value")

SIM901

This rule will be renamed to SIM224 after its 6-month trial period is over. Please report any issues you encounter with this rule!

The trial period starts on 23rd of January and will end on 23rd of August 2022.

# Bad
bool(a == b)

# Good
a == b

SIM904

# Bad
a = {}
a["b"] = "c"

# Good
a = {"b": "c"}

Metadata

Release files for flake8_simplify 0.16.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for flake8_simplify 0.16.0
File Size Uploaded Provenance Actions
flake8_simplify-0.16.0.tar.gz 17.6 kB Without provenance Details for flake8_simplify-0.16.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for flake8_simplify 0.16.0
File Interpreter ABI Platform Actions
flake8_simplify-0.16.0-py3-none-any.whl Python 3 none any Details for flake8_simplify-0.16.0-py3-none-any.whl

Total release size: 34.2 kB

Release files / flake8_simplify-0.16.0.tar.gz

Download URL flake8_simplify-0.16.0.tar.gz
Size 17.6 kB
Tags Source
SHA-256 checksum
How to use checksums
c758f6b35811517d6986c3c71677fc89523f98fe58d52be6237e81d676840542
BLAKE2b-256 checksum
How to use checksums
82809962178c1c6130399eb0a61c1adfcc07402c55def53a28b1eb617d6abf47
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.7.1 importlib_metadata/4.10.1 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.7.7

Release files / flake8_simplify-0.16.0-py3-none-any.whl

Download URL flake8_simplify-0.16.0-py3-none-any.whl
Size 16.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a4e05bb21dab96bdbbea26c19ca1444cd64a521e28376488c79e37abc33b0b61
BLAKE2b-256 checksum
How to use checksums
af9ce7731701c9e4fe1cb845713ff12829d793fce935378b57605f72c625c6e0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.7.1 importlib_metadata/4.10.1 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.7.7

Security for flake8_simplify 0.16.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.16.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page