pylint icon indicating copy to clipboard operation
pylint copied to clipboard

False Positive on contextmanager-generator-missing-cleanup / W0135 When Using With Expression in the ContextManager

Open ancantus opened this issue 1 year ago • 0 comments

Bug description

The contextmanager-generator-missing-cleanup warning triggers a false positive (by my understanding of the warning) when a yield expression is fully cleaned up by a surrounding with statement (or multiple with statements).

Below is a simplified example of the issue:

import contextlib


@contextlib.contextmanager
def cm():
    with open("/tmp/test", "wb+") as contextvar:
        yield contextvar.fileno()


def genfunc_with_cm():  # [contextmanager-generator-missing-cleanup]
    with cm() as context:
        yield context * 2

The warning can be silenced with the guidance from https://pylint.readthedocs.io/en/latest/user_guide/messages/warning/contextmanager-generator-missing-cleanup.html . But by my understanding this is an unnecessary warning in this case. The with statement in cm() does the 'right thing' when yield throws GeneratorExit and closes the file.

Configuration

No response

Command used

pylint ./test.py

Pylint output

************* Module test
W  test.py:10: The context used in function 'genfunc_with_cm' will not be exited. (contextmanager-generator-missing-cleanup | W0135)

Expected behavior

I would expect the contextmanager-generator-missing-cleanup to only warn when there is extra cleanup required in a contextmanager outside of with statements.

I think you see the intention of these cases being supported in the good_cm_yield_none() example in https://pylint.readthedocs.io/en/latest/user_guide/messages/warning/contextmanager-generator-missing-cleanup.html

If there's nothing to clean up: the warning should not be generated.

Pylint version

pylint 3.2.0
astroid 3.2.0
Python 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0]

OS / Environment

Ubuntu 22.04 LTS

Additional dependencies

No response

ancantus avatar May 15 '24 01:05 ancantus