Skip to content

False positive involving re.sub and + operator introduced in mypy 0.960 #12961

Closed as not planned
@DMRobertson

Description

@DMRobertson

Bug Report

Consider the following snippet. (This is a minified example of the problem detected in matrix-org/synapse#12996.)

import re

"#" + re.sub(
    "PATTERN",
    lambda match: match.group(0) + "ANOTHER_STRING",
    "HAYSTACK",
)

Mypy 0.950 is happy with this, but mypy 0.960 is not.

main.py:5: error: Unsupported operand types for + ("bytes" and "str")

AFAICS this is a legitimate usage of re.sub, consistent with the stubs defined in typeshed.

Additional

Strangely, removing either of the addition operators and the corresponding string literal causes mypy 0.960 to accept the snippet. That is, applying this change

- "#" + re.sub(
+ re.sub(

is accepted, and applying this change

-    lambda match: match.group(0) + "ANOTHER_STRING",
+    lambda match: match.group(0),

to the vanilla snippet above is also accepted.

I'm not sure how to get mypy to reveal the type of an expression in a lambda body, but I'd guess that in the error cases it deduces match: Match[bytes] rather than match: Match[str]?

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions