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

Regression in 'unwrapping' optional variables with a function #18059

Closed
stianjensen opened this issue Oct 28, 2024 · 1 comment
Closed

Regression in 'unwrapping' optional variables with a function #18059

stianjensen opened this issue Oct 28, 2024 · 1 comment
Labels
bug mypy got something wrong

Comments

@stianjensen
Copy link

Bug Report

For as long as we've been using mypy, we've had this small helper called 'unwrap' to help us work with variables that are for any reason typed to include None, but we for different reasons know in some context are never None in practice.
The helper looks like this:

def unwrap[T](optional: T | None) -> T:
    if optional is None:
        raise ValueError()
    return optional

As of mypy 1.12 we see that, if the type before we try narrowing with our function is Any, the resulting type is now Never.

My suspicion is this is related to #17427, but I have not performed a bisect.

To Reproduce

https://mypy-play.net/?mypy=master&python=3.12&flags=show-traceback%2Cwarn-unreachable&gist=6b15a353aa5a6a39fa16fb13fbc009b3

Expected Behavior

I would expect the type to update to just not include None.

Actual Behavior

Type is changed to Never.

Your Environment

  • Mypy version used: mypy 1.12, mypy 1.13, mypy master branch
  • Python version used: 3.12
@stianjensen stianjensen added the bug mypy got something wrong label Oct 28, 2024
@stianjensen
Copy link
Author

After comparing the playground some more with mypy 1.11, I realize this is not really a regression. The actual regression I've been observing is related to django-stubs now inferring some types to Any | None, which means I need to use my helper more than before.

It has actually never worked with types that includes Any. But I solved it with some use of overload:

@overload
def unwrap[T](optional: T | None) -> T: ...


@overload
def unwrap(optional: Any) -> Any: ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

1 participant