def foo()->tuple[int, str] tuple[str, int]: if input(): return 1, "" else: return "", 1…
- User
def foo()->tuple[int, str] | tuple[str, int]: if input(): return 1, "" else: return "", 1
a, b = foo() if a == 1: reveal_type(a) # Type of "a" is "str | Literal[1]" reveal_type(b) # Type of "b" is "str | int"
how to make the types work
Assistant
This code has a type narrowing issue. When you check
a == 1, Python's type checker doesn't fully narrow the return type. Let me fix it:from typing import Union, Literal, TypeVar, overload, get_type_hints # Use overloaded function definitions for precise return types @overload def foo() -> tuple[Literal[1], str]: ... @overload def foo() -> tuple[str, int]: ... def foo() -> Union[tuple[Literal[1], str], tuple[str, int]]: if input(): return 1, "" else: return "", 1 a, b = foo() if isinstance(a, int): # Use isinstance instead of equality check reveal_type(a) # Should be Literal[1] reveal_type(b) # Should be str else: reveal_type(a) # Should be str reveal_type(b) # Should be int
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.