Skip to content

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

@stianjensen

Description

@stianjensen

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions