Skip to content

Union of different Tuples as a return value and conditionals after that #6641

Closed
@yurkobb

Description

@yurkobb
  • Are you reporting a bug, or opening a feature request?

Not exactly sure if this is a bug or a feature request, but I think this might be a valid use case.

  • Please insert below the code you are checking with mypy,

A simplified example:

from typing import Tuple, Union

def something_or_nothing() -> Union[Tuple[str, int],
                                    Tuple[None, None]]:
    # In alternative scenario, based on a network request,
    # could return (None, None)
    return ("hi", 18)

def process(string: str, integer: int):
    pass

something, number = something_or_nothing()
if something:
    # number must be int
    process(something, number)
  • What is the actual behavior/output?

test.py:16: error: Argument 2 to "process" has incompatible type "Optional[int]"; expected "int"

  • What is the behavior/output you expect?

Ideally, mypy would recognize that it should be either a tuple of (str, int) or (None, None), but it can't be (str, None).

Currently the only way to represent this code that I know of is to use cast(int, integer), however that doesn't improve the code readability and makes it more confusing.

  • What are the versions of mypy and Python you are using?

mypy 0.700

I haven't tried with git master yet.

  • What are the mypy flags you are using? (For example --strict-optional)

none

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