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

前端 未结 8 1590
忘掉有多难
忘掉有多难 2021-02-05 01:26

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 erro

8条回答
  •  死守一世寂寞
    2021-02-05 01:49

    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
    

提交回复
热议问题