Skip to Content
Fluent Python 第2版 ―Pythonicな思考とコーディング手法
book

Fluent Python 第2版 ―Pythonicな思考とコーディング手法

by Luciano Ramalho, 牧野 聡
November 2025
Intermediate to advanced
984 pages
16h 17m
Japanese
O'Reilly Japan, Inc.
Content preview from Fluent Python 第2版 ―Pythonicな思考とコーディング手法

18章with、match、elseのブロック

コンテキストマネージャは今や、サブルーチン自体と同じくらい重要になってきています。我々はコンテキストマネージャの表層しか見てこなかったのです。(中略)BASIC言語にもwith文はあり、その他の多くの言語もwith文を備えています。しかし、そのはたらきは言語ごとに異なり、いずれも底の浅い処理しか行ってはくれません。属性へのアクセスの際にドットを何度も書かずに済む程度で、初期化や最終処理は行われません。Pythonでのwithはとても広範な概念であり、たまたま同じ名前だからといって処理内容も同じだと考えるのは危険です†1

—— Raymond Hettinger

雄弁なPythonエバンジェリスト

[†1] PyCon US 2013の基調講演『What Makes Python Awesome』(https://fpy.li/18-1)より。with文については23分00秒から26分15秒の間に言及されています。

この章では、他の言語ではあまり見られず、それゆえにPythonでも見過ごされることの多い制御構造について解説します。具体的には以下の3つを取り上げます。

  • with文とコンテキストマネージャのプロトコル
  • match/caseを使ったパターンマッチング
  • for文、while文、try文でのelse

with文を使うと一時的なコンテキストが用意され、最終的には適切に破棄されます。コンテキストはコンテキストマネージャの管理下に置かれます。エラーの防止や、定型的に繰り返されるコードの削減を期待でき、APIを安全かつ容易に利用できるようになります。ファイルを自動的に閉じるという目的の他にも、さまざまな用法がプログラマーたちによって考案されています。 ...

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

Fluent Python ―Pythonicな思考とコーディング手法

Fluent Python ―Pythonicな思考とコーディング手法

Luciano Ramalho, 豊沢 聡, 桑井 博之, 梶原 玲子

Publisher Resources

ISBN: 9784814401284Publisher Website