Skip to content

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

@p-adema

Description

@p-adema

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",
]

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions