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

SIM115 false positive when using open() inside of a custom context manager __enter__ #11567

Closed
p-adema opened this issue May 27, 2024 · 1 comment · Fixed by #11575
Closed
Assignees
Labels
bug Something isn't working

Comments

@p-adema
Copy link

p-adema commented May 27, 2024

Keywords: SIM115, __enter__, context manager

When writing your own context manager, which internally uses another context manager (like open), SIM115 suggests using a with block when this is not possible (as the goal is to open the resource in __enter__, and keep it open).

I would expect/hope the behaviour be to automatically suppress this check within an __enter__ block, as (in my experience) it is often the case that these blocks delegate some of the handling to e.g. open()

Code snippet:

class MyFile:
    def __init__(self, filename: str):
        self.filename = filename

    def __enter__(self):
        self.file = open(self.filename) # SIM115 : Use context handler for opening files

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.file.close()

Command invoked:

ruff check context.py --isolated --select SIM115
context.py:7:21: SIM115 Use context handler for opening files
Found 1 error.

Ruff version: 0.4.5
Configuration:

[lint]
select = [
    "SIM",
]
@charliermarsh charliermarsh added the bug Something isn't working label May 27, 2024
@charliermarsh
Copy link
Member

Seems reasonable to me...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants