Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making return type of python optional

Tags:

python-3.x

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.

like image 941
apeter Avatar asked Mar 12 '18 14:03

apeter


People also ask

What is optional return type in Python?

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.

Can you specify return type in Python?

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] .

Are return values optional Python?

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.


1 Answers

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.

like image 181
Chad Befus Avatar answered Nov 02 '22 10:11

Chad Befus