Skip to content

Bug with match.group().count in loop on v1.15.0 #18738

Open

Description

@kmurphy4

Bug Report

On v1.15.0, with mypy --warn-unreachable ... successfully finds no errors with

import re
re.sub("x", lambda m: m.group().count("x") * "x", "x")

but reports an error with

import re
for _ in re.findall("x", "x"):
    re.sub("x", lambda m: m.group().count("x") * "x", "x")  # E: Argument 1 to "count" of "bytes" has incompatible type "str"; expected "Buffer | SupportsIndex"  [arg-type]

for reference, both examples pass with v1.14.1 and with v1.15.0 without --warn-unreachable.

Activity

  1. changed the title [-]Crash with `match.group().count` in loop on v1.15.0[/-] [+]Bug with `match.group().count` in loop on v1.15.0[/+] on Feb 25, 2025
  2. sterliakov commented on Apr 11, 2025

    @sterliakov
    Collaborator

    Minimal repro to avoid re dependency, playground:

    from typing import overload, Any, AnyStr, Callable, Generic
    
    def takes_str(s: str) -> str:
        return s
    
    class Match(Generic[AnyStr]):
        def group(self, group: int, /) -> AnyStr: ...
        
    @overload
    def sub(
        pattern: str, 
        repl: Callable[[Match[str]], str]
    ) -> str: ...
    @overload
    def sub(
        pattern: bytes,
        repl: Callable[[Match[bytes]], bytes]
    ) -> bytes: ...
    
    text: str
    while True:
        text = sub("", lambda m: takes_str(m.group(1)))  # E: Argument 1 to "takes_str" has incompatible type "bytes"; expected "str"  [arg-type]
  3. sterliakov commented on Apr 11, 2025

    @sterliakov
    Collaborator

    Bisects to #18433, but only exposed by it - accepting this loop for the second time results in this error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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