MartinThoma / flake8-simplify

❄ A flake8 plugin that helps you to simplify code
MIT License
186 stars 19 forks source link

[New Rule] Suggest `exist_ok` for `Path.mkdir` and `os.makedirs` #172

Open MaxG87 opened 1 year ago

MaxG87 commented 1 year ago

Explanation

The methods Path.mkdir and os.makedirs will fail if the target directory already exists. One approach is use a try-except block to handle that issue gracefully. While this is caught by with rule SIM105, the proposed solution is suboptimal, as it requires an additional import, two lines and some nesting.

Example

# Bad, because very verbose and cumbersome
try:
    os.makedirs("some-directory")
except OSError:
    pass

# Bad, because still hiding the intent
import contextlib
with contextlib.suppress(OSError):
    os.makedirs("some-directory")

# Good
os.makedirs("some-directory", exist_ok=True)

All the same applies to p.mkdir if p is a pathlib.Path.