I really enjoy using the Option and Either monads in Scala. Are there any equivalent for these things in Python? If there aren't, then what is the pythonic way of handling errors or "absence of value" without throwing exceptions?
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 / 0
Traceback (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 default
class Just(Maybe):
def __init__(self, value):
self.value = value
class Nothing(Maybe):
pass
But I would not do this, unless you're trying to port something from Scala to Python without changing much.
-
2One may also use
None
vs.<actual value you want>
and enforce it with discipline. – Malcolm May 2 '17 at 21:00 -
1Hi @SingleNegationElimination, i understand your point about absence of static types, but still Option (and other Monads) gives you a powerful abstraction to reason about your code! Even if you won't get type check you still get a hint that value, in case of option, can be missing, and do something to recover from failure! – iuriisusuk Sep 11 '18 at 7:54
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.
-
mypy
'sOptional
is only a type annotation only, meaning that it can be used like this "def foo(arg: Optional[int]) -> Optional[str]: ...` but it cannot be instantiated, namelyOptional("foo")
throws an error. – pseudosudo Aug 28 '20 at 16:29
In python, for an absence of value, the variable is None, so you can do it this way.
vars = None
vars = 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
-
4Why is this voted down? It makes an important point that anything is nullable in Python because Python is not statically type-checked. I'd use
None
in Python the same way I'd useNone
in Scala, but Scala can verify that I don't useNone
in arithmetic, while Python lets me make this mistake all the time. – Jim Pivarski Jun 30 '17 at 7:33 -
3I voted down because the answer is very poor in terms of the question. The Option pattern in scala refers to a pattern Called 'Null Object Pattern' and the intention is to avoid the if statement – LuisKarlos Jan 6 '18 at 0:28
-
This is the simplest and most Pythonic answer, in my opinion. While I think highly of the option pattern in Scala and Rust (for example), but for Python, I think this commenter says it best: "One may also use None vs. <actual value you want> and enforce it with discipline. – Malcolm May 2 '17 at 21:00" – David J. Jan 11 '18 at 15:56
-
@LuisKarlos Under the hood there is if statement anyway. Option type is nothing but syntactic sugar. You can easily write OptionType function in any language. – Marek Marczak Aug 19 '19 at 12:54
-
I vote up because this is what I was looking for. (each language has its strengths, Scala has a cool compiler for having a cool Option pattern ... well, Python has simplicity for quick prototyping and with that a simple None, cool for me too) – Carlos Saltos Apr 3 '20 at 5:35
I realize this is pretty late to the party but I came to this page on top of google before deciding to implement it so maybe I can help others googling with this. I implemented it, you can get it from pypi as pyther-maybe
, it implements both Either and Maybe with Maybe as a special subclass of Either. This example should explain how it works:
import sys
from pyther_maybe import *
def save_div ( x, y ):
if y == 0:
return nothing() # alias of Maybe()
else:
return value(x / y) # alias of Maybe(x / y)
float_test = save_div(1.0, 3.0)
assert isinstance(float_test, Maybe)
if float_test: #nothing tests as false:
float = float_test() # calling the container with no arguments returns its value
else:
sys.exit("something went wrong")
print float
# or if you want to encode a reason:
def save_div ( x, y ):
if y == 0:
return left("You can't divide by zero, silly") # alias of Either(left=...)
else:
return right(x / y) # alis of Either(...)
float_test = save_div(4.2, 0.0)
assert isinstance(float_test, Either)
def fake_exit ( string ):
print "We would have exited with:"
print string
return "Whatever value"
if float_test:
# these two are te same
float = float_test()
float = float_test.right()
else:
fake_exit(float_test.left())
# or in a shorter and more pleasant format
# does the same as above
float = float_test.extract(fake_exit)
print float # prints "Whatever value"
# Also, these containers are mutable:
box = nothing()
try:
print box() # raises exception
except RightEitherException:
print "We caught an exception"
def change_box():
box(4)
change_box()
print box() # 4
It has more features than that, some of which are pretty useless in practise (it's also an iterator for instance and has subscript notation like pyther_maybe.either(x)[pyther_maybe.Right] == x
.
You can play with typing package (Python 3.6.9). Using following makes type checker happy
from typing import Optional, Union
def parse_int(s: str) -> Optional[int]:
try:
return int(s)
except:
return None
print('-- optional --')
print(parse_int('123'))
print(parse_int('a'))
def parse_int2(s: str) -> Union[str, int]:
try:
return int(s)
except Exception as e:
return f'Error during parsing "{s}": {e}'
print('-- either --')
print(parse_int2('123'))
print(parse_int2('a'))
Result
-- optional --
123
None
-- either --
123
Error during parsing "a": invalid literal for int() with base 10: 'a'
If you want to add monadic behaviour to Either
you can try this
from typing import TypeVar, Generic, Callable
A = TypeVar('A')
B = TypeVar('B')
C = TypeVar('C')
Either = NewType('Either', Union['Left[A]', 'Right[C]'])
class Left(Generic[A]):
def __init__(self, value: A):
self.__value = value
def get(self) -> A:
raise Exception('it is left')
def get_left(self) -> A:
return self.__value
def flat_map(self, f: Callable[[B], Either]) -> Either:
return self
def map(self, f: Callable[[B], C]) -> Either:
return self
def __str__(self):
return f'Left({self.__value})'
and right type
class Right(Generic[B]):
def __init__(self, value: B):
self.__value = value
def flat_map(self, f: Callable[[B], Either]) -> Either:
return f(self.__value)
def map(self, f: Callable[[B], C]) -> Either:
return Right(f(self.__value))
def __str__(self):
return f'Right({self.__value})'
def parse_int(s: str) -> Union[Left[str], Right[int]]:
try:
return Right(int(s))
except Exception as e:
return Left(f'Error during parsing {s}: {e}')
def divide(x: int) -> Union[Left[str], Right[int]]:
return Right(4 / x) if x != 0 else Left('zero !!!')
print(parse_int('1').map(lambda x: x * 2))
print(parse_int('a').map(lambda x: x * 2))
print(parse_int('2').flat_map(divide))
print(parse_int('0').flat_map(divide))
Result
Right(2)
Left(Error during parsing a: invalid literal for int() with base 10: 'a')
Right(2.0)
Left(zero !!!)
A list that happens to always be of length zero or one fulfills some of the same goals as optional/maybe types. You won't get the benefits of static typing in Python, but you'll probably get a run-time error even on the happy path if you write code that tries to use the "maybe" without explicitly "unwrapping" it.
Try This:
from monad import Monad
class Either(Monad):
# pure :: a -> Either a
@staticmethod
def pure(value):
return Right(value)
# flat_map :: # Either a -> (a -> Either b) -> Either b
def flat_map(self, f):
if self.is_left:
return self
else:
return f(self.value)
class Left(Either):
def __init__(self, value):
self.value = value
self.is_left = True
class Right(Either):
def __init__(self, value):
self.value = value
self.is_left = False
Natively, Python has a Literal Type Optional but it's not the same. Alternatively this is a representation of the Either data type for python 3.
https://gist.github.com/MatteoGuadrini/98e79a9ab2bd6ae5badc41df89cfe338
pip install either
The library was created in 2012, its Development status is: Stable, according to https://pypi.org/project/either/.