Closed
Description
Bug Report
When using key
function in min
builtin function, default None value and returning it from a function which has an Optional
type, mypy reports a problem where I believe there is none.
To Reproduce
from dataclasses import dataclass
from typing import List
@dataclass
class X:
x: int
def get_min(vals: List[X]) -> X | None:
return min(vals, key = lambda tsync: tsync.x, default=None)
result = get_min([X(1), X(2), X(3)])
Expected Behavior
No errors reported.
Actual Behavior
$ mypy b.py --pretty
b.py:11: error: Item "None" of "X | None" has no attribute "x" [union-attr]
return min(vals, key = lambda tsync: tsync.x, default=None)
^~~~~~~
Found 1 error in 1 file (checked 1 source file)
The error goes away if I remove the default=None
or when the min
is not in a function with X | None
return type:
from dataclasses import dataclass
from typing import List
@dataclass
class X:
x: int
def get_min_1(vals: List[X]) -> X | None:
return min(vals, key = lambda tsync: tsync.x, default=None)
def get_min_2(vals: List[X]) -> X | None:
return min(vals, key = lambda tsync: tsync.x) # <- this is fine
vals = [X(1), X(2), X(3)]
result1 = get_min_1(vals)
result2 = get_min_2(vals)
result3 = min(vals, key = lambda tsync: tsync.x, default=None) # <- this is fine
Here, mypy complains only about get_min_1
:
$ mypy a.py --pretty
a.py:11: error: Item "None" of "X | None" has no attribute "x" [union-attr]
return min(vals, key = lambda tsync: tsync.x, default=None)
^~~~~~~
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used: 1.8.0
- Mypy command-line flags: none required for reproducting the bug
- Mypy configuration options from
mypy.ini
(and other config files): (no config) - Python version used: 3.11