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

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

[[341459]]

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

具体来说,我想解读减法的工作原理:a - b。我故意选择了减法,因为它是不可交换的。这可以强调出操作顺序的重要性,与加法操作相比,你可能会在实现时误将 a 和 b 翻转,但还是得到相同的结果。

查看 C 代码

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

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

看起来我们需要深入研究 BINARY_SUBTRACT 操作码。翻查 Python/ceval.c 文件,可以看到实现该操作码的 C 代码如下:

  1. case TARGET(BINARY_SUBTRACT): { 
  2.     PyObject *right = POP(); 
  3.     PyObject *left = TOP(); 
  4.     PyObject *diff = PyNumber_Subtract(leftright); 
  5.     Py_DECREF(right); 
  6.     Py_DECREF(left); 
  7.     SET_TOP(diff); 
  8.     if (diff == NULL
  9.     goto error; 
  10.     DISPATCH(); 

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

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

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

从数据模型中学习

通读数据模型的文档,你会发现在实现减法时,有两个方法起到了关键作用:__sub__ 和 __rsub__。

1、__sub__()方法

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

因此,如果已定义 __sub__(),则 type(a).__sub__(a,b) 会被用来作减法操作。(译注:魔术方法属于对象的类型,不属于对象)

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

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

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

2、让右侧使用__rsub__()

但是,如果 a 没有实现__sub__() 怎么办?如果 a 和 b 是不同的类型,那么我们会尝试调用 b 的 __rsub__()(__rsub__ 里面的“r”表示“右”,代表在操作符的右侧)。

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

3、不关心类型

现在,表达式双方都可以参与运算!但是,如果由于某种原因,某个对象的类型不支持减法怎么办(例如不支持 4 - “stuff”)?在这种情况下,__sub__ 或__rsub__ 能做的就是返回 NotImplemented。

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

  1. # 减法的实现,其中表达式的左侧和右侧均可参与运算 
  2. _MISSING = object() 
  3.  
  4. def sub(lhs: Any, rhs: Any, /) -> Any
  5.         # lhs.__sub__ 
  6.         lhs_type = type(lhs) 
  7.         try: 
  8.             lhs_method = debuiltins._mro_getattr(lhs_type, "__sub__"
  9.         except AttributeError: 
  10.             lhs_method = _MISSING 
  11.  
  12.         # lhs.__rsub__ (for knowing if rhs.__rub__ should be called first
  13.         try: 
  14.             lhs_rmethod = debuiltins._mro_getattr(lhs_type, "__rsub__"
  15.         except AttributeError: 
  16.             lhs_rmethod = _MISSING 
  17.  
  18.         # rhs.__rsub__ 
  19.         rhs_type = type(rhs) 
  20.         try: 
  21.             rhs_method = debuiltins._mro_getattr(rhs_type, "__rsub__"
  22.         except AttributeError: 
  23.             rhs_method = _MISSING 
  24.  
  25.         call_lhs = lhs, lhs_method, rhs 
  26.         call_rhs = rhs, rhs_method, lhs 
  27.  
  28.         if lhs_type is not rhs_type: 
  29.             calls = call_lhs, call_rhs 
  30.         else
  31.             calls = (call_lhs,) 
  32.  
  33.         for first_obj, meth, second_obj in calls: 
  34.             if meth is _MISSING: 
  35.                 continue 
  36.             value = meth(first_obj, second_obj) 
  37.             if value is not NotImplemented: 
  38.                 return value 
  39.         else
  40.             raise TypeError( 
  41.                 f"unsupported operand type(s) for -: {lhs_type!r} and {rhs_type!r}" 
  42.             ) 

4、子类优先于父类

如果你看一下__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() 判断出的子类。)

  1. # Python中减法的完整实现 
  2. _MISSING = object() 
  3.  
  4. def sub(lhs: Any, rhs: Any, /) -> Any
  5.         # lhs.__sub__ 
  6.         lhs_type = type(lhs) 
  7.         try: 
  8.             lhs_method = debuiltins._mro_getattr(lhs_type, "__sub__"
  9.         except AttributeError: 
  10.             lhs_method = _MISSING 
  11.  
  12.         # lhs.__rsub__ (for knowing if rhs.__rub__ should be called first
  13.         try: 
  14.             lhs_rmethod = debuiltins._mro_getattr(lhs_type, "__rsub__"
  15.         except AttributeError: 
  16.             lhs_rmethod = _MISSING 
  17.  
  18.         # rhs.__rsub__ 
  19.         rhs_type = type(rhs) 
  20.         try: 
  21.             rhs_method = debuiltins._mro_getattr(rhs_type, "__rsub__"
  22.         except AttributeError: 
  23.             rhs_method = _MISSING 
  24.  
  25.         call_lhs = lhs, lhs_method, rhs 
  26.         call_rhs = rhs, rhs_method, lhs 
  27.  
  28.         if ( 
  29.             rhs_type is not _MISSING  # Do we care? 
  30.             and rhs_type is not lhs_type  # Could RHS be a subclass? 
  31.             and issubclass(rhs_type, lhs_type)  # RHS is a subclass! 
  32.             and lhs_rmethod is not rhs_method  # Is __r*__ actually different? 
  33.         ): 
  34.             calls = call_rhs, call_lhs 
  35.         elif lhs_type is not rhs_type: 
  36.             calls = call_lhs, call_rhs 
  37.         else
  38.             calls = (call_lhs,) 
  39.  
  40.         for first_obj, meth, second_obj in calls: 
  41.             if meth is _MISSING: 
  42.                 continue 
  43.             value = meth(first_obj, second_obj) 
  44.             if value is not NotImplemented: 
  45.                 return value 
  46.         else
  47.             raise TypeError( 
  48.                 f"unsupported operand type(s) for -: {lhs_type!r} and {rhs_type!r}" 
  49.             ) 

推广到其它二元运算

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

所以,如果我们可以推广这种方法,那么我们就可以实现 13 种操作的语义:+ 、-、*、@、/、//、%、**、<<、>>、&、^、和 |。

由于闭包和 Python 在对象自省上的灵活性,我们可以提炼出 operator 函数的创建。

  1. # 一个创建闭包的函数,实现了二元运算的逻辑 
  2. _MISSING = object() 
  3.  
  4.  
  5. def _create_binary_op(name: str, operator: str) -> Any
  6.     """Create a binary operation function
  7.  
  8.     The `name` parameter specifies the name of the special method used for the 
  9.     binary operation (e.g. `sub` for `__sub__`). The `operator` name is the 
  10.     token representing the binary operation (e.g. `-` for subtraction). 
  11.  
  12.     ""
  13.  
  14.     lhs_method_name = f"__{name}__" 
  15.  
  16.     def binary_op(lhs: Any, rhs: Any, /) -> Any
  17.         """A closure implementing a binary operation in Python.""" 
  18.         rhs_method_name = f"__r{name}__" 
  19.  
  20.         # lhs.__*__ 
  21.         lhs_type = type(lhs) 
  22.         try: 
  23.             lhs_method = debuiltins._mro_getattr(lhs_type, lhs_method_name) 
  24.         except AttributeError: 
  25.             lhs_method = _MISSING 
  26.  
  27.         # lhs.__r*__ (for knowing if rhs.__r*__ should be called first
  28.         try: 
  29.             lhs_rmethod = debuiltins._mro_getattr(lhs_type, rhs_method_name) 
  30.         except AttributeError: 
  31.             lhs_rmethod = _MISSING 
  32.  
  33.         # rhs.__r*__ 
  34.         rhs_type = type(rhs) 
  35.         try: 
  36.             rhs_method = debuiltins._mro_getattr(rhs_type, rhs_method_name) 
  37.         except AttributeError: 
  38.             rhs_method = _MISSING 
  39.  
  40.         call_lhs = lhs, lhs_method, rhs 
  41.         call_rhs = rhs, rhs_method, lhs 
  42.  
  43.         if ( 
  44.             rhs_type is not _MISSING  # Do we care? 
  45.             and rhs_type is not lhs_type  # Could RHS be a subclass? 
  46.             and issubclass(rhs_type, lhs_type)  # RHS is a subclass! 
  47.             and lhs_rmethod is not rhs_method  # Is __r*__ actually different? 
  48.         ): 
  49.             calls = call_rhs, call_lhs 
  50.         elif lhs_type is not rhs_type: 
  51.             calls = call_lhs, call_rhs 
  52.         else
  53.             calls = (call_lhs,) 
  54.  
  55.         for first_obj, meth, second_obj in calls: 
  56.             if meth is _MISSING: 
  57.                 continue 
  58.             value = meth(first_obj, second_obj) 
  59.             if value is not NotImplemented: 
  60.                 return value 
  61.         else
  62.             exc = TypeError( 
  63.                 f"unsupported operand type(s) for {operator}: {lhs_type!r} and {rhs_type!r}" 
  64.             ) 
  65.             exc._binary_op = operator 
  66.             raise exc 

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

更多信息

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

更正2020-08-19:修复了当__rsub__() 比 __sub__() 先调用时的规则。

2020-08-22:修复了当类型相同时不调用__rsub__ 的问题;还精简了过渡代码,仅保留开头和结尾代码,这让我轻松些。

 

2020-08-23:在多数示例中添加了内容。

原题 | Unravelling binary arithmetic operations in Python

作者 | Brett Cannon

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

 

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

本文转载自微信公众号「 Python猫」,可以通过以下二维码关注。转载本文请联系 Python猫公众号。

 

责任编辑:武晓燕 来源: Python猫
相关推荐

2016-10-14 14:04:34

JAVA语法main

2010-03-09 11:15:28

Python语言教程

2016-06-02 15:10:12

SwiftSelector

2022-10-08 06:38:01

元宇宙NFT加密货币

2022-02-14 08:04:02

Go语法糖编译器

2020-12-08 07:51:53

Java语法糖泛型

2022-04-10 22:59:51

区块链元宇宙技术

2012-01-05 10:31:17

Kindle Fire

2009-06-02 17:05:19

网管运维管理摩卡软件

2020-07-22 08:01:41

Python开发运算符

2024-03-15 08:45:31

Vue 3setup语法

2023-04-03 11:21:29

PythonGoRust

2022-05-20 11:41:00

数据科学编程语言Python

2020-12-20 17:37:38

Java开发代码

2011-11-08 09:18:42

云计算开源OpenStack

2021-01-06 10:51:39

云计算云服务IT

2020-07-03 14:05:26

Serverless云服务商

2022-03-14 08:33:09

TypeScriptJavaScript前端

2021-11-29 18:27:12

Web Wasmjs

2022-06-01 16:13:51

元宇宙
点赞
收藏

51CTO技术栈公众号