Skip to content

new rule - function decorated with @contextlib.contextmanager that does not wrap its yield statement in a try/finally block #15629

Description

@DetachHead

contextlib.contextmanager is dangerous because its __exit__ won't get run if an exception is raised, which is rarely what you want:

from contextlib import contextmanager

@contextmanager
def foo():
    print('starting')
    yield
    print('ending')

with foo():
    raise Exception

it would be nice if ruff had a rule to enforce try/finally on these types of context managers:

from contextlib import contextmanager

@contextmanager
def foo():
    print('starting')
    try:
        yield
    finally:
        print('ending')

Metadata

Metadata

Labels

acceptedReady for implementationruleImplementing or modifying a lint rule

Type

No type

Fields

No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions