中学数学623755 views
りんご209490 views
小学算数1200427 views
LaTeX962153 views
雑学1473612 views
中学英語811710 views
Computer368106 views
高校国語788336 views
中学理科1630641 views
世界の国564520 views
Help
Tools
NewsSpreadsheetCalendarSlidesTier ListPen ToolIllustrationCrayonPixel ArtASCII ArtPerspectiveEndless StairsGraphMind MapER DiagramFamily TreeMemeCurved TextImage EditorMosaicRetro FilterPencil SketchSwirl EffectOCR/HighlighterMakeup EditorFaviconVideo TrimmerScrolling VideoVideo TitleColor PickerColor ExtractorBonfireFireworksWater RippleWater SplashBreaking GlassWood GrainMarble TextureCSS ButtonIcon MakerBar ChartGrouped Bar ChartStacked Bar ChartPie ChartLine ChartArea ChartStacked Area ChartScatter Plot3D Bar Chart3D Pie ChartBar Chart RaceBubble ChartPopulation PyramidPictogramEarningsCandlestick ChartInvestment RiskMortgage SimulatorCalculatorMatrix CalculatorFunction GraphPolynomial ExpansionVenn DiagramField VisualizerRubik's Cube Group TheoryTraveling SalesmanVoronoi and DelaunayFractalColumn ArithmeticDraw Math FiguresArithmetic AnimationArithmetic Word ProblemsCounting with Tree DiagramsCube NetsCross SectionsMotion PathMechanicsWavesElectromagnetic WavesLight and LensesThermodynamicsHow Semiconductors WorkMolecular StructuresAtomic OrbitalsElectrochemical CellsChemical EquilibriumCrystal LatticesBuffer pHPeriodic TableComplex IonsDNA Double HelixCell DivisionMembrane ChannelsNerve ImpulseMuscle ContractionRock ClassificationWeatherConstellationsSolar and Lunar Eclipses3D ModelingFloor PlanSeismic StructuresIntersection TurnMaglevCooking AnimationOrigamiLive Viewer CountGeoJSON MapRailway MapPopulation MapCrime MapLand Price MapSchool MapShrine and Castle MapHouse of Representatives MapWord MapSolitaireReversiHakoiri MusumeChessHamburgerRippleSlide Puzzle MakerNeon PinballNovel MakerJapanese Typing PracticePiano Score EditorMusic TheoryShogi StrategyPiano Rhythm Game

English

Python の contextlib 入門

contextlib モジュールは、コンテキストマネージャを作成・操作するための便利なツールを提供します。標準ライブラリに含まれており、with 文をより効果的に活用できます。

モジュールの主要な機能

contextlib には以下のような機能があります。

コンテキストマネージャの作成

@contextmanager デコレータでジェネレータから作成。

例外処理

suppress() で特定の例外を無視。

出力のリダイレクト

redirect_stdout / redirect_stderr で出力先を変更。

動的リソース管理

ExitStack で可変個数のリソースを管理。

@contextmanager

ジェネレータ関数からコンテキストマネージャを作成します。

from contextlib import contextmanager

@contextmanager
def tag(name):
    print(f"<{name}>")
    yield
    print(f"</{name}>")

with tag("div"):
    print("コンテンツ")
# <div>
# コンテンツ
# </div>

closing

close() メソッドを持つオブジェクトを with 文で使えるようにします。

from contextlib import closing
from urllib.request import urlopen

with closing(urlopen("https://example.com")) as page:
    content = page.read()

suppress

特定の例外を無視します。

from contextlib import suppress
import os

# FileNotFoundError を無視
with suppress(FileNotFoundError):
    os.remove("存在しないファイル.txt")

print("処理継続")  # 例外が発生しても続行

redirect_stdout / redirect_stderr

標準出力・標準エラー出力をリダイレクトします。

from contextlib import redirect_stdout
import io

f = io.StringIO()
with redirect_stdout(f):
    print("キャプチャされる出力")

output = f.getvalue()
print(f"キャプチャ結果: {output}")

nullcontext

何もしないコンテキストマネージャです。条件分岐で使えます。

from contextlib import nullcontext

def process(use_lock=True):
    lock = Lock() if use_lock else nullcontext()
    with lock:
        print("処理中")

ExitStack

動的に複数のコンテキストマネージャを管理します。

from contextlib import ExitStack

with ExitStack() as stack:
    files = [stack.enter_context(open(f"file{i}.txt", "w")) 
             for i in range(3)]
    for f in files:
        f.write("test")
# すべてのファイルが自動で閉じられる

chdir(Python 3.11以降)

カレントディレクトリを一時的に変更します。

from contextlib import chdir  # Python 3.11+

with chdir("/tmp"):
    print(os.getcwd())  # /tmp
# 元のディレクトリに戻る

主な関数一覧

関数用途
@contextmanagerジェネレータからCMを作成
closingclose()を自動呼び出し
suppress例外を無視
redirect_stdout標準出力をリダイレクト
nullcontext何もしないCM
ExitStack動的リソース管理

contextlib を活用することで、リソース管理のコードをより簡潔に書けます。