如何不使用链式比较实现a() < b() < c()的等价逻辑?
等价实现链式比较的替代方案问题
本文灵感源于AEC转WebAssembly编译器的相关问题。Python中,a() < b() and b() < c()这种写法和链式比较a() < b() < c()并不等价,因为前者会调用两次b()。而采用变量存储的方式:
_a = a() _b = b() _a < _b and _b < c()
也并非完全等价——a()的返回值会存活到第二次比较之后,可能引发问题。
通过日志对比三种实现的执行过程如下:
chained: a() b() (3 4) del c() (3 3) del del simple_and: a() b() (3 3) del del b() c() (3 3) del del variables: a() b() (4 4) c() (4 3) del del del
(注:del记录函数返回对象的“销毁”,括号内的数字对表示比较时两个对象的引用计数)
请问是否存在不使用链式比较的等价实现方式?
测试脚本
def chained(): return a() < b() < c() def simple_and(): return a() < b() and b() < c() def variables(): _a = a() _b = b() return _a < _b and _b < c() import sys class X: def __lt__(self, other): print(end=f'({sys.getrefcount(self)} {sys.getrefcount(other)}) ') return True def __del__(self): print(end='del ') def a(): print(end='a() '); return X() def b(): print(end='b() '); return X() def c(): print(end='c() '); return X() for f in chained, simple_and, variables: print(f.__name__ + ':') f() print('\n')
内容的提问来源于stack exchange,提问作者no comment
相关产品推荐
相关产品推荐

