flake8-simplify
flake8-simplify copied to clipboard
[New Rule] Suggest `exist_ok` for `Path.mkdir` and `os.makedirs`
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
.