Skip to content

Union of different-length Tuple types should agree for corresponding items #2509

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

Closed
gvanrossum opened this issue Nov 29, 2016 · 2 comments · Fixed by #6475
Closed

Union of different-length Tuple types should agree for corresponding items #2509

gvanrossum opened this issue Nov 29, 2016 · 2 comments · Fixed by #6475
Labels

Comments

@gvanrossum
Copy link
Member

See python/typeshed#721 (comment). The issue is that after

T = Union[Tuple[int, int], Tuple[int, int, str]]
def f() -> T: pass
a = f()
reveal_type(a[0])
reveal_type(a[2])

the item types are considered to be Any. A better approach would be to understand that a[0] is always an int while a[2] is invalid without some check (however we can't do isinstance() checks on tuple lengths so that's problematic).

@JukkaL
Copy link
Collaborator

JukkaL commented Nov 30, 2016

We could support len(x) checks for tuple unions: #1178

@rwbarton
Copy link
Contributor

I'm a little surprised this doesn't go through the path for a method call on a union. For example, this works fine:

class A:
    def f(self) -> int: pass

class B:
    def f(self) -> int: pass

U = Union[A, B]
def g() -> U: pass

b = g()
reveal_type(b.f())   # Revealed type is 'builtins.int'

It might just take some code reorganization (translate the IndexExpr into a __getitem__ method call, then handle __getitem__ on tuples in check_op).

ilevkivskyi added a commit that referenced this issue Feb 26, 2019
Fixes #4286
Fixes #2509

The fix is straightforward, map the indexing through union types. I decided to use the existing error message mentioning the full type. IMO `Value of type "Union[int, List[int]]" is not indexable` is better than `Value of type "int" is not idexable`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants