python2 与 python3 raise 语句

标签 python python-3.x exception flask raise

在 flask 文档中有一个钩子(Hook)函数的示例,当没有找到 flask 定义的 url 端点时,它允许通过调用为 url_for 函数添加自定义行为。如果也没有匹配的用户定义的 url 端点,程序员可以添加自定义端点或重新引发异常(使用原始上下文)。

def external_url_handler(error, endpoint, values):
    "Looks up an external URL when `url_for` cannot build a URL."
    # This is an example of hooking the build_error_handler.
    # Here, lookup_url is some utility function you've built
    # which looks up the endpoint in some external URL registry.
    url = lookup_url(endpoint, **values)
    if url is None:
        # External lookup did not have a URL.
        # Re-raise the BuildError, in context of original traceback.
        exc_type, exc_value, tb = sys.exc_info()
        if exc_value is error:
            raise exc_type, exc_value, tb
        else:
            raise error
    # url_for will use this result, instead of raising BuildError.
    return url

app.url_build_error_handlers.append(external_url_handler)

此代码片段似乎是 python2 代码,但由于 raise exc_type, exc_value, tb 行而无法用于 python3。 python2python3文档列出了 raise 语句的不同参数。

将此代码段转换为 python3 的正确方法是什么?

最佳答案

这在 the raise statement 的文档中指定:

You can create an exception and set your own traceback in one step using the with_traceback() exception method (which returns the same exception instance, with its traceback set to its argument), like so:

raise Exception("foo occurred").with_traceback(tracebackobj)

因此,在您的情况下,这将是:

raise exc_type(exc_value).with_traceback(tb) 

关于python2 与 python3 raise 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45404867/

相关文章:

python - 独立 Django ORM - 无法识别默认设置

python - 从 Excel 填充 QTableWidget

arrays - 我做错了什么? (python/数组声明)

Python 尝试 block 大小

java - 如何内联抛出异常的方法?

python - 如何在pandas dataframe Python中找到GPS坐标之间的角度

python - 使用 cx_freeze 和 bdist_msi 为 PySide 应用程序创建 MSI

java - 以编程方式区分异常

python-3.x - python 3.x 导入错误 : No module named 'cStringIO'

python - 即时解压缩下载的 gzip 内容