Skip to content

Better error message when union may not have been narrowed #17036

Open
@JukkaL

Description

@JukkaL

Feature

If some attribute is not defined for a single union item (often None), we could give a hint that the type may need to be narrowed down.

Pitch

New users don't always figure out that they need an isinstance or an is not None check, and mypy could make this easier for beginners.

Toy example where this could apply:

def f(s: str | None) -> bool:
    # Item "None" of "str | None" has no attribute "startswith"
    return s.startswith('x')

I'm not sure what a good hint could be, but here's an initial idea:

x.py:3: note: You can use "if s is not None" to guard against a None value

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions