Skip to Content
Effective Python 第3版 ―Pythonプログラムを改良する125項目
book

Effective Python 第3版 ―Pythonプログラムを改良する125項目

by Brett Slatkin, 鈴木 駿
October 2025
Intermediate to advanced
572 pages
7h 46m
Japanese
O'Reilly Japan, Inc.
Content preview from Effective Python 第3版 ―Pythonプログラムを改良する125項目

10章ロバストネス

役に立つPythonコードの大半は、特定の問題をその場しのぎで解決するための使い捨てスクリプトから始まります。このようなスクリプトは拡張や転用、再利用を重ねるうちに、その場しのぎの使い捨てコードから、長期的に保守する価値のあるプログラムへと進化していきます。

有用なPythonプログラムを書いた後の重要なステップは、そのコードを本番環境向けにブラッシュアップして盤石な品質に仕上げることです。予期せぬ事態に直面した際にもプログラムが確実に動作するようにすることは、プログラムが正しい機能を持つのと同じぐらい重要です。Pythonにはプログラムのロバストネスを高めて、さまざまな状況に対応できるようにする機能やモジュールが用意されています。

項目80 try/except/else/finallyブロックを使う

Pythonの例外処理において、何らかのアクションを実行する場所としてtryexceptelsefinallyの各ブロックがあります。各ブロックはそれぞれ異なる目的があり、目的に応じてブロックを組み合わせて使います([項目121]参照)。

try/finally

try/finallyは、発生した例外をそのまま送出しつつ、例外が発生した場合でもクリーンアップ処理を実行したい場合に使います。try/finallyの典型的な例は、ファイルオブジェクトを確実に閉じる処理です([項目82]参照)。

def try_finally_example(filename): print("* Opening file") handle = open(filename, encoding="utf-8") # OSErrorが発生しうる try: print("* Reading ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

Think Python 第3版 ―コンピュータ科学者の思考で問題を解決する

Think Python 第3版 ―コンピュータ科学者の思考で問題を解決する

Allen B. Downey, 大橋 真也
入門 Python 3 第2版

入門 Python 3 第2版

Bill Lubanovic, 鈴木 駿, 長尾 高弘

Publisher Resources

ISBN: 9784814401338Publisher Website