Skip to content

AnyStr does not accept str|bytes in single-argument functions of StdLib #20340

Closed as duplicate

Description

@nolar

MyPy cannot unfold AnyStr with a single-argument StdLib function (re.escape). The typeshed defines the function as:

def escape(pattern: AnyStr) -> AnyStr: ...

AnyStr = TypeVar("AnyStr", str, bytes)

There is nothing wrong with the definition, all is good in typeshed. My suspicion is that it is something wrong with type inference.

I see that AnyStr is deprecated, but in Python 3.18, so roughly in 4 years — a long time to wait. Some clarity on how this is expected to be used, would be nice.

My code supports both strings and bytes at runtime, they both behave similarly, never mix-up together. Now, I have to duplicate the code fragments first for if isinstance(val, str):…, then else:… for bytes — while there is no difference in the code pieces.

To Reproduce

import re
val: str | bytes = 'hello'
re.escape(val)

Expected Behavior

It accepts either str ot bytes, and returns the respective type back.

Actual Behavior

_repro_pattern.py:3: error: Value of type variable "AnyStr" of "escape" cannot be "str | bytes"  [type-var]

Your Environment

MyPy 1.19.0.
Python 3.14.0 (the same in others).

mypy --strict _repro_pattern.py

Activity

  1. added
    bugmypy got something wrong
    on Dec 1, 2025
  2. ilevkivskyi commented on Dec 1, 2025

    @ilevkivskyi
    Member

    This is a duplicate of #1533

  3. nolar commented on Dec 1, 2025

    @nolar
    Author

    Ah, I see now. So, it is a generic case with a union producing unresolved union back (instead if a type-var), so even if re.escape() is made to work, it would fail further down the call chain with re.compile(), re.match() & co, as it cannot mix byte patterns with str values, and vice versa. @ilevkivskyi, thanks for the reference! I will try to rewrite the code to be more deterministic.

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