Python2.5のwith文
Python2.5からwith文が導入されました。with文を使用すればtry文のfinally節で行っていた後処理が明快に記述できます。
例えばファイルを開いてデータを読み出してからクローズする場合は下記のようになります。
今回、MySQLに接続してクエリを実行してから接続を閉じる処理をwith文で作成してみたので掲載したいと思います。
上記のサンプルを説明すると、with文は最初に「__enter__」メソッドを呼び出し、with文から抜け出すときに「__exit__」メソッドを呼び出します。
「__enter__」メソッドの戻り値がwith文の変数(上記のサンプルでは「as cursor」の部分です)に代入されるようです。
※with文の中で例外が発生した場合でも「__exit__」メソッドが呼び出されます。
例えばファイルを開いてデータを読み出してからクローズする場合は下記のようになります。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import with_statement
# try finallyを使用
try:
file = open(r"C:\test.txt", "r")
for line in file:
print line
finally:
file.close()
# withを使用
with open(r"C:\test.txt", "r") as file:
for line in file:
print line
今回、MySQLに接続してクエリを実行してから接続を閉じる処理をwith文で作成してみたので掲載したいと思います。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import with_statement
import MySQLdb
class MySQLConnector(object):
def __init__(self, username, password):
self.username = username
self.password = password
def __enter__(self):
self.connection = MySQLdb.connect(db="test", host="localhost", port=3306, user=self.username, passwd=self.password)
self.cursor = self.connection.cursor()
print "called __enter__"
return self.cursor
def __exit__(self, type, value, tb):
self.cursor.close()
self.connection.close()
print "called __exit__"
if __name__ == '__main__':
with MySQLConnector("testuser", "testpassword") as cursor:
cursor.execute("select * from testdata")
for row in cursor.fetchall():
print row
上記のサンプルを説明すると、with文は最初に「__enter__」メソッドを呼び出し、with文から抜け出すときに「__exit__」メソッドを呼び出します。
「__enter__」メソッドの戻り値がwith文の変数(上記のサンプルでは「as cursor」の部分です)に代入されるようです。
※with文の中で例外が発生した場合でも「__exit__」メソッドが呼び出されます。
ラベル: Python

0 件のコメント :
コメントを投稿
この投稿へのリンク :
リンクを作成
<< ホーム