【问题标题】:Is it pythonic for a function to call itself in its error handling?一个函数在其错误处理中调用自己是pythonic吗?
【发布时间】:2019-05-03 12:31:43
【问题描述】:

我有一个场景,如果满足某个条件,函数会在错误处理期间调用自身。比如:

def test(param):
    # code
    try:
        # attempt
    except ValueError as e:
        if (x):
            test(param+1)

我注意到,如果我陷入excepts 的循环中并尝试用我的键盘取消,我会得到一个巨大的堆栈跟踪。这似乎不对。

有没有更好的方法来处理这个问题?

编辑:

运行了一段时间后,我得到了:

RecursionError: maximum recursion depth exceeded while calling a Python object

我不确定这是否相关,但我想递归函数调用过多会导致递归深度问题?

【问题讨论】:

  • 递归总是有替代方案。比如显式的while 循环。
  • @khelwood:...在 Python 中。 :)
  • I am not sure it is related, but I would imagine a recursion depth issue would arise from too many recursive function calls?
  • @khelwood 然后你会在那里扔一面旗帜,然后while !flag 做我想做的事吗?如果代码通过try 中的尝试,则提高标志以退出循环?
  • 正如您所发现的,如果这可能多次出现,那么递归在 CPython 中就不会很好地工作。您可以增加递归深度,但最终会遇到内存错误(无尾调用优化)。只需使用一个while循环。

标签: python python-3.x error-handling


【解决方案1】:

这是在失败时重复操作的一种方法,无需使用递归。

def dostuff(param):
    while True:
        # code
        try:
            # attempt
        except ValueError:
            if x:
                param += 1
                continue
        break 

这样,如果attempt 成功,循环就会中断。但如果它引发了ValueError,并且如果您的x 条件(无论是什么)为真,那么循环的主体将重复param 递增1。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 2019-09-24
    • 2011-10-02
    • 2014-09-01
    • 1970-01-01
    相关资源
    最近更新 更多