How to pass a value of type `Union[bytes, str]` to function taking `AnyStr`

Viewed 489

Suppose I have a couple of functions:

from typing import Union, AnyStr
def f(x: Union[bytes, str]):
  return g(x)
def g(x: AnyStr):
  return x

Running mypy on this causes an error

:3: error: Value of type variable "AnyStr" of "g" cannot be "Union[bytes, str]"

This is fixable by doing the following:

from typing import Union, AnyStr
def f(x: Union[bytes, str]):
        if isinstance(x, bytes):
                g(x)
        elif isinstance(x, str):
                g(x)
def g(x: AnyStr):
        return x

Surely a type which is either bytes or str (a Union[bytes, str] must either be bytes or str, not both) can be passed to a function taking AnyStr?

Why isn't this the case?

0 Answers
Related