Skip to content

Commit 3e90887

Browse files
authored
feat(types): Add NonNone non-null assertion operator stand-in (#70236)
This introduces a `NonNone` type utility meant to mimic the non-null assertion operator (`!`) in TypeScript. For example, given a function with the signature `make_stuff() -> Stuff | None`, used in a place where you know it's going to return a `Stuff` instance, you can change your call from `stuff = make_stuff()` to `stuff = NonNone(make_stuff())`, and mypy will stop complaining that `stuff` might be `None`. I know you can do this with `cast`, but this seemed more expressive and like it would add a little less( or possibly a lot less) clutter to the code. (Consider a value typed as `dict[str, tuple[list[Stuff]]] | None`. Would you rather `cast(dict[str, tuple[list[Stuff]]], stuff)` or `NonNone(stuff)`?) Disclaimer: This may or may not be the most elegant way to do this, and I'm very open to suggestions for future improvements (or for a different approach entirely), but for now this clears a blocker (and was the best option with which fairly extensive googling provided me), so I went with it.
1 parent 288f928 commit 3e90887

File tree

1 file changed

+6
-0
lines changed

1 file changed

+6
-0
lines changed

src/sentry/utils/types.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,3 +221,9 @@ def type_from_value(value):
221221

222222

223223
AnyCallable = typing.Callable[..., AnyType]
224+
225+
226+
def NonNone(value: T | None) -> T:
227+
"""A hacked version of TS's non-null assertion operator"""
228+
assert value is not None
229+
return value

0 commit comments

Comments
 (0)