Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
MaxG87 opened this issue Mar 24, 2023 · 0 comments
Open

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

MaxG87 opened this issue Mar 24, 2023 · 0 comments
Assignees
Labels
enhancement New feature or request

Comments

@MaxG87
Copy link

MaxG87 commented Mar 24, 2023

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 MaxG87 added the enhancement New feature or request label Mar 24, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants