Skip to content

No type inference for indexed expressions #3006

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
pkch opened this issue Mar 15, 2017 · 5 comments
Closed

No type inference for indexed expressions #3006

pkch opened this issue Mar 15, 2017 · 5 comments

Comments

@pkch
Copy link
Contributor

pkch commented Mar 15, 2017

I'm sure there's a limit to how far type inference can go, and it's reasonable that it doesn't evaluate the result of applying an index:

from typing import *

def f(x: Dict[str, Union[int, str]], k: str) -> None:
    if isinstance(x[k], int):
        x[k] + 1  # type error: Unsupported operand types for + ("Union[int, str]" and "int")

But maybe an example in the docs would be helpful? A suggestion could be given to either rewrite it like this:

def f(x: Dict[str, Union[int, str]], k: str) -> None:
    v = x[k]
    # note: both x[k] (in the if expression and in the body) must be replaced with a simple variable
    if isinstance(v, int):
        v + 1  # no type error

or to just mark it as # type: ignore.

@refi64
Copy link
Contributor

refi64 commented Mar 15, 2017

I'm not sure how things are here, but I know over in Crystal (a type-inferred language), it's the same way, and it's entirely intentional; in theory, in a multi-threaded program, x[k] could change between the two points.

@gvanrossum
Copy link
Member

gvanrossum commented Mar 15, 2017 via email

@pkch
Copy link
Contributor Author

pkch commented Mar 15, 2017

@kirbyfan64:I think in mypy case, this is only because inference complexity grows really fast once you move away from simple variables. It's not because of thread safety: after all, it works fine if you replace x[k] with a global variable, which can be changed from a different thread.

@gvanrossum
Copy link
Member

gvanrossum commented Mar 15, 2017 via email

@miedzinski
Copy link
Contributor

Duplicate of #2458.

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

4 participants