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

Add not_none #7

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
12 changes: 12 additions & 0 deletions static_tests/test_not_none.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from __future__ import annotations

from typing import Any
from typing_extensions import assert_type

from useful_types import not_none


def test(x: Any, y: str | None, z: str) -> None:
assert_type(not_none(x), Any)
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Mypy fails on this one:

static_tests/test_not_none.py:10: error: Expression is of type <nothing>, not "Any"  [assert-type]

Possibly fixable with overloads, let me try that

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

OK, now pyright fails with something worse:

  /home/runner/work/useful_types/useful_types/static_tests/test_not_none.py:10:17 - error: "assert_type" mismatch: expected "Any" but received "Never" (reportGeneralTypeIssues)

I think I prefer the version without overloads.

Copy link
Owner

Choose a reason for hiding this comment

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

I think might work with both if you reorder overloads?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

No, that way it doesn't narrow away the None at all, because None matches the first overload.

assert_type(not_none(y), str)
assert_type(not_none(z), str)
14 changes: 14 additions & 0 deletions useful_types/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,3 +321,17 @@ def __getitem__(self, __i: int) -> int:

class SizedBuffer(Sized, Buffer, Protocol):
...


def not_none(obj: _T | None, /, message: str | None = None) -> _T:
"""Raise TypeError if obj is None, otherwise return obj.

Useful for safely casting away optional types.

"""
if obj is None:
if message is not None:
raise TypeError(message)
else:
raise TypeError("Object is unexpectedly None")
return obj