<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>manager</title>
	<atom:link href="https://techgrowup.net/tag/manager/feed/" rel="self" type="application/rss+xml" />
	<link>https://techgrowup.net</link>
	<description>エンジニアを強くする</description>
	<lastBuildDate>Sun, 15 Dec 2024 15:11:42 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>

<image>
	<url>https://techgrowup.net/wp-content/uploads/2021/05/hp-icon-150x150.png</url>
	<title>manager</title>
	<link>https://techgrowup.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Python開発入門42 Pythonのコンテキストマネージャーを解説</title>
		<link>https://techgrowup.net/python-context-manager/</link>
					<comments>https://techgrowup.net/python-context-manager/?noamp=mobile#respond</comments>
		
		<dc:creator><![CDATA[techgrowup]]></dc:creator>
		<pubDate>Sun, 15 Dec 2024 15:11:40 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[プログラミング]]></category>
		<category><![CDATA[context]]></category>
		<category><![CDATA[manager]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://techgrowup.net/?p=2212</guid>

					<description><![CDATA[はじめに Pythonでファイルやネットワーク接続などのリソースを扱う際には、適切なリソース管理が重要です。適切に管理されないリソースは、システムに負担をかけたり、予期しないエラーを引き起こす原因となります。 そこで活用 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<h1 class="wp-block-heading"><strong>はじめに</strong></h1>



<p class="wp-block-paragraph">Pythonでファイルやネットワーク接続などのリソースを扱う際には、適切なリソース管理が重要です。適切に管理されないリソースは、システムに負担をかけたり、予期しないエラーを引き起こす原因となります。</p>



<p class="wp-block-paragraph">そこで活用できるのが<strong>コンテキストマネージャー</strong>です。Pythonのコンテキストマネージャーを使うと、リソースの管理を自動化し、コードをシンプルで安全なものにできます。この記事では、コンテキストマネージャーの基本的な使い方からカスタムマネージャーの作成方法までを解説します。</p>



<h2 class="wp-block-heading"><strong>コンテキストマネージャーとは</strong></h2>



<h3 class="wp-block-heading"><strong>概要</strong></h3>



<p class="wp-block-paragraph">コンテキストマネージャーは、<strong>特定のリソースのセットアップとクリーンアップを自動的に処理する仕組み</strong>です。Pythonでは、<code>with</code>文を使ってコンテキストマネージャーを簡単に利用できます。</p>



<h3 class="wp-block-heading"><strong>主な用途</strong></h3>



<ul class="wp-block-list">
<li><strong>ファイル操作</strong><br>ファイルを開いて読み書きし、処理終了後に自動で閉じる。</li>



<li><strong>データベース接続</strong><br>セッションを開始し、終了時に適切にクローズ。</li>



<li><strong>スレッドロック</strong><br>ロックを確保し、使用後に解放。</li>
</ul>



<h2 class="wp-block-heading"><strong>基本的なコンテキストマネージャーの使い方</strong></h2>



<h3 class="wp-block-heading"><strong><code>with</code>文の基本構文</strong></h3>



<p class="wp-block-paragraph">コンテキストマネージャーを使うと、リソースの確保と解放を簡単に管理できます。</p>



<h6 class="wp-block-heading"><strong>例：ファイル操作</strong></h6>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="with open(&quot;example.txt&quot;, &quot;r&quot;) as file:
    content = file.read()
    print(content)
# ファイルは自動的に閉じられる" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">with</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">open</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;example.txt&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;r&quot;</span><span style="color: #D4D4D4">) </span><span style="color: #C586C0">as</span><span style="color: #D4D4D4"> file:</span></span>
<span class="line"><span style="color: #D4D4D4">    content = file.read()</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(content)</span></span>
<span class="line"><span style="color: #6A9955"># ファイルは自動的に閉じられる</span></span></code></pre></div>



<p class="wp-block-paragraph"><strong>説明：</strong></p>



<ul class="wp-block-list">
<li><code>open()</code>でファイルを開きます。</li>



<li><code>with</code>文を使うことで、スコープを抜けた際に自動的に<code>file.close()</code>が呼び出されます。</li>
</ul>



<h3 class="wp-block-heading"><strong><code>with</code>文がない場合の処理</strong></h3>



<p class="wp-block-paragraph">以下は、コンテキストマネージャーを使わないコードの例です。</p>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="file = open(&quot;example.txt&quot;, &quot;r&quot;)
try:
    content = file.read()
    print(content)
finally:
    file.close()" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #D4D4D4">file = </span><span style="color: #DCDCAA">open</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;example.txt&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;r&quot;</span><span style="color: #D4D4D4">)</span></span>
<span class="line"><span style="color: #C586C0">try</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">    content = file.read()</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(content)</span></span>
<span class="line"><span style="color: #C586C0">finally</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">    file.close()</span></span></code></pre></div>



<p class="wp-block-paragraph"><strong>違い：</strong><br><code>with</code>文を使うと、<code>try...finally</code>を明示的に記述する必要がなくなり、コードが簡潔になります。</p>



<h2 class="wp-block-heading"><strong>標準ライブラリでのコンテキストマネージャー</strong></h2>



<p class="wp-block-paragraph">Pythonの標準ライブラリには、便利なコンテキストマネージャーがいくつも用意されています。</p>



<h3 class="wp-block-heading"><strong>ファイル操作</strong></h3>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="with open(&quot;example.txt&quot;, &quot;w&quot;) as file:
    file.write(&quot;Hello, World!&quot;)" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">with</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">open</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;example.txt&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;w&quot;</span><span style="color: #D4D4D4">) </span><span style="color: #C586C0">as</span><span style="color: #D4D4D4"> file:</span></span>
<span class="line"><span style="color: #D4D4D4">    file.write(</span><span style="color: #CE9178">&quot;Hello, World!&quot;</span><span style="color: #D4D4D4">)</span></span></code></pre></div>



<h3 class="wp-block-heading"><strong>ロックの管理</strong></h3>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="from threading import Lock

lock = Lock()

with lock:
    print(&quot;ロック中です&quot;)
# ロックは自動的に解放されます" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">from</span><span style="color: #D4D4D4"> threading </span><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> Lock</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">lock = Lock()</span></span>
<span class="line"></span>
<span class="line"><span style="color: #C586C0">with</span><span style="color: #D4D4D4"> lock:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #CE9178">&quot;ロック中です&quot;</span><span style="color: #D4D4D4">)</span></span>
<span class="line"><span style="color: #6A9955"># ロックは自動的に解放されます</span></span></code></pre></div>



<h3 class="wp-block-heading"><strong>一時ファイルの利用</strong></h3>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="from tempfile import TemporaryFile

with TemporaryFile(&quot;w+t&quot;) as temp:
    temp.write(&quot;一時データ&quot;)
    temp.seek(0)
    print(temp.read())
# 一時ファイルは自動的に削除されます" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">from</span><span style="color: #D4D4D4"> tempfile </span><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> TemporaryFile</span></span>
<span class="line"></span>
<span class="line"><span style="color: #C586C0">with</span><span style="color: #D4D4D4"> TemporaryFile(</span><span style="color: #CE9178">&quot;w+t&quot;</span><span style="color: #D4D4D4">) </span><span style="color: #C586C0">as</span><span style="color: #D4D4D4"> temp:</span></span>
<span class="line"><span style="color: #D4D4D4">    temp.write(</span><span style="color: #CE9178">&quot;一時データ&quot;</span><span style="color: #D4D4D4">)</span></span>
<span class="line"><span style="color: #D4D4D4">    temp.seek(</span><span style="color: #B5CEA8">0</span><span style="color: #D4D4D4">)</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(temp.read())</span></span>
<span class="line"><span style="color: #6A9955"># 一時ファイルは自動的に削除されます</span></span></code></pre></div>



<h2 class="wp-block-heading"><strong>カスタムコンテキストマネージャーの作成</strong></h2>



<h3 class="wp-block-heading"><strong>クラスを使った作成</strong></h3>



<p class="wp-block-paragraph">カスタムコンテキストマネージャーを作るには、<code>__enter__</code>と<code>__exit__</code>メソッドを定義します。</p>



<h6 class="wp-block-heading"><strong>例：タイマーの実装</strong></h6>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="import time

class Timer:
    def __enter__(self):
        self.start = time.time()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.end = time.time()
        print(f&quot;処理時間: {self.end - self.start}秒&quot;)

with Timer():
    for _ in range(1000000):
        pass" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> time</span></span>
<span class="line"></span>
<span class="line"><span style="color: #569CD6">class</span><span style="color: #D4D4D4"> </span><span style="color: #4EC9B0">Timer</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #569CD6">def</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">__enter__</span><span style="color: #D4D4D4">(</span><span style="color: #9CDCFE">self</span><span style="color: #D4D4D4">):</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #569CD6">self</span><span style="color: #D4D4D4">.start = time.time()</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #C586C0">return</span><span style="color: #D4D4D4"> </span><span style="color: #569CD6">self</span></span>
<span class="line"></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #569CD6">def</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">__exit__</span><span style="color: #D4D4D4">(</span><span style="color: #9CDCFE">self</span><span style="color: #D4D4D4">, </span><span style="color: #9CDCFE">exc_type</span><span style="color: #D4D4D4">, </span><span style="color: #9CDCFE">exc_value</span><span style="color: #D4D4D4">, </span><span style="color: #9CDCFE">traceback</span><span style="color: #D4D4D4">):</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #569CD6">self</span><span style="color: #D4D4D4">.end = time.time()</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #DCDCAA">print</span><span style="color: #D4D4D4">(</span><span style="color: #569CD6">f</span><span style="color: #CE9178">&quot;処理時間: </span><span style="color: #569CD6">{self</span><span style="color: #D4D4D4">.end - </span><span style="color: #569CD6">self</span><span style="color: #D4D4D4">.start</span><span style="color: #569CD6">}</span><span style="color: #CE9178">秒&quot;</span><span style="color: #D4D4D4">)</span></span>
<span class="line"></span>
<span class="line"><span style="color: #C586C0">with</span><span style="color: #D4D4D4"> Timer():</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #C586C0">for</span><span style="color: #D4D4D4"> _ </span><span style="color: #C586C0">in</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">range</span><span style="color: #D4D4D4">(</span><span style="color: #B5CEA8">1000000</span><span style="color: #D4D4D4">):</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #C586C0">pass</span></span></code></pre></div>



<p class="wp-block-paragraph"><strong>説明：</strong></p>



<ul class="wp-block-list">
<li><code>__enter__</code>：コンテキストが開始される際の処理を記述します。</li>



<li><code>__exit__</code>：コンテキストを終了する際のクリーンアップ処理を記述します。</li>
</ul>



<h3 class="wp-block-heading"><strong>デコレーターを使った作成</strong></h3>



<p class="wp-block-paragraph">簡易的なカスタムマネージャーを作成するには、<code>contextlib</code>モジュールを使用します。</p>



<h6 class="wp-block-heading"><strong>例：ファイル操作のデコレーター版</strong></h6>



<div class="wp-block-kevinbatdorf-code-block-pro" data-code-block-pro-font-family="Code-Pro-JetBrains-Mono" style="font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)"><span style="display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E"><svg xmlns="http://www.w3.org/2000/svg" width="54" height="14" viewBox="0 0 54 14"><g fill="none" fill-rule="evenodd" transform="translate(1 1)"><circle cx="6" cy="6" r="6" fill="#FF5F56" stroke="#E0443E" stroke-width=".5"></circle><circle cx="26" cy="6" r="6" fill="#FFBD2E" stroke="#DEA123" stroke-width=".5"></circle><circle cx="46" cy="6" r="6" fill="#27C93F" stroke="#1AAB29" stroke-width=".5"></circle></g></svg></span><span role="button" tabindex="0" data-code="from contextlib import contextmanager

@contextmanager
def open_file(path, mode):
    file = open(path, mode)
    try:
        yield file
    finally:
        file.close()

with open_file(&quot;example.txt&quot;, &quot;w&quot;) as file:
    file.write(&quot;デコレーターによるコンテキストマネージャー&quot;)" style="color:#D4D4D4;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki dark-plus" style="background-color: #1E1E1E" tabindex="0"><code><span class="line"><span style="color: #C586C0">from</span><span style="color: #D4D4D4"> contextlib </span><span style="color: #C586C0">import</span><span style="color: #D4D4D4"> contextmanager</span></span>
<span class="line"></span>
<span class="line"><span style="color: #DCDCAA">@contextmanager</span></span>
<span class="line"><span style="color: #569CD6">def</span><span style="color: #D4D4D4"> </span><span style="color: #DCDCAA">open_file</span><span style="color: #D4D4D4">(</span><span style="color: #9CDCFE">path</span><span style="color: #D4D4D4">, </span><span style="color: #9CDCFE">mode</span><span style="color: #D4D4D4">):</span></span>
<span class="line"><span style="color: #D4D4D4">    file = </span><span style="color: #DCDCAA">open</span><span style="color: #D4D4D4">(path, mode)</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #C586C0">try</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">        </span><span style="color: #C586C0">yield</span><span style="color: #D4D4D4"> file</span></span>
<span class="line"><span style="color: #D4D4D4">    </span><span style="color: #C586C0">finally</span><span style="color: #D4D4D4">:</span></span>
<span class="line"><span style="color: #D4D4D4">        file.close()</span></span>
<span class="line"></span>
<span class="line"><span style="color: #C586C0">with</span><span style="color: #D4D4D4"> open_file(</span><span style="color: #CE9178">&quot;example.txt&quot;</span><span style="color: #D4D4D4">, </span><span style="color: #CE9178">&quot;w&quot;</span><span style="color: #D4D4D4">) </span><span style="color: #C586C0">as</span><span style="color: #D4D4D4"> file:</span></span>
<span class="line"><span style="color: #D4D4D4">    file.write(</span><span style="color: #CE9178">&quot;デコレーターによるコンテキストマネージャー&quot;</span><span style="color: #D4D4D4">)</span></span></code></pre></div>



<p class="wp-block-paragraph"><strong>説明：</strong></p>



<ul class="wp-block-list">
<li><code>@contextmanager</code>を使うことで、クラスを使わずにコンテキストマネージャーを簡単に作成できます。</li>



<li><code>yield</code>を使ってリソースを返し、その後にクリーンアップ処理を実行します。</li>
</ul>



<h2 class="wp-block-heading"><strong>コンテキストマネージャーを使う際の注意点</strong></h2>



<ol class="wp-block-list">
<li><strong>例外処理の設計</strong><br><code>__exit__</code>メソッドで例外が発生した場合の処理を記述できます。例えば、例外を無視する場合は<code>True</code>を返します。pythonCopy code<code>def __exit__(self, exc_type, exc_value, traceback): return True # 例外を無視する</code></li>



<li><strong>リソースの明示的な管理</strong><br>コンテキストマネージャーを使用すると、リソース管理が自動化されますが、適切にスコープを設定することが重要です。</li>
</ol>



<h2 class="wp-block-heading"><strong>コンテキストマネージャーのメリット</strong></h2>



<ul class="wp-block-list">
<li><strong>リソース管理の簡略化</strong><br>手動でのクリーンアップが不要になるため、コードがシンプルになります。</li>



<li><strong>安全性の向上</strong><br>クリーンアップ漏れを防ぎ、予期しないエラーを回避できます。</li>



<li><strong>コードの可読性向上</strong><br><code>with</code>文によって処理のスコープが明確になります。</li>
</ul>



<h2 class="wp-block-heading"><strong>まとめ</strong></h2>



<p class="wp-block-paragraph">Pythonのコンテキストマネージャーは、効率的で安全なリソース管理を可能にする強力なツールです。<code>with</code>文を使うことで、コードの可読性が向上し、リソースのクリーンアップを自動化できます。この記事で紹介した基本操作やカスタムマネージャーの作成方法を参考に、プロジェクトで積極的に活用してみてください！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://techgrowup.net/python-context-manager/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Disk: Enhanced  を使用したページ キャッシュ

Served from: techgrowup.net @ 2026-07-08 23:55:45 by W3 Total Cache
-->