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

enumerate causes incompatible type mypy error #11934

Closed
jroberts07 opened this issue Jan 7, 2022 · 4 comments
Closed

enumerate causes incompatible type mypy error #11934

jroberts07 opened this issue Jan 7, 2022 · 4 comments
Labels
bug mypy got something wrong topic-join-v-union Using join vs. using unions

Comments

@jroberts07
Copy link

Bug Report

When using the enumerate function mypy seems to generalise the output to object instead of respecting the type of the input

To Reproduce

from typing import Union


def process(actions: Union[list[str], list[int]]) -> None:
    for pos, action in enumerate(actions):
        act(action)


def act(action: Union[str, int]) -> None:
    print(action)

Expected Behavior

Mypy raises no errors

Actual Behavior

Mypy raises the following error: Argument 1 to "act" has incompatible type "object"; expected "Union[str, int]"

Its worth noting that the same code without using enumerate does not raise this error:

from typing import Union


def process(actions: Union[list[str], list[int]]) -> None:
    for action in actions:
        act(action)


def act(action: Union[str, int]) -> None:
    print(action)

Your Environment

  • Mypy version used: 0.921
  • Python version used: 0.9
@jroberts07 jroberts07 added the bug mypy got something wrong label Jan 7, 2022
@sobolevn
Copy link
Member

sobolevn commented Jan 9, 2022

You can try this (if you are using python>=3.9):

from typing import Union

def process(actions: Union[list[str], list[int]]) -> None:
    for pos, action in enumerate[str | int](actions):
        act(action)

def act(action: Union[str, int]) -> None:
    print(action)

But, I agree that automatically infering str | int here can be a good feature. But, it is really hard to do 🙂

@erictraut
Copy link

This is yet another case where mypy's choice to use join rather than union causes problems. Pyright uses only unions, never joins, so it produces the expected result in this case.

Has there been any serious discussion of changing mypy's behavior to use unions instead of joins? I can't think of any case where joins are preferable, and there are many cases where unions are better because they retain more detailed type information.

@sobolevn
Copy link
Member

sobolevn commented Jan 9, 2022

CC @JukkaL

@AlexWaygood
Copy link
Member

Closing as a duplicate of #8586

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-join-v-union Using join vs. using unions
Projects
None yet
Development

No branches or pull requests

5 participants