In JVM languages there is a data type called Optional which says value can be Null/None. By using the data type of a function as Option(for example Option(Int)). Calling statement of function can take action.
How does one implement a similar approach in Python. I want to create a function and the return value of function should tell me 1. Function was successful so I have a value returned. 2. Function was not successful and so there is nothing to return.
The Optional[T] type is well-known in the functional programming community. The reader will not only know that it means Union[T, None] , but will also recognise the use pattern that the function shall return None when there is no meaningful answer, there is an error, or the result is not found.
It is possible to declare the return type of a callable without specifying the call signature by substituting a literal ellipsis for the list of arguments in the type hint: Callable[..., ReturnType] .
Understanding the Python return Statement. The Python return statement is a special statement that you can use inside a function or method to send the function's result back to the caller. A return statement consists of the return keyword followed by an optional return value.
I also wanted to tackle this problem and made a library called optional.py to do so. It can be installed using pip install optional.py
. It is fully test covered and supports python2 and python3. Would love some feedback, suggestions, contributions.
To address the concerns of the other answer, and to head off any haters, yes, raising exceptions is more idiomatic of python, however it leads to ambiguity between exceptions for control-flow and exceptions for actual exceptional reasons.
There are large discussions about preventing defensive programming which mask the core logic of an application and smart people on both sides of the conversation. My personal preference is towards using optionals and so I provided the library to support that preference. Doing it with exceptions (or returning None
) are acceptable alternatives, just not my preference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With