Skip to content

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

Closed
@knbk

Description

@knbk

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions