The issue you're encountering is that Python's type system can't automatically narrow the types of a and b based on the if a == 1 check because the return types of foo() are overlapping tuples with different orders of types.
Here's how you can make the types work properly:
Solution 1: Use Type Guards
You can create a type guard function to help the type checker understand the relationship between the types:
from typing import TypeGuard, Union, Literal
def is_first_int(a: Union[int, str]) -> TypeGuard[Literal[1]]:
return a == 1
def foo() -> tuple[int, str] | tuple[str, int]:
if input():
return 1, ""
else:
return "", 1
a, b = foo()
if is_first_int(a):
reveal_type(a) # Type of "a" is "Literal[1]"
reveal_type(b) # Type of "b" is "str"
else:
reveal_type(a) # Type of "a" is "str"
reveal_type(b) # Type of "b" is "int"
Solution 2: Use a Discriminated Union
A better approach might be to use a discriminated union with a tag:
from typing import Literal, Union
class IntFirst:
def __init__(self, a: int, b: str):
self.tag = "int_first"
self.a = a
self.b = b
class StrFirst:
def __init__(self, a: str, b: int):
self.tag = "str_first"
self.a = a
self.b = b
def foo() -> Union[IntFirst, StrFirst]:
if input():
return IntFirst(1, "")
else:
return StrFirst("", 1)
result = foo()
if result.tag == "int_first":
a = result.a # Type is int
b = result.b # Type is str
else:
a = result.a # Type is str
b = result.b # Type is int
Solution 3: Use Type Narrowing with isinstance
If you're using Python 3.10+, you can use structural pattern matching:
def foo() -> tuple[int, str] | tuple[str, int]:
if input():
return 1, ""
else:
return "", 1
a, b = foo()
match a, b:
case (1, str()):
reveal_type(a) # Type is Literal[1]
reveal_type(b) # Type is str
case (str(), int()):
reveal_type(a) # Type is str
reveal_type(b) # Type is int
Best Practice Recommendation
The discriminated union approach (Solution 2) is generally the most robust and maintainable solution for this kind of problem, as it makes the types explicit and easy to work with. The type checker can then properly understand the different cases without any ambiguity.