I have a function where it usually returns an object that it searches for and performs some other actions. It raises an exception if it fails to find a match. Frequently, I don't care if it finds a match or not, but not frequently enough that I'd consider removing the exception entirely. As such, the compromise I've made is to create a parameter raise_on_failure which defaults to True. If it is False, then None is returned rather than the reference.
def searchAndOperate(f, raise_on_failure: bool = True) -> Optional[Foo]:
# Search
result = ...
if result is None:
if raise_on_failure: raise ValueError("No results")
else: return None
# Operate
...
# Then return the result
return result
However, this has caused some issues with my type hinting. I want to make it so that if raise_on_failure is True, the function is guaranteed to return a Foo, such that it is only Optional[Foo] if raise_on_failure is False.
How can I do this? Something akin to the following snippet would be the most desirable, but I'm open to other ideas too.
def searchAndOperate(
f,
raise_on_failure: bool = True
) -> Foo if raise_on_failure else Optional[Foo]:
...