FP python:S1481 — false positive when using walrus operator in any() with generator expression


  • Operating system: macOS 14.5
  • SonarLint plugin version:
  • Programming language you’re coding in: python
  • Is connected mode used: no
    • Connected to SonarCloud or SonarQube (and which version):

Description of the problem:

SonarLint incorrectly flags the assignment target of the walrus operator := as unused when used in a generator expression inside a call to any() or all().

Presumably the special case described in PEP 572 — Scope of the target is not implemented.

In the snippet below, taken from the text of PEP 572, comment is flagged as being unused with a reference to python:S1481.

lines = ['# comment line', 'normal line']

if any((comment := line).startswith('#') for line in lines):
    print("First comment:", comment)
    print("There are no comments")

Expected behaviour:

SonarLint correctly calculates the scope of the variable and recognises that it is used.

Hello @peter.aisher,

Thank you for raising this issue!

We are incorrectly raising an issue here, for the reason you mentioned exactly. I have created this ticket to keep track of our progress.

Thank you again for the detailed research on the issue!


Hi @david.kunzmann,

Thanks for opening the ticket.

I’d be happy to contribute a fix if that’s helpful and you’re open to contributions from the community?


Hi @peter.aisher,

Sure, we welcome contributions from the community! Do not hesitate to tackle the ticket. I would also suggest taking a look at our conventions before submitting a PR.

Kind regards,