My function returns a tuple of two values, one of which is string with one of two possible values, say "a" or "b". This string is retrieved from the URL and indeed in theory can be something else - in which case I raise a Valuerror. However, it seems that mypy does not see my error, and still upset with string to Literal conversion. What is the proper way to solve that?
def _get_listing_info(txt: str) -> Tuple[int, Literal["a", "b"]]:
findInfo = re.search(r"ios-app://\d+/item/(\w+)/(\d+)", txt)
if findInfo is None:
raise ValueError(f"Failed to establish listing type from `{txt}`")
tp, listting_id = findInfo.group(1), int(findInfo.group(2))
if tp not in {"a", "b"}:
raise ValueError(tp, url)
return listting_id, tp
Mypy raises an issue with:
Expression of type "tuple[int, str]" cannot be assigned to return type "Tuple[int, > Literal['a', 'b']]" Tuple entry 2 is incorrect type Type "str" cannot be assigned to type "Literal['a', 'b']" "str" cannot be assigned to type "Literal['a']" "str" cannot be assigned to type "Literal['b']"