flake8-simplify icon indicating copy to clipboard operation
flake8-simplify copied to clipboard

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

Open MaxG87 opened this issue 1 year ago • 0 comments

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.

MaxG87 avatar Mar 24 '23 11:03 MaxG87