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

SIM105: Replace try-except-pass blocks with the contextlib.suppress context manager #3448

Closed
wants to merge 2 commits into from

Conversation

seisman
Copy link
Member

@seisman seisman commented Sep 23, 2024

Description of proposed changes

Fix ruff SIM105 violations.

What it does

Checks for try-except-pass blocks that can be replaced with the contextlib.suppress context manager.

Why is this bad?

Using contextlib.suppress is more concise and directly communicates the intent of the code: to suppress a given exception.

Note that contextlib.suppress is slower than using try-except-pass directly. For performance-critical code, consider retaining the try-except-pass pattern.

Not sure why ruff doesn't catch these violations, but the codes look cleaner with contextlib.suppress.

@seisman seisman added maintenance Boring but important stuff for the core devs skip-changelog Skip adding Pull Request to changelog labels Sep 23, 2024
@seisman seisman added this to the 0.14.0 milestone Sep 23, 2024
@seisman seisman added the needs review This PR has higher priority and needs review. label Sep 23, 2024
@weiji14
Copy link
Member

weiji14 commented Sep 24, 2024

Not sure why ruff doesn't catch these violations, but the codes look cleaner with contextlib.suppress.

Looks the the SIM105 rule won't work with >1 line under the try: block, see astral-sh/ruff#8593. The idea I think is that if the 1st line fails, it's not so clear that the 2nd line wouldn't run if there is not an except: below it, see also rationale at astral-sh/ruff#1947.

@seisman
Copy link
Member Author

seisman commented Sep 24, 2024

The idea I think is that if the 1st line fails, it's not so clear that the 2nd line wouldn't run if there is not an except: below it, see also rationale at astral-sh/ruff#1947.

Makes sense. Closing the PR.

@seisman seisman closed this Sep 24, 2024
@seisman seisman deleted the SIM105 branch September 24, 2024 02:12
@seisman seisman removed the needs review This PR has higher priority and needs review. label Sep 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
maintenance Boring but important stuff for the core devs skip-changelog Skip adding Pull Request to changelog
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants