您好,欢迎访问一九零五行业门户网

详解增强算术赋值“-=”操作

相关学习推荐:python教程
序言本文是 python语法糖 系列文章之一。最新的源代码可以在 desugar 项目中找到(github.com/brettcannon…
介绍python 有一种叫做增强算术赋值(augmented arithmetic assignment)的东西。可能你不熟悉这个叫法,其实就是在做数学运算的同时进行赋值,例如 a -= b 就是减法的增强算术赋值。
增强赋值是在 python 2.0 版本中 加入进来的。(译注:在 pep-203 中引入)
剖析-=因为 python 不允许覆盖式赋值,所以相比其它有特殊/魔术方法的操作,它实现增强赋值的方式可能跟你想象的不完全一样。
首先,要知道a -= b在语义上与 a = a-b 相同。但也要意识到,如果你预先知道要将一个对象赋给一个变量名,相比a - b 的盲操作,就可能会更高效。
例如,最起码的好处是可以避免创建一个新对象:如果可以就地修改一个对象,那么返回 self,就比重新构造一个新对象要高效。
因此,python 提供了一个__isub__() 方法。如果它被定义在赋值操作的左侧(通常称为 lvalue),则会调用右侧的值(通常称为 rvalue )。所以对于a -= b ,就会尝试去调用 a.__isub__(b)。
如果调用的结果是 notimplemented,或者根本不存在结果,那么 python 会退回到常规的二元算术运算:a - b。(译注:作者关于二元运算的文章,译文在此)
最终无论用了哪种方法,返回值都会被赋值给 a。
下面是简单的伪代码,a -= b 被分解成:
# 实现 a -= b 的伪代码if hasattr(a, "__isub__"): _value = a.__isub__(b) if _value is not notimplemented: a = _value else: a = a - b del _value else: a = a - b复制代码
归纳这些方法由于我们已经实现了二元算术运算,因此归纳增强算术运算并不太复杂。
通过传入二元算术运算函数,并做一些自省(以及处理可能发生的 typeerror),它可以被漂亮地归纳成:
def _create_binary_inplace_op(binary_op: _binaryop) -> callable[[any, any], any]: binary_operation_name = binary_op.__name__[2:-2] method_name = f"__i{binary_operation_name}__" operator = f"{binary_op._operator}=" def binary_inplace_op(lvalue: any, rvalue: any, /) -> any: lvalue_type = type(lvalue) try: method = debuiltins._mro_getattr(lvalue_type, method_name) except attributeerror: pass else: value = method(lvalue, rvalue) if value is not notimplemented: return value try: return binary_op(lvalue, rvalue) except typeerror as exc: # if the typeerror is due to the binary arithmetic operator, suppress # it so we can raise the appropriate one for the agumented assignment. if exc._binary_op != binary_op._operator: raise raise typeerror( f"unsupported operand type(s) for {operator}: {lvalue_type!r} and {type(rvalue)!r}" ) binary_inplace_op.__name__ = binary_inplace_op.__qualname__ = method_name binary_inplace_op.__doc__ = ( f"""implement the augmented arithmetic assignment `a {operator} b`.""" ) return binary_inplace_op复制代码
这使得定义的 -= 支持 _create_binary_inplace_op(__ sub__),且可以推断出其它内容:函数名、调用什么 __i*__ 函数,以及当二元算术运算出问题时,该调用哪个可调用对象。
我发现几乎没有人使用**=在写本文的代码时,我碰上了 **= 的一个奇怪的测试错误。在所有确保 __pow__ 会被适当地调用的测试中,有个测试用例对于 python 标准库中的operator 模块却是失败。
我的代码通常没问题,如果代码与 cpython 的代码之间存在差异,通常会意味着是我哪里出错了。
但是,无论我多么仔细地排查代码,我都无法定位出为什么我的测试会通过,而标准库则失败。
我决定深入地了解 cpython 内部发生了什么。从反汇编字节码开始:
>>> def test(): a **= b... >>> import dis>>> dis.dis(test) 1 0 load_fast 0 (a) 2 load_global 0 (b) 4 inplace_power 6 store_fast 0 (a) 8 load_const 0 (none) 10 return_value复制代码
通过它,我找到了在 eval 循环中的inplace_power:
case target(inplace_power): { pyobject *exp = pop(); pyobject *base = top(); pyobject *res = pynumber_inplacepower(base, exp, py_none); py_decref(base); py_decref(exp); set_top(res); if (res == null) goto error; dispatch(); }复制代码
出处:github.com/python/cpyt…
然后找到pynumber_inplacepower():
pyobject *pynumber_inplacepower(pyobject *v, pyobject *w, pyobject *z){ if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_inplace_power != null) { return ternary_op(v, w, z, nb_slot(nb_inplace_power), "**="); } else { return ternary_op(v, w, z, nb_slot(nb_power), "**="); }}复制代码
出处:github.com/python/cpyt…
松了口气~代码显示如果定义了__ipow__,则会调用它,但是只在没有__ipow__ 时,才会调用__pow__。
然而,正确的做法应该是:如果调用__ipow__ 时出问题,返回了 notimplemented 或者根本不存在返回,那么就应该调用 __pow__ 和__rpow__。
换句话说,当存在__ipow__ 时,以上代码会意外地跳过 a**b 的后备语义!
实际上,大约11个月前,这个问题被部分地发现,并提交了 bug。我修复了该问题,并在 python-dev 上作了说明。
截至目前,这似乎会在 python 3.10 中修复,我们还需要在 3.8 和 3.9 的文档中添加关于 **= 有 bug 的通知(该问题可能很早就有了,但较旧的 python 版本已处于仅安全维护模式,因此文档不会变更)。
修复的代码很可能不会被移植,因为它是语义上的变化,并且很难判断是否有人意外地依赖了有问题的语义。但是这个问题花了很长时间才被注意到,这就表明 **= 的使用并不广泛,否则问题早就被发现了。
想了解更多编程学习,敬请关注php培训栏目!
以上就是详解增强算术赋值“-=”操作的详细内容。
其它类似信息

推荐信息