[英]Recursion and Exceptions in Python, how to catch exceptions without losing recursive stack
[英]how to do a recursion without stack overflow in python?
我正在使用 ZODB 數據庫開發一個項目,遇到以下問題:
def balance(db, id, max_sleep, manager=None):
'''to calculate the funds of an account(saving + checking)'''
if manager is None:
transaction = TransactionManager()
else:
transaction = manager
transaction.begin()
try:
name = db['account'][id].getName()
funds = db['saving'][name].balance + db['checking'][name].balance
transaction.commit()
return funds
except Exception:
sleep(randint(0, max_sleep)*(10**-6))
balance(db, id, max_sleep, manager)
我需要遞歸 function 直到交易完成; 我不需要將它們堆疊起來,我嘗試增加更多的睡眠時間但是事務仍然需要遞歸這么多(即使只有 2 個線程。)? 有沒有辦法解決這個問題!?
考慮改用while
循環:
def balance(db, id, max_sleep, manager=None):
'''to calculate the funds of an account(saving + checking)'''
if manager is None:
transaction = TransactionManager()
else:
transaction = manager
while True:
transaction.begin()
try:
name = db['account'][id].getName()
funds = db['saving'][name].balance + db['checking'][name].balance
transaction.commit()
return funds
except Exception:
sleep(randint(0, max_sleep)*(10**-6))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.