Skip to content

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

Closed as not planned

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

Activity

  1. Eben-Success commented on Mar 22, 2024

    @Eben-Success

    I want to fix this issue.

  2. keshavt3 commented on Apr 3, 2024

    @keshavt3

    I want to work on this.

  3. kr321 commented on Apr 8, 2024

    @kr321

    I would like to work on this with a group for a college software engineering class.

  4. hauntsaninja commented on Apr 8, 2024

    @hauntsaninja
    Collaborator

    Any of you please feel free to, just post on this issue when you have an open PR that passes tests!

  5. GabrielAguirre1 commented on Apr 9, 2024

    @GabrielAguirre1

    I would similarly like to work on it.

  6. biswaisop commented on Jun 18, 2024

    @biswaisop

    I want to fix this

  7. Prabhat-Thapa45 commented on Jul 24, 2024

    @Prabhat-Thapa45

    I felt many people missed what you( @JukkaL ) meant by often None to only none. I have added hint for all the missing attribute in my pr.

  8. added a commit that references this issue on Sep 7, 2024
  9. paulorochaoliveira commented on Dec 6, 2024

    @paulorochaoliveira

    I believe this issue can be closed.

  10. brianschubert commented on Dec 6, 2024

    @brianschubert
    Collaborator

    I don't think a PR for this issue has been merged yet (the merged PR above is on a fork).

  11. paulorochaoliveira commented on Dec 6, 2024

    @paulorochaoliveira

    @brianschubert You're right. My bad.

  12. added a commit that references this issue on Feb 24, 2026
    5418322
  13. hauntsaninja commented on Mar 27, 2026

    @hauntsaninja
    Collaborator

    I think mypy's behaviour is fine as-is. It's not clear that this is an issue users are confused about, or that recommending an if is better than recommending an assert

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions