详解 Python 的二元算术运算,为何说减法只是语法糖?

原题 | Unravelling binary arithmetic operations in Pythonhtml

做者 | Brett Cannonpython

译者 | 豌豆花下猫(“Python猫”公众号做者)git

声明 | 本翻译是出于交流学习的目的,基于 CC BY-NC-SA 4.0 受权协议。为便于阅读,内容略有改动。github

你们对我解读属性访问的博客文章反应热烈,这启发了我再写一篇关于 Python 有多少语法实际上只是语法糖的文章。在本文中,我想谈谈二元算术运算。c#

具体来讲,我想解读减法的工做原理:a - b。我故意选择了减法,由于它是不可交换的。这能够强调出操做顺序的重要性,与加法操做相比,你可能会在实现时误将 a 和 b 翻转,但仍是获得相同的结果。闭包

查看 C 代码

按照惯例,咱们从查看 CPython 解释器编译的字节码开始。函数

>>> def sub(): a - b
... 
>>> import dis
>>> dis.dis(sub)
  1           0 LOAD_GLOBAL              0 (a)
              2 LOAD_GLOBAL              1 (b)
              4 BINARY_SUBTRACT
              6 POP_TOP
              8 LOAD_CONST               0 (None)
             10 RETURN_VALUE

看起来咱们须要深刻研究 BINARY_SUBTRACT 操做码。翻查 Python/ceval.c 文件,能够看到实现该操做码的 C 代码以下:性能

case TARGET(BINARY_SUBTRACT): {
    PyObject *right = POP();
    PyObject *left = TOP();
    PyObject *diff = PyNumber_Subtract(left, right);
    Py_DECREF(right);
    Py_DECREF(left);
    SET_TOP(diff);
    if (diff == NULL)
    goto error;
    DISPATCH();
}

来源:https://github.com/python/cpython/blob/6f8c8320e9eac9bc7a7f653b43506e75916ce8e8/Python/ceval.c#L1569-L1579学习

这里的关键代码是PyNumber_Subtract(),实现了减法的实际语义。继续查看该函数的一些宏,能够找到binary_op1() 函数。它提供了一种管理二元操做的通用方法。ui

不过,咱们不把它做为实现的参考,而是要用Python的数据模型,官方文档很好,清楚介绍了减法所使用的语义。

从数据模型中学习

通读数据模型的文档,你会发如今实现减法时,有两个方法起到了关键做用:__sub____rsub__

一、__sub__()方法

当执行a - b 时,会在 a 的类型中查找__sub__(),而后把 b 做为它的参数。这很像我写属性访问的文章 里的__getattribute__(),特殊/魔术方法是根据对象的类型来解析的,并非出于性能目的而解析对象自己;在下面的示例代码中,我使用_mro_getattr() 表示此过程。

所以,若是已定义 __sub__(),则 type(a).__sub__(a,b) 会被用来做减法操做。(译注:魔术方法属于对象的类型,不属于对象)

这意味着在本质上,减法只是一个方法调用!你也能够将它理解成标准库中的 operator.sub() 函数。

咱们将仿造该函数实现本身的模型,用 lhs 和 rhs 两个名称,分别表示 a-b 的左侧和右侧,以使示例代码更易于理解。

# 经过调用__sub__()实现减法 
def sub(lhs: Any, rhs: Any, /) -> Any:
    """Implement the binary operation `a - b`."""
    lhs_type = type(lhs)
    try:
        subtract = _mro_getattr(lhs_type, "__sub__")
    except AttributeError:
        msg = f"unsupported operand type(s) for -: {lhs_type!r} and {type(rhs)!r}"
        raise TypeError(msg)
    else:
        return subtract(lhs, rhs)

二、让右侧使用__rsub__()

可是,若是 a 没有实现__sub__() 怎么办?若是 a 和 b 是不一样的类型,那么咱们会尝试调用 b 的 __rsub__()(__rsub__ 里面的“r”表示“右”,表明在操做符的右侧)。

当操做的双方是不一样类型时,这样能够确保它们都有机会尝试使表达式生效。当它们相同时,咱们假设__sub__() 就可以处理好。可是,即便两边的实现相同,你仍然要调用__rsub__(),以防其中一个对象是其它的(子)类。

三、不关心类型

如今,表达式双方均可以参与运算!可是,若是因为某种缘由,某个对象的类型不支持减法怎么办(例如不支持 4 - “stuff”)?在这种状况下,__sub__ 或__rsub__ 能作的就是返回 NotImplemented。

这是给 Python 返回的信号,它应该继续执行下一个操做,尝试使代码正常运行。对于咱们的代码,这意味着须要先检查方法的返回值,而后才能假定它起做用。

# 减法的实现,其中表达式的左侧和右侧都可参与运算
_MISSING = object()

def sub(lhs: Any, rhs: Any, /) -> Any:
        # lhs.__sub__
        lhs_type = type(lhs)
        try:
            lhs_method = debuiltins._mro_getattr(lhs_type, "__sub__")
        except AttributeError:
            lhs_method = _MISSING

        # lhs.__rsub__ (for knowing if rhs.__rub__ should be called first)
        try:
            lhs_rmethod = debuiltins._mro_getattr(lhs_type, "__rsub__")
        except AttributeError:
            lhs_rmethod = _MISSING

        # rhs.__rsub__
        rhs_type = type(rhs)
        try:
            rhs_method = debuiltins._mro_getattr(rhs_type, "__rsub__")
        except AttributeError:
            rhs_method = _MISSING

        call_lhs = lhs, lhs_method, rhs
        call_rhs = rhs, rhs_method, lhs

        if lhs_type is not rhs_type:
            calls = call_lhs, call_rhs
        else:
            calls = (call_lhs,)

        for first_obj, meth, second_obj in calls:
            if meth is _MISSING:
                continue
            value = meth(first_obj, second_obj)
            if value is not NotImplemented:
                return value
        else:
            raise TypeError(
                f"unsupported operand type(s) for -: {lhs_type!r} and {rhs_type!r}"
            )

四、子类优先于父类

若是你看一下__rsub__() 的文档,就会注意到一条注释。它说若是一个减法表达式的右侧是左侧的子类(真正的子类,同一类的不算),而且两个对象的__rsub__() 方法不一样,则在调用__sub__() 以前会先调用__rsub__()。换句话说,若是 b 是 a 的子类,调用的顺序就会被颠倒。

这彷佛是一个很奇怪的特例,但它背后是有缘由的。当你建立一个子类时,这意味着你要在父类提供的操做上注入新的逻辑。这种逻辑不必定要加给父类,不然父类在对子类操做时,就很容易覆盖子类想要实现的操做。

具体来讲,假设有一个名为 Spam 的类,当你执行 Spam() - Spam() 时,获得一个 LessSpam 的实例。接着你又建立了一个 Spam 的子类名为 Bacon,这样,当你用 Spam 去减 Bacon 时,你获得的是 VeggieSpam。

若是没有上述规则,Spam() - Bacon() 将获得 LessSpam,由于 Spam 不知道减掉 Bacon 应该得出 VeggieSpam。

可是,有了上述规则,就会获得预期的结果 VeggieSpam,由于 Bacon.__rsub__() 首先会在表达式中被调用(若是计算的是 Bacon() - Spam(),那么也会获得正确的结果,由于首先会调用 Bacon.__sub__(),所以,规则里才会说两个类的不一样的方法需有区别,而不只仅是一个由 issubclass() 判断出的子类。)

# Python中减法的完整实现
_MISSING = object()

def sub(lhs: Any, rhs: Any, /) -> Any:
        # lhs.__sub__
        lhs_type = type(lhs)
        try:
            lhs_method = debuiltins._mro_getattr(lhs_type, "__sub__")
        except AttributeError:
            lhs_method = _MISSING

        # lhs.__rsub__ (for knowing if rhs.__rub__ should be called first)
        try:
            lhs_rmethod = debuiltins._mro_getattr(lhs_type, "__rsub__")
        except AttributeError:
            lhs_rmethod = _MISSING

        # rhs.__rsub__
        rhs_type = type(rhs)
        try:
            rhs_method = debuiltins._mro_getattr(rhs_type, "__rsub__")
        except AttributeError:
            rhs_method = _MISSING

        call_lhs = lhs, lhs_method, rhs
        call_rhs = rhs, rhs_method, lhs

        if (
            rhs_type is not _MISSING  # Do we care?
            and rhs_type is not lhs_type  # Could RHS be a subclass?
            and issubclass(rhs_type, lhs_type)  # RHS is a subclass!
            and lhs_rmethod is not rhs_method  # Is __r*__ actually different?
        ):
            calls = call_rhs, call_lhs
        elif lhs_type is not rhs_type:
            calls = call_lhs, call_rhs
        else:
            calls = (call_lhs,)

        for first_obj, meth, second_obj in calls:
            if meth is _MISSING:
                continue
            value = meth(first_obj, second_obj)
            if value is not NotImplemented:
                return value
        else:
            raise TypeError(
                f"unsupported operand type(s) for -: {lhs_type!r} and {rhs_type!r}"
            )

推广到其它二元运算

解决掉了减法运算,那么其它二元运算又如何呢?好吧,事实证实它们的操做相同,只是碰巧使用了不一样的特殊/魔术方法名称。

因此,若是咱们能够推广这种方法,那么咱们就能够实现 13 种操做的语义:+ 、-、*、@、/、//、%、**、<<、>>、&、^、和 |。

因为闭包和 Python 在对象自省上的灵活性,咱们能够提炼出 operator 函数的建立。

# 一个建立闭包的函数,实现了二元运算的逻辑
_MISSING = object()


def _create_binary_op(name: str, operator: str) -> Any:
    """Create a binary operation function.

    The `name` parameter specifies the name of the special method used for the
    binary operation (e.g. `sub` for `__sub__`). The `operator` name is the
    token representing the binary operation (e.g. `-` for subtraction).

    """

    lhs_method_name = f"__{name}__"

    def binary_op(lhs: Any, rhs: Any, /) -> Any:
        """A closure implementing a binary operation in Python."""
        rhs_method_name = f"__r{name}__"

        # lhs.__*__
        lhs_type = type(lhs)
        try:
            lhs_method = debuiltins._mro_getattr(lhs_type, lhs_method_name)
        except AttributeError:
            lhs_method = _MISSING

        # lhs.__r*__ (for knowing if rhs.__r*__ should be called first)
        try:
            lhs_rmethod = debuiltins._mro_getattr(lhs_type, rhs_method_name)
        except AttributeError:
            lhs_rmethod = _MISSING

        # rhs.__r*__
        rhs_type = type(rhs)
        try:
            rhs_method = debuiltins._mro_getattr(rhs_type, rhs_method_name)
        except AttributeError:
            rhs_method = _MISSING

        call_lhs = lhs, lhs_method, rhs
        call_rhs = rhs, rhs_method, lhs

        if (
            rhs_type is not _MISSING  # Do we care?
            and rhs_type is not lhs_type  # Could RHS be a subclass?
            and issubclass(rhs_type, lhs_type)  # RHS is a subclass!
            and lhs_rmethod is not rhs_method  # Is __r*__ actually different?
        ):
            calls = call_rhs, call_lhs
        elif lhs_type is not rhs_type:
            calls = call_lhs, call_rhs
        else:
            calls = (call_lhs,)

        for first_obj, meth, second_obj in calls:
            if meth is _MISSING:
                continue
            value = meth(first_obj, second_obj)
            if value is not NotImplemented:
                return value
        else:
            exc = TypeError(
                f"unsupported operand type(s) for {operator}: {lhs_type!r} and {rhs_type!r}"
            )
            exc._binary_op = operator
            raise exc

有了这段代码,你能够将减法运算定义为 _create_binary_op(“sub”, “-”),而后根据须要重复定义出其它运算。

更多信息

经过本博客的“语法糖”标签,你能够找到更多详解 Python 语法的文章。源代码能够在https://github.com/brettcannon/desugar上找到。

更正

  • 2020-08-19:修复了当__rsub__() 比 __sub__() 先调用时的规则。
  • 2020-08-22:修复了当类型相同时不调用__rsub__ 的问题;还精简了过渡代码,仅保留开头和结尾代码,这让我轻松些。
  • 2020-08-23:在多数示例中添加了内容。
相关文章
相关标签/搜索