Skip to content

Unneeded type widening of inner function call when using explicit return type #12092

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
knbk opened this issue Jan 28, 2022 · 1 comment · May be fixed by #18976
Open

Unneeded type widening of inner function call when using explicit return type #12092

knbk opened this issue Jan 28, 2022 · 1 comment · May be fixed by #18976

Comments

@knbk
Copy link
Contributor

knbk commented Jan 28, 2022

Using an explicit return type unnecessarily widens the types in filter():

def return_a(strings: list[str]) -> Optional[str]:
    # Item "None" of "Optional[str]" has no attribute "strip"
    return next(filter(lambda s: s.strip() == "a", strings), None)

and a comparable error when the filter function is explicitly typed:

def matches_a(s: str) -> bool:
    return s.strip() == "a"

def return_a(strings: list[str]) -> Optional[str]:
    # Argument 1 to "filter" has incompatible type "Callable[[str], Any]"; expected "Callable[[Optional[str]], Any]"
    return next(filter(matches_a, strings), None)

No error occurs when the explicit return type is removed:

# return_a is inferred to return str | None
def return_a(strings: list[str]):
    # No error
    return next(filter(lambda s: s.strip() == "a", strings), None)

Mypy 0.931, Python 3.8.6.

@hauntsaninja
Copy link
Collaborator

Note that mypy doesn't infer return types, so in your last example, mypy is actually treating the return type of return_a as Any.

But the issue is true in general, it's a somewhat commonly reported problem with mypy's type context, e.g. the following type checks:

def return_a(strings: list[str]) -> Optional[str]:
    ret = next(filter(lambda s: s.strip() == "a", strings), None)
    return ret

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
2 participants