Is there a Python equivalent for Scala's Option or Either? Is there a Python equivalent for Scala's Option or Either? python python

Is there a Python equivalent for Scala's Option or Either?


The pythonic way for a function to say "I am not defined at this point" is to raise an exception.

>>> int("blarg")Traceback (most recent call last):  ...ValueError: invalid literal for int() with base 10: 'blarg'>>> dict(foo=5)['bar']Traceback (most recent call last):  ...KeyError: 'bar'>>> 1 / 0Traceback (most recent call last):  ...ZeroDivisionError: integer division or modulo by zero

This is, in part, because there's no (generally useful) static type checker for python. A Python function cannot syntactically state, at compile time, that it has a particular codomain; there's no way to force callers to match all of the cases in the function's return type.

If you prefer, you can write (unpythonically) a Maybe wrapper:

class Maybe(object):    def get_or_else(self, default):        return self.value if isinstance(self, Just) else defaultclass Just(Maybe):    def __init__(self, value):        self.value = valueclass Nothing(Maybe):    pass

But I would not do this, unless you're trying to port something from Scala to Python without changing much.


mypy adds type definitions and type checking (not at runtime) over regular Python. They have an Optional: https://docs.python.org/3/library/typing.html#typing.Optional. More here https://www.python.org/dev/peps/pep-0484/#rationale-and-goals. Intellij has plugin support which makes it all very professional and smooth.


In python, for an absence of value, the variable is None, so you can do it this way.

vars = Nonevars = myfunction()if vars is None:     print 'No value!'else:     print 'Value!'

or even just check if a value is present like this

if vars is not None:     print vars