Skip to content

Commit

Permalink
feat(types): Add NonNone non-null assertion operator stand-in (#70236)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
lobsterkatie authored May 3, 2024
1 parent 288f928 commit 3e90887
Showing 1 changed file with 6 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/sentry/utils/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,3 +221,9 @@ def type_from_value(value):


AnyCallable = typing.Callable[..., AnyType]


def NonNone(value: T | None) -> T:
"""A hacked version of TS's non-null assertion operator"""
assert value is not None
return value

0 comments on commit 3e90887

Please sign in to comment.