pure function是一个函数,它的返回值对于相同的参数是相同的,并且没有任何副作用。
CPython是否意识到返回值将是相同的,并只对函数调用一次进行优化?如果没有,其他python解释器会这样做吗?
下面我用os.path.join写了一个例子,假设它是一个纯函数(我实际上不知道它的实现),但是这个问题扩展到了所有纯函数。
dirpath = "C:\\Users"
dirname = "Username"
mylist = [["another\\directory", 6], ["C:\\Users\\Username", 8], ["foo\\bar", 3]]
count = 0
for pair in mylist:
if os.path.join(dirpath, dirname) == pair[0]:
count = pair[1]dirpath和dirname在for循环中不会被修改。给定相同的输入,os.path.join总是有相同的返回值。
发布于 2020-04-21 18:29:27
标准的python实现几乎没有对用户代码进行任何优化。
但是,您可以在纯函数上使用lru cache装饰器来获得您想要的功能。
from functools import lru_cache
def fib(n):
"""
Calculate the n'th fibanaci number
With O(N^2) <quadratic> runtime
"""
if n < 2: return n
return fib(n-1) + fib(n-2)
@lru_cache
def fib2(n):
"""
Calculate the n'th fibanaci number
With O(N) <linear> runtime
"""
if n < 2: return n
return fib2(n-1) + fib2(n-2)发布于 2020-04-21 18:46:14
严格地说,Python没有纯函数。在任何时候修改函数的含义都是定义明确的。
>>> def add(a, b): return a + b
>>> def sub(a, b): return a - b
>>> add(10, 5)
15
>>> add.__code__ = sub.__code__
>>> add(10, 5)
5此外,还可以更改函数访问的builtins、globals和闭包。
参考实现CPython不会基于函数的纯度进行优化。
实现PyPy使用了一个跟踪JIT,即capable of pure optimisations。请注意,这适用于低级操作(不一定是整个函数),并且仅适用于常用代码。
https://stackoverflow.com/questions/61341111
复制相似问题