A utility to confirm "or None" types are not None #1997
-
We all have to deal with return values that are "X | None" and the type checker assumes the value is None until we prove it is not None. Sometimes, I want to raise an exception if the value is None, such as: importlibSpecification = importlib.util.spec_from_file_location(pathFilename.stem, pathFilename)
if importlibSpecification is None:
raise ImportError I want to reduce code duplication with a simple utility. Perhaps the syntax would be like importlibSpecification = raiseIfNone(importlib.util.spec_from_file_location(pathFilename.stem, pathFilename), ImportError) I feel like a real programmer must have already come up with ways to handle this situation, whether with a function or something else. What options are there? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
def raise_if_none[T](obj: T | None) -> T:
if obj is None:
raise TypeError('message')
return obj I think that this 3-line-function is easy enough to be just written, when you need it 🤔 |
Beta Was this translation helpful? Give feedback.
-
Thank you. The following seems to be working well. def raiseIfNone[TypeSansNone](returnTarget: TypeSansNone | None) -> TypeSansNone:
if returnTarget is None:
raise ValueError('Return is None.')
return returnTarget |
Beta Was this translation helpful? Give feedback.
I think that this 3-line-function is easy enough to be just written, when you need it 🤔