python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.56k stars 2.84k forks source link

(inter-)dependent variable types #7422

Open Naddiseo opened 5 years ago

Naddiseo commented 5 years ago

I'm not sure how to entitle this, but I think it's a dependent type.

def x() -> Union[Tuple[int, int], Tuple[str, str]]: ...

a, b = x()

if isinstance(b, int): reveal_type(a) # can only be int but is reported as Union[int, str]


* What is the actual behavior/output?
   **type is reported as `Union[int, str]`**
* What is the behavior/output you expect?
   **type of `a` can only be `int` given the return type signature**
* What are the versions of mypy and Python you are using? **7.20**
  Do you see the same issue after installing mypy from Git master? **yes**
* What are the mypy flags you are using? (For example --strict-optional)
  **python_version=3.7**

I'm assuming this would be a difficult change, but I figured I'd open an issue for the sake of having a record, and in the meantime I can use `assert isinstance()`
JukkaL commented 5 years ago

Yeah, this comes up every once in a while. There might be an existing issue but I couldn't immediately find it. You are correct that this would be difficult to support, especially considering that this happens pretty rarely.

ilevkivskyi commented 5 years ago

Naively this may look like a duplicate of https://github.com/python/mypy/issues/6478, but I think this is different (and harder). In that issue we would essentially check the same expression multiple times (for every item in the relevant union). Here however we need to type-check the rest of the function multiple times.

See also https://github.com/python/mypy/issues/5579 for yet another aspect. Sometimes binder can infer restrictions for the "parent" expression.