Skip to content

Typechecking differs between one-line def of "return expr" vs. "r = expr; return r" #11985

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

Open
drvink opened this issue Jan 13, 2022 · 2 comments · May be fixed by #18976
Open

Typechecking differs between one-line def of "return expr" vs. "r = expr; return r" #11985

drvink opened this issue Jan 13, 2022 · 2 comments · May be fixed by #18976
Labels
bug mypy got something wrong topic-type-context Type context / bidirectional inference

Comments

@drvink
Copy link
Contributor

drvink commented Jan 13, 2022

mypy 0.931

#!/usr/bin/env python3

from collections.abc import Iterable
from typing import Optional
import os

def min_direntry_good(
        fs: 'Iterable[os.DirEntry[str]]'
) -> 'Optional[os.DirEntry[str]]':
    r = min(fs, default=None, key=lambda x: x.stat().st_mtime)
    return r

def min_direntry_bad(
        fs: 'Iterable[os.DirEntry[str]]'
) -> 'Optional[os.DirEntry[str]]':
    return min(fs, default=None, key=lambda x: x.stat().st_mtime)
hober.py:16: error: Item "None" of "Optional[DirEntry[str]]" has no attribute "stat"
Found 1 error in 1 file (checked 1 source file)
@drvink
Copy link
Contributor Author

drvink commented Mar 12, 2022

This is still broken in mypy 0.940:

hober.py:16: error: Item "None" of "Optional[DirEntry[str]]" has no attribute "stat"  [union-attr]
hober.py:16: error: Invalid self argument "stat_result" to attribute function "st_mtime" with type "Callable[[stat_result], float]"  [misc]
Found 2 errors in 1 file (checked 1 source file)

@JelleZijlstra
Copy link
Member

This is likely an issue with mypy's "type context", which infers different types based on the "expected" type. Here it obviously goes wrong, but chances are it's hard to fix it without breaking some other use case.

@AlexWaygood AlexWaygood added bug mypy got something wrong topic-type-context Type context / bidirectional inference labels Mar 28, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-type-context Type context / bidirectional inference
Projects
None yet
3 participants