Skip to content

Define return type based on boolean flag #8634

Closed
@adithyabsk

Description

@adithyabsk

Situation

# scratch.py
from typing import Union

def test_func(ret_str = True) -> Union[int, str]:
    return "Hello " if ret_str else 0

if __name__ == "__main__":
    print(test_func(True)+"World!")
    print(test_func(False)+10)
$ mypy test.py

Error

scratch.py:7: error: Unsupported operand types for + ("int" and "str")
scratch.py:7: note: Left operand is of type "Union[int, str]"
scratch.py:8: error: Unsupported operand types for + ("str" and "int")
scratch.py:8: note: Left operand is of type "Union[int, str]"
Found 2 errors in 1 file (checked 1 source file)

Expectation

I, the programmer, know that I can expect a string from the functions as a result of the boolean flag. How would I go about clueing the static type checker into that as well. I know that I can use instanceof in the code that calls the function but that doesn't make much sense when one is guaranteed the return type due to the boolean flag.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions