I have a function myfunction that returns a rather complicated custom type MyClass, or False when the result does not exist, or is irrelevant. Returning False is simpler and I assume more efficient that constructing an instance of MyClass that evaluates to False. Code using the myfunction checks whether the return value is True, not False, before processing the returned object. This works fine.
I now add type hints and run into a problem. I can define:
def myfunction(zap: SomeType) -> MyClass|bool.
This also works fine. The problem is when calling myfunction. For example.
value = myfunction(dadada)
if not value:
return None # We return None when myfunction has nothing useful to return
if value.someattribute > 1:
...
The type checker complains that someattribute may not exist. This is correct, it does not exist when the return value of myfunction is bool. However, if the return is bool, it is False, and this is filtered out. The type checker might be smart enough to see this if it would know the bool can only take the value False, but it does not know that.
I tried, without hope, the following, but it of course does not work:
def myfunction(dadada) -> MyClass|False.
How can I solve this problem, without changing the code to always return a complex MyClass instance?