Java-like Optional in Python

Posted on Wed, 23 Nov 2016 in Python

Sometimes using None makes a mess of a code. For example, if you want to separate some "empty" value and "no data" value for integer input where 0 isn't "empty" value, it's very hard to do with None only. Possible solution is to use something like Optional in Java.

Of course, using Optional isn't the pythonic way. In some cases using exception as supposed in this StackOverflow discussion is enough.

It doesn't work in my case. I decided to implement Optional. At the end I've got clean and nice piece of code. After short discussion with my colleagues, we decided to use Haskell names for it (Maybe instead Optional). There is my simple version:

from abc import ABCMeta, abstractmethod

class Maybe(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def get(self, default=None):
        pass


class Just(Maybe):
    def __init__(self, value):
        self.value = value

    def __nonzero__(self):
        return True

    def get(self, default=None):
        return self.value


class Nothing(Maybe):
    def __nonzero__(self):
        return False

    def get(self, default=None):
        return default

After integrating it to existing code, I can say that this solution works perfectly. Maybe you should add repr-functions. But even without them it's very convenient while debug.

If you want something more complex, try hask. Note! There is too much Haskell in their Python.

Some more approaches to deal with the same problem you can find in Python Option Types article.

---
Got a question? Hit me on Twitter: avkorablev