Skip to content

False positive unnecessary-dunder-call on __enter__ #8551

Open
@jamesbraza

Description

@jamesbraza

Bug description

Here is b.py:

"""b.py"""

# pylint: disable=missing-function-docstring

from collections.abc import Iterator
from contextlib import contextmanager

@contextmanager
def some_context_manager() -> Iterator[None]:
    yield

Here is a.py:

"""a.py"""

# pylint: disable=missing-function-docstring

from unittest.mock import MagicMock, call, patch

from .b import some_context_manager  # pylint: disable=relative-beyond-top-level

def just_enters() -> None:
    # NOTE: the pylint false positive is on the next line: unnecessary-dunder-call
    some_context_manager().__enter__()

@patch(f"{__name__}.some_context_manager")
def test_just_enters(mock_some_context_manager: MagicMock) -> None:
    all_mocks = MagicMock()
    all_mocks.attach_mock(mock_some_context_manager, "some_context_manager")

    just_enters()

    # Known pylint bug, SEE: https://github.com/pylint-dev/pylint/issues/7351
    # pylint: disable-next=unnecessary-dunder-call
    all_mocks.assert_has_calls([call.some_context_manager().__enter__()])

When there is an import of a function decorated with contextlib.contextmanager, and one just calls __enter__ (and not __exit__), pylint will report a false positive unnecessary-dunder-call.

Another comment is the message printed says: "Invoke context manager directly." How else can one invoke a context manager directly, without calling __exit__?

Configuration

No response

Command used

pylint --score=false a.py

Pylint output

************* Module a
a.py:11:4: C2801: Unnecessarily calls dunder method __enter__. Invoke context manager directly. (unnecessary-dunder-call)

Expected behavior

I expect pylint to not have this false positive.

Pylint version

pylint 2.17.2
astroid 2.15.2
Python 3.10.10 (main, Feb 19 2023, 17:57:18) [Clang 14.0.0 (clang-1400.0.29.102)]

OS / Environment

macOS Monterey version 12.6

Additional dependencies

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs decision 🔒Needs a decision before implemention or rejection

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions