mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Better error message when union may not have been narrowed

Open JukkaL opened this issue 1 year ago • 6 comments

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

JukkaL avatar Mar 15 '24 18:03 JukkaL

I want to fix this issue.

Eben-Success avatar Mar 22 '24 14:03 Eben-Success

I want to work on this.

keshavt3 avatar Apr 03 '24 22:04 keshavt3

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

kr321 avatar Apr 08 '24 14:04 kr321

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

hauntsaninja avatar Apr 08 '24 19:04 hauntsaninja

I would similarly like to work on it.

GabrielAguirre1 avatar Apr 09 '24 01:04 GabrielAguirre1

I want to fix this

biswaisop avatar Jun 18 '24 20:06 biswaisop

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.

Prabhat-Thapa45 avatar Jul 24 '24 09:07 Prabhat-Thapa45

I believe this issue can be closed.

paulorochaoliveira avatar Dec 06 '24 18:12 paulorochaoliveira

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

brianschubert avatar Dec 06 '24 18:12 brianschubert

@brianschubert You're right. My bad.

paulorochaoliveira avatar Dec 06 '24 18:12 paulorochaoliveira