是否有与Scala的Option或Either相当的Python? [英] Is there a Python equivalent for Scala's Option or Either?

查看:215
本文介绍了是否有与Scala的Option或Either相当的Python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我非常喜欢在Scala中使用Option和Either monads。 Python中是否有这些东西的等价物?如果没有,那么在没有抛出异常的情况下处理错误或没有价值的pythonic方式是什么? 解决方案

呃,真的,一个函数说我现在没有定义的pythonic方法是引发一个异常。

 >>> int(blarg)
Traceback(最近一次调用最后一次):
...
ValueError:int()的基数为10的无效字面值:'blarg'

>>> dict(foo = 5)['bar']
Traceback(最近一次调用最后一次):
...
KeyError:'bar'

>> ;> 1/0
Traceback(最近一次调用最后一次):
...
ZeroDivisionError:整数除法或零模

这部分是因为python没有(通常有用的)静态类型检查器。在编译时,一个python函数不能在语法上声明它具有特定的共域;没有办法强制调用者匹配函数返回类型中的所有情况。



如果您愿意,您可以编写(unpython)一个Maybe包装器:

  class Maybe(object):
def get_or_else(self,default):
如果isinstance返回self.vaue( self,just)else default

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

class没有(也许):
通过

但我不会这么做,除非你试图将某些东西从scala移植到python而不会改变太多

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?

解决方案

Well, really, 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.vaue 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

这篇关于是否有与Scala的Option或Either相当的Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆