Following system colour scheme - Python 增强提案 Selected dark colour scheme - Python 增强提案 Selected light colour scheme - Python 增强提案

Python 增强提案

PEP 341 – 统一 try-except 和 try-finally

作者:
Georg Brandl <georg at python.org>
状态:
最终版
类型:
标准跟踪
创建日期:
2005年5月4日
Python 版本:
2.5
发布历史:


目录

摘要

本PEP提议更改try语句的语法和语义,以允许组合的try-except-finally块。简而言之,这意味着以下写法将是有效的:

try:
    <do something>
except Exception:
    <handle the error>
finally:
    <cleanup>

基本原理/提议

try-except语句和try-finally语句本身都有许多用例;然而,通常需要捕获异常并在之后执行一些清理代码。必须写成这样有点恼人且不易理解:

f = None
try:
    try:
        f = open(filename)
        text = f.read()
    except IOError:
        print 'An error occurred'
finally:
    if f:
        f.close()

因此,提议以下构造

try:
    <suite 1>
except Ex1:
    <suite 2>
<more except: clauses>
else:
    <suite 3>
finally:
    <suite 4>

与旧式写法完全相同:

try:
    try:
        <suite 1>
    except Ex1:
        <suite 2>
    <more except: clauses>
    else:
        <suite 3>
finally:
    <suite 4>

这是向后兼容的,今天合法的每个try语句都将继续有效。

对语法的更改

try语句的语法,目前是

try_stmt: ('try' ':' suite (except_clause ':' suite)+
        ['else' ':' suite] | 'try' ':' suite 'finally' ':' suite)

将不得不变成

try_stmt: 'try' ':' suite
        (
            (except_clause ':' suite)+
            ['else' ':' suite]
            ['finally' ':' suite]
        |
            'finally' ':' suite
        )

实施

由于PEP作者目前对CPython实现没有足够的了解,因此他很遗憾无法提供一个。Thomas Lee已提交了一个补丁 [2]

然而,根据Guido的说法,实现起来应该是一件轻而易举的事 [1] – 至少对于核心开发者来说。

此补丁于2005年12月17日提交,SVN版本41740 [3]

参考资料


来源:https://github.com/python/peps/blob/main/peps/pep-0341.rst

最后修改:2025-02-01 08:59:27 GMT