Skip to content

False "Invalid index type" for min derived from return type #14664

Closed
@ods

Description

@ods

Bug Report

Mypy gives [index] error for key when calling min from function that is declared to return Optional.

To Reproduce

This pretty valid

def func() -> Optional[int]:
    d = {1: 2, 3: 4}
    return min([1, 2], key=lambda k: d[k], default=None)

returns error

Invalid index type "Optional[int]" for "Dict[int, int]"; expected type "int"  [index]

Changing default to 0 doesn't fix the problem, but changing return type of func to int does. So, the following works fine:

def func() -> int:
    d = {1: 2, 3: 4}
    return min([1, 2], key=lambda k: d[k], default=0)

Expected Behavior

No error for the first example, as default is never compared to objects in collection.

Actual Behavior

Invalid index type "Optional[int]" for "Dict[int, int]"; expected type "int"  [index]

Your Environment

  • Mypy version used: 1.0.0
  • Mypy command-line flags: no
  • Mypy configuration options from mypy.ini (and other config files): no
  • Python version used: 3.10

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-contextType context / bidirectional inference

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions