コンテキストマネージャーの使い方

Python関数の書き方

Shayne Miel

Software Architect @ Duo Security

コンテキストマネージャーとは?

コンテキストマネージャーの機能:

  • コンテキストを設定する
  • コードを実行する
  • コンテキストを削除する
Python関数の書き方

ケータリングパーティー

空の部屋

Python関数の書き方

ケータリングパーティー

ケータリングされた部屋

Python関数の書き方

ケータリングパーティー

パーティー中の部屋

Python関数の書き方

ケータリングパーティー

ケータリングされた部屋

Python関数の書き方

ケータリングパーティー

空の部屋

Python関数の書き方

コンテキストとしてのパーティー

コンテキストマネージャー:

  • コンテキストを設定する
  • コードを実行する
  • コンテキストを削除する

ケータリング業者:

  • テーブルに食事・飲み物を準備する
  • パーティーを楽しんでもらう
  • 片付けてテーブルを撤去する
Python関数の書き方

実際の使用例

with open('my_file.txt') as my_file:
  text = my_file.read()
  length = len(text)

print('The file is {} characters long'.format(length))

open() の3つの動作:

  • ファイルを開いてコンテキストを設定する
  • ファイルに対して任意のコードを実行する
  • ファイルを閉じてコンテキストを削除する
Python関数の書き方

コンテキストマネージャーの使い方

with
Python関数の書き方

コンテキストマネージャーの使い方

with <context-manager>()
Python関数の書き方

コンテキストマネージャーの使い方

with <context-manager>(<args>)
Python関数の書き方

コンテキストマネージャーの使い方

with <context-manager>(<args>):
Python関数の書き方

コンテキストマネージャーの使い方

with <context-manager>(<args>):
  # Run your code here
  # This code is running "inside the context"
Python関数の書き方

コンテキストマネージャーの使い方

with <context-manager>(<args>):
  # Run your code here
  # This code is running "inside the context"

# This code runs after the context is removed
Python関数の書き方

コンテキストマネージャーの使い方

with <context-manager>(<args>) as <variable-name>:
  # Run your code here
  # This code is running "inside the context"

# This code runs after the context is removed
with open('my_file.txt') as my_file:
  text = my_file.read()
  length = len(text)

print('The file is {} characters long'.format(length))
Python関数の書き方

練習しましょう!

Python関数の書き方

Preparing Video For Download...