Creating generic type argument bound to Exception in Python

46 views Asked by At

I'm trying to create a generic type for an exception, to be sent to a method. This is what I have, currently:

E = TypeVar("E", bound=Exception)

I would annotate the argument like this:

def parse_td_value(
        self,
        data: Tag,
        name: str,
        parser: Callable[[str], T],
        exc_type: Type[E] = ValueError,
    ) -> T:
    ...

However, when I do this mypy gives me an error:

Incompatible default for argument "exc_type" (default has type "Type[ValueError]", argument has type "Type[E]")

I have attempted to resolve this issue using overloads, as described here, but to no avail. I'm assuming this has something to do with the fact that the bound condition of E is different than the type of the default argument for the method, ValueError.

To my mind, this doesn't make sense because ValueError should be a E. So, why is mypy disagreeing here and how can I make this annotation work?

0

There are 0 answers