詳解 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:在多數示例中添加了內容。
相關文章
相關標籤/搜索