Movatterモバイル変換


[0]ホーム

URL:


Following system colour schemeSelected dark colour schemeSelected light colour scheme

Python Enhancement Proposals

PEP 341 – Unifying try-except and try-finally

Author:
Georg Brandl <georg at python.org>
Status:
Final
Type:
Standards Track
Created:
04-May-2005
Python-Version:
2.5
Post-History:


Table of Contents

Abstract

This PEP proposes a change in the syntax and semantics of trystatements to allow combined try-except-finally blocks. Thismeans in short that it would be valid to write:

try:<dosomething>exceptException:<handletheerror>finally:<cleanup>

Rationale/Proposal

There are many use cases for the try-except statement andfor the try-finally statement per se; however, often one needsto catch exceptions and execute some cleanup code afterwards.It is slightly annoying and not very intelligible thatone has to write:

f=Nonetry:try:f=open(filename)text=f.read()exceptIOError:print'An error occurred'finally:iff:f.close()

So it is proposed that a construction like this:

try:<suite1>exceptEx1:<suite2><moreexcept:clauses>else:<suite3>finally:<suite4>

be exactly the same as the legacy:

try:try:<suite1>exceptEx1:<suite2><moreexcept:clauses>else:<suite3>finally:<suite4>

This is backwards compatible, and every try statement that islegal today would continue to work.

Changes to the grammar

The grammar for the try statement, which is currently:

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

would have to become:

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

Implementation

As the PEP author currently does not have sufficient knowledgeof the CPython implementation, he is unfortunately not ableto deliver one. Thomas Lee has submitted a patch[2].

However, according to Guido, it should be a piece of cake toimplement[1] – at least for a core hacker.

This patch was committed 17 December 2005, SVN revision 41740[3].

References

[1]
https://mail.python.org/pipermail/python-dev/2005-May/053319.html
[2]
https://bugs.python.org/issue1355913
[3]
https://mail.python.org/pipermail/python-checkins/2005-December/048457.html

Copyright

This document has been placed in the public domain.


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

Last modified:2025-02-01 08:59:27 GMT


[8]ページ先頭

©2009-2025 Movatter.jp