Skip to content

Mypy is still too eager about outer context #5874

Closed

Description

@ilevkivskyi

Consider this example:

T = TypeVar('T')
S = TypeVar('S')

def add(x: List[T], y: List[S]) -> List[Union[T, S]]: ...

a: List[int]
b: List[str]

e: List[Union[int, str]] = add(a, b)

It fails on the last line with the following (I skip invariance notes):

error: Argument 1 to "add" has incompatible type "List[int]"; expected "List[Union[int, str]]"
error: Argument 2 to "add" has incompatible type "List[str]"; expected "List[Union[int, str]]"

If I remove the annotation for e, everything works fine.

When previously working on the external context issues, I found that I don't like how constrains for unions against unions are inferred (not that they are wrong, just counterintuitive). For example, Union[T, S] <: Union[str, int] infers T < : Union[str, int] and S <: Union[str, int], which is technically fine, but leads to errors like above.

This blocks #5873

Activity

  1. added
    bug
    false-positive
    on Nov 8, 2018
  2. changed the title [-]Mypy is still to eager about outer context[/-] [+]Mypy is still too eager about outer context[/+] on Nov 8, 2018
  3. ilevkivskyi commented on Nov 8, 2018

    @ilevkivskyi
    MemberAuthor

    But again, a permanent solution for this kind of issues is to put all constraints into the same bin.

  4. ilevkivskyi commented on Nov 8, 2018

    @ilevkivskyi
    MemberAuthor

    Actually this is not specific to unions against unions, unions against instance also fails:

    e: Sequence[object] = add(a, b)

    with:

    error: Argument 1 to "add" has incompatible type "List[int]"; expected "List[object]"
    error: Argument 2 to "add" has incompatible type "List[str]"; expected "List[object]"
    

    because Union[T, S] <: object infers T <: object and S <: object.

  5. JukkaL commented on Nov 29, 2018

    @JukkaL
    Collaborator

    Solving both return type context and argument constraints in one go seems to be the only somewhat promising way to solve the issue that I can think of. This would be a big change however, and it could result in other difficulties.

    My proposal is to revert the change to the signature of list.__add__ in typeshed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugfalse-positivepriority-1-normaltopic-type-variablestopic-union-types

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions