Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type not narrowed with keyboard in and list #13315

Closed
edaqa-uncountable opened this issue Aug 3, 2022 · 3 comments
Closed

Type not narrowed with keyboard in and list #13315

edaqa-uncountable opened this issue Aug 3, 2022 · 3 comments

Comments

@edaqa-uncountable
Copy link

In the following code I was expecting the type of item to be narrowed inside the conditional. Instead I get an error message about an incompatible return type. The code following the conditional shows that two separated checks do narrow the type.

from typing import TypeVar

VariantResult = dict | None
MISSING: VariantResult = {}
T = TypeVar("T")


def get_something(key: int, default: T) -> int | T:
    """ Trying to mimic the type of the "dict.get" method """
    return default


def check() -> VariantResult:
    item = get_something(123, MISSING)

    if item in [None, MISSING]:
        return item  # Error here*

    if item == None:
        return None
    if item == MISSING:
        return MISSING

    return {}

*Error: mypy :return-value Incompatible return value type (got "Union[int, Dict[Any, Any], None]", expected "Optional[Dict[Any, Any]]")

The error is unexpected since item can only be one of None or INVALID_SPEC, which are both valid for the result of VariantResult. If they weren't, then the following returns would also fail, but they do not.

@edaqa-uncountable
Copy link
Author

Additionally, the code following the if ... in does not narrow the type either. While there is no way to exlclude the MISSING type, the None type should be excluded. But the item is still marked as | None after the if statement, this fails:

...
def require_int(value: int) -> None:
   pass

require_int(item)  # Type error, may not be None

@A5rocks
Copy link
Collaborator

A5rocks commented Aug 3, 2022

Yes, this is a good idea.

Duplicate of #10977 though

@AlexWaygood
Copy link
Member

Duplicate of #10977 though

Indeed

@AlexWaygood AlexWaygood closed this as not planned Won't fix, can't repro, duplicate, stale Aug 3, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants