Python Optionals

Clean Code, Data-Structures, Developing, Libraries, Python

Optionals for Python

The Optional data type is highly valuable to various languages which have it built-in or use is standard.
It’s a collection like object which can hold one item or be empty. If you have a function which returns multiple items, when you have nothing to return, an empty list is returned, and can be used just as if you had returned a full one. With an optional, when you have a function which returns a single item, but have nothing to return, you return the empty optional and it can be used just as if you had a full optional.

Visit GitHub Page

This isn’t Pythonic

It’s right there in the second line of the Zen of Python: “Explicit is better than implicit”. Yet python heavily depends on its implicit None (A function with no return, returns a None). There are two problems with None: It propagates (masked as whatever it’s been named) and it’s definition is ambiguous.

The propagation isn’t really fixed by using optionals in a dynamically typed language (though it does fix it in statically typed languages). But for the record, the problem with None Propagation is that the error occurs at the dereference point, not at the assignment, which makes debugging harder than necessary. It’s not a reason to use optionals (they have this same issue in python) but the ambiguity of None in python does make the propagation problem worth.

None is ambiguous. It gets used to indicate emptiness, error results, and it can be a sign of an unintentional mistake; also known as a bug (for example forgetting a return statement). As developers we can control the first two cases but the third is harder. For error results we should throw exceptions, to indicate emptiness we should use optionals and with those we will always know that None indicates a bug.

To read more about optionals, how they can and should be used, and start with the optional.py library visit the GitHub page.

GitHub