Scala的选项是否有一个Python等价物?

2024-04-23 15:53:58 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

函数表示“此时未定义我”的python方法是引发异常。

>>> 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

这在一定程度上是因为python没有(通常是有用的)静态类型检查器。Python函数不能在编译时在语法上声明它有一个特定的codomain;无法强制调用方匹配函数返回类型中的所有情况。

如果愿意,可以(不按语法顺序)编写一个Maybe包装器:

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

但我不会这么做,除非您尝试将Scala中的某些内容移植到Python中而不做太多更改。

在python中,由于缺少值,变量为None,因此可以这样做。

vars = None

vars = myfunction()

if vars is None:
     print 'No value!'
else:
     print 'Value!'

或者检查一下是否有这样的值

if vars is not None:
     print vars

mypy在常规Python上添加类型定义和类型检查(不是在运行时)。他们有一个Optionalhttps://docs.python.org/3/library/typing.html#typing.Optional。这里还有https://www.python.org/dev/peps/pep-0484/#rationale-and-goals。Intellij有插件支持,这使得它非常专业和流畅。

相关问题 更多 >