python2 与 python3 raise 语句
python2 vs. python3 raise statement
在 flask 文档中有一个钩子函数的示例,当没有找到 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。
python2 and python3 文档列出了 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)
在 flask 文档中有一个钩子函数的示例,当没有找到 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。
python2 and python3 文档列出了 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)