[python:S5886] False-positive when using contextlib.AbstractContextManager


Language: Python
Rule: python:S5886
Tool: SonarLint in PyCharm

  • SontarLint
  • PyCharm 2023.1.1
  • Python 3.10

Why I believe it’s a false-positive:

When I originally made myself this context manager, I tried to research how it should be hinted.
The internet came up with 3 ideas:

I’m using the last one because it the best conveys what I’m doing - a context manager, duh. Being on 3.10 I use the contextlib.AbstractContextManager but typing.ContextManager also gets marked.

This code predates my use of SonarLint, I just had to do something in that file and noticed the big yellow marks on my code - and that’s how I ended up here, actually reporting it.

Simple example:

import contextlib
def test() -> contextlib.AbstractContextManager[str]:
    yield "this is an example"

Hello @hazelnutfox,

Thank you for reporting this!

To be transparent, the previous false positive you refer to in your thread (with Iterator) led to 2 tickets being created and one of them still has not been fixed (though we do have it in our radar).

I think the one you’re encountering here is somehow related, in the sense that the rule is a bit too strict about what type hint should be used, and has a tendency to over-report. In this case, the analyzer is able to resolve the semantics properly, but contextlib.AbstractContextManager is somehow not accepted ad a valid type hint.

I created the following ticket for this.