Skip to content
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

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

Open
JukkaL opened this issue Mar 15, 2024 · 7 comments · Fixed by hemant-iitkgp/mypy#1 · 4 remaining pull requests
Open

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

JukkaL opened this issue Mar 15, 2024 · 7 comments · Fixed by hemant-iitkgp/mypy#1 · 4 remaining pull requests

Comments

@JukkaL
Copy link
Collaborator

JukkaL commented Mar 15, 2024

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
@Eben-Success
Copy link

I want to fix this issue.

@keshavt3
Copy link

keshavt3 commented Apr 3, 2024

I want to work on this.

@kr321
Copy link

kr321 commented Apr 8, 2024

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

@hauntsaninja
Copy link
Collaborator

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

@GabrielAguirre1
Copy link

I would similarly like to work on it.

@biswaisop
Copy link

I want to fix this

@Prabhat-Thapa45
Copy link

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.

Hemant-exe18 pushed a commit to Hemant-exe18/mypy that referenced this issue Sep 7, 2024
Updated messages.py to include a helpful note suggesting the use of "if s is not None" to handle cases where Union types might include None. This enhancement provides clearer guidance for users encountering attribute errors with Union types.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment