I have a function, it’s return type is tuple[bool, set[int] | str]
. If the 0th item is True
, then the 1st item is the result set[int]
, else the 1st item is a str showing the reason why it failed. It’s like this
def callee(para_a: int) -> tuple[bool, set[int] | str]:
result = set([1, 2, 3])
if (something wrong):
return False, "something wrong"
return True, result
Now I call this function from other functions
from fastapi import FastAPI
from fastapi.responses import JSONResponse
api = FastAPI()
def kernel(para: set[int]):
return [i for i in para]
@api.post("/test")
def caller(para_a: int):
res = callee(para_a)
if res[0] is True:
return {"result": kernel(res[1])}
return JSONResponse(status_code=500, content={"fail_msg": res[1]}
Never mind fastapi
, that’s just because I want to say it is sometimes useful in web.
Now mypy
would blame that error: Argument 1 to "kernel" has incompatible type "set[int] | str"; expected "set[int]" [arg-type]
, so I’d like to make mypy
know that if the 0th item is True
, then the 1st item is the result set[int]
, else the 1st item is a str. I thought about overload
, so I wrote
from typing import overload, Literal
@overload
def callee(para_a: int) -> tuple[Literal[True], set[int]]:
...
@overload
def callee(para_a: int) -> tuple[Literal[False], str]:
...
Then mypy
blames that Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader
.
What I’d like to know is whether there is a good way to solve my problem? As I can’t use overload
in this situation, what should I use to make mypy
know res[1]
is just a set[int]
but never would be a str
if res[0] is True
?