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

wrongly reported typing error in min with key lambda function and default value when result is Optional #17221

Open
jan-spurny opened this issue May 7, 2024 · 0 comments
Labels
bug mypy got something wrong

Comments

@jan-spurny
Copy link

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
@jan-spurny jan-spurny added the bug mypy got something wrong label May 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

1 participant