Skip to content

re.match(), re.search() and re.fullmatch() cannot be used with AnyStr #9591

Description

@agateau-gg

Given this test file:

fromtypingimportAnyStrfromreimportMatch, Patterndefcheck_re_search(pattern: Pattern[AnyStr], string: AnyStr) ->Match[AnyStr]:
match=pattern.search(string)
ifmatchisNone:
raiseValueError(f"'{string!r}' does not match {pattern!r}")
returnmatch

pyright reports the following error:

No configuration file found.
No pyproject.toml file found.
stubPath /home/agateau/tmp/typings is not a valid directory.
Assuming Python platform Linux
Searching for source files
Found 1 source file
pyright 1.1.291
/home/agateau/tmp/crs.py
/home/agateau/tmp/crs.py:6:21 - error: Could not bind method "search" because "Pattern[AnyStr@check_re_search]" is not assignable to parameter "self"
"Pattern[AnyStr@check_re_search]" is incompatible with "Pattern[str]"
TypeVar "AnyStr@Pattern" is invariant
Type "AnyStr@check_re_search" cannot be assigned to type "str" (reportGeneralTypeIssues)
/home/agateau/tmp/crs.py:6:21 - error: Could not bind method "search" because "Pattern[AnyStr@check_re_search]" is not assignable to parameter "self"
"Pattern[AnyStr@check_re_search]" is incompatible with "Pattern[bytes]"
TypeVar "AnyStr@Pattern" is invariant
Type "AnyStr@check_re_search" cannot be assigned to type "bytes" (reportGeneralTypeIssues)

The same code works fine if one replaces all AnyStr with either str or bytes.

I originally reported this on pyright issue tracker (microsoft/pyright#4534) but it seems the issue is actually here (see microsoft/pyright#4534 (comment))

Quoting erictraut comment:

The fix for this would require an additional overload within the typeshed stubs. Something like this:

@overloaddefsearch(self, string: AnyStr|ReadableBuffer, pos: int= ..., endpos: int= ...) ->Match[AnyStr] |None: ...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions