Is there a practical noticeable speed-up (that could balance the inconvenience of the larger function signature)?
我非常怀疑它,因为查找在原始定义中每次都发生一次.请注意,您已更改了该功能的含义.
In which specific conditions the use of local variables in a case as the one shown would be relevant?
只在紧密的循环内;在这种情况下,如果dot_product用于表示非常大的矩阵乘法(无论如何你都不会在纯Python中做,更不用说迭代器了).
编辑:我刚刚拆开了这两个功能,但我的预感是错误的,尽管我的观点仍然存在:
>>> def dotproduct(vec1, vec2):
... return sum(imap(operator.mul, vec1, vec2))
...
>>> dis.dis(dotproduct)
2 0 LOAD_GLOBAL 0 (sum)
3 LOAD_GLOBAL 1 (imap)
6 LOAD_GLOBAL 2 (operator)
9 LOAD_ATTR 3 (mul)
12 LOAD_FAST 0 (vec1)
15 LOAD_FAST 1 (vec2)
18 CALL_FUNCTION 3
21 CALL_FUNCTION 1
24 RETURN_VALUE
>>> def dotproduct(vec1, vec2, sum=sum, imap=imap, mul=operator.mul):
... return sum(imap(mul, vec1, vec2))
...
>>> dis.dis(dotproduct)
2 0 LOAD_FAST 2 (sum)
3 LOAD_FAST 3 (imap)
6 LOAD_FAST 4 (mul)
9 LOAD_FAST 0 (vec1)
12 LOAD_FAST 1 (vec2)
15 CALL_FUNCTION 3
18 CALL_FUNCTION 1
21 RETURN_VALUE
python局部变量屏蔽全局变量_python – 将局部变量设置为函数而不是使用全局变量来优化函数...
如果觉得《python局部变量屏蔽全局变量_python – 将局部变量设置为函数而不是使用全局变量来》对你有帮助,请点赞、收藏,并留下你的观点哦!