You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
AnyStr does not accept str|bytes in single-argument functions of StdLib #20340
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
importreval: 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]
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.
Activity
ilevkivskyi commentedon Dec 1, 2025
This is a duplicate of #1533
nolar commentedon Dec 1, 2025
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 withre.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.