回调的天真实现:如何阻止堆栈增长?

2024-09-27 04:29:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚了解了回调的概念,我决定尝试实现自己的回调。我的努力是卓有成效的,我确实设法模拟了回调的功能。不幸的是,我注意到我的实现导致堆栈每周期增加2个函数调用,我假设,如果代码运行足够长的时间,最终会导致堆栈溢出

我想知道,如何实现这段代码来防止堆栈在每个循环中增长?或者这是实施的必然产物,在这种情况下,如何规避这个问题

import time
import inspect 

def doSomething(x):
    return x + 0.00000001

def continue_processing(runningTotal,termination_condition,callback,callback_args,timeout=5):
    startTime = time.time()
    while (time.time() - startTime < timeout and not(termination_condition(runningTotal))):
        runningTotal = doSomething(runningTotal)

    print(f"Returning control to calling function, running total is {runningTotal}")
    return callback(runningTotal,*callback_args)

def process(runningTotal,n,beginTime):

    if(runningTotal < n):
        print(f"Continue processing, running total is {runningTotal}\nTime elapsed {time.time() - beginTime}\nCurrent stack size: {len(inspect.stack())}")
        continue_processing(runningTotal,lambda x: x>n,process,(n,beginTime))

if __name__ == '__main__':

    beginTime = time.time()
    try:
        process(0,1,beginTime)
    except KeyboardInterrupt:
        print("Program interrupted!")
        exit(0)
    print(f"Completed in {time.time() - beginTime}"

Tags: importreturntime堆栈defcallbackprocessprint
1条回答
网友
1楼 · 发布于 2024-09-27 04:29:42

问题是回调是递归的,它(间接地)调用自己——这就是堆栈溢出的原因。下面是如何避免这种情况。注意,我还修改了您的代码,使之符合PEP 8 - Style Guide for Python Code准则,使其更具可读性。我强烈建议你阅读和遵循它,特别是如果你只是学习语言

import time
import inspect


def doSomething(x):
    return x + 0.00000001

def continue_processing(runningTotal, termination_condition, timeout=5):
    startTime = time.time()
    while (time.time() - startTime < timeout
            and not(termination_condition(runningTotal))):
        runningTotal = doSomething(runningTotal)

    print(f"Returning control to calling function, running total is "
          f"{runningTotal}")

    # Don't call back the callback
    #return callback(runningTotal, *callback_args)

def process(runningTotal, n, beginTime):
    while runningTotal < n:
        print(f"Continue processing, running total is {runningTotal}\n"
              f"Time elapsed {time.time() - beginTime}\n"
              f"Current stack size: {len(inspect.stack())}")
        continue_processing(runningTotal, lambda x: x>n)


if __name__ == '__main__':

    beginTime = time.time()
    try:
        process(0, 1, beginTime)
    except KeyboardInterrupt:
        print("Program interrupted!")
        exit(0)
    print(f"Completed in {time.time() - beginTime}")

相关问题 更多 >

    热门问题