Skip to content

Mypy incorrectly gives an error for a ternary return statement #15368

Closed

Description

@johndoknjas

Bug Report

Hi, I was using mypy and I think I've noticed a bug. For a function that returns either List[str] or List[List[str]], mypy gives an error if the return type is decided as a ternary. However, if the return type is decided with an 'if-else' instead, there are no problems. I also tested a similar function, except where the return type is either a float or str. In that case, mypy had no problems with the ternary usage.

To Reproduce

from typing import Union, List

def get_str_float(b: bool) -> Union[str, float]:
    return 8 if b else '8' # mypy correctly gives no error here

def get_list(b: bool) -> Union[List[str], List[List[str]]]:
    return ['a'] if b else [['a']] # mypy incorrectly gives an error
    """
    Mypy gives no error if I replace the above line with the following:
    if b:
        return ['a']
    else:
        return [['a']]
    """

def main():
    print(get_list(True))
    print(get_str_float(True))

if __name__ == "__main__":
    main()

Expected Behavior

No errors

Actual Behavior

main.py:7: error: List item 0 has incompatible type "List[str]"; expected "str" [list-item]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 1.3.0 (compiled: yes)
  • Mypy command-line flags: none - just ran mypy main.py
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.11.0
  • OS: Windows 11

Activity

  1. added a commit that references this issue on Jun 13, 2025
    2ba79cb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-contextType context / bidirectional inference

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions