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
Your Environment
I experienced a similar issue with the following code:
from typing import Optional class MyObject: def __init__(self, attribute: int) -> None: self.attribute = attribute def find_biggest_attribute(objects: list[MyObject]) -> Optional[MyObject]: return max(objects, default=None, key=lambda object: object.attribute) print(find_biggest_attribute([MyObject(42), MyObject(41)])) print(find_biggest_attribute([]))
Running mypy raises:
mypy_bug.py:10: error: Item "None" of "Optional[MyObject]" has no attribute "attribute" [union-attr] return max(objects, default=None, key=lambda object: object.attribute) ^~~~~~~~~~~~~~~~ Found 1 error in 1 file (checked 1 source file)
As per Python built-in max() documentation:
The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.
Know what:
def func() -> Optional[int]: d = {1: 2, 3: 4} x = min([1, 2], key=lambda k: d[k], default=None) return x # mypy.....................................................................Passed
This is odd
Extend special case for context-based typevar inference to typevar un…
Activity
EdwardEisenhauer commented on Feb 20, 2023
I experienced a similar issue with the following code:
Running mypy raises:
As per Python built-in max() documentation:
EugeneYushin commented on Feb 21, 2025
Know what:
This is odd
Extend special case for context-based typevar inference to typevar un…