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

stubgen: Gracefully handle invalid Optional and recognize aliases to PEP 604 unions #17386

Merged
merged 6 commits into from
Jun 17, 2024

Conversation

hamdanal
Copy link
Collaborator

@hamdanal hamdanal commented Jun 15, 2024

This Fixes 2 issues with invalid Optional (inspired by an error reported in #17197):

  • do not crash on empty Optional
  • treat Optional with more than one index as an unknown type instead of choosing the first type.

It also fixes PEP 604 unions not being recognized as type aliases.

This comment has been minimized.

@AlexWaygood
Copy link
Member

AlexWaygood commented Jun 15, 2024

Hmm not sure about this. I lean towards saying we should refuse the temptation to guess if we're given an invalid annotation. I would probably print an error to the terminal noting that we encountered an invalid annotation on line X, fall back to using Incomplete for the variable that has the invalid annotation, and move on.

This comment has been minimized.

Copy link
Member

@AlexWaygood AlexWaygood left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Do we have any tests for e.g. Optional[str | int]?

mypy/stubgen.py Outdated Show resolved Hide resolved
mypy/stubutil.py Outdated Show resolved Hide resolved
Copy link
Member

@AlexWaygood AlexWaygood left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. It looks like stubgen already does the right thing here, but you could also test exotic things like Optional[type[int | str]], for completeness

@hamdanal hamdanal changed the title Gracefully handle invalid Optional usage in stubgen stubgen: Gracefully handle invalid Optional and recognize aliases to PEP 604 unions Jun 15, 2024
Copy link
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

@JukkaL JukkaL merged commit 06c7d26 into python:master Jun 17, 2024
19 checks passed
@hamdanal hamdanal deleted the stubgen-invalid-optional branch June 17, 2024 18:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants