Python2.5からの機能 try/except/finallyとかwithとか

前社内でちょっと話題になったんだけど2.5からの機能で try/except/finally の同時使用


今までは、try/except か try/finally の組み合わせしか出来なかった(elseはどちらにも使用可能)けど
2.5からは try/except/finally が使用出来る。

2.5より前

import sys
try:
    f = open('a.txt')
except IOError, (errno, strerror):
    print "I/O error(%s): %s" % (errno, strerror)
else:
    print "line count = ", len(f.readlines())
    f.close()


2.5以降

import sys

try:
    f = open('a.txt')
except IOError, (errno, strerror):
    print "I/O error(%s): %s" % (errno, strerror)
else:
    print "line count = ", len(f.readlines())
finally:
    f.close()

※このfinallyの例だと、a.txtが無い場合はエラーになるので例が悪いですが




C#で開発してる今は、usingが特にイイ。
自動的にDispose();を呼び出して、例外にも対応してくれてる構文です。

こんな処理が

    FileStream fs = new FileStream("test.txt", FileMode.Read);
    try 
    {
        StreamReader reader = new StreamReader(fs);
        try 
        {
            // 処理
        }
        finally 
        {
            if (reader != null) 
            {
                reader.Dispose();
            }
        }
    }
    finally 
    {
        if (fs != null) 
        {
            fs.Dispose();
        }
    }


usingを使うことで

    using (FileStream fs = new FileStream("test.txt", FileMode.Read)) 
    {
        using (StreamReader sr = new StreamReader(fs)) 
        {
            // 処理
        }  
    }

mopemopeなんて、暇さえあれば「using使え」と言っています。




C#のusingに似た機能にPythonには2.5からwithがあります。

from __future__ import with_statement
import sys
try:
    with open('aa.txt') as f:
        print "line count = ", len(f.readlines())
except IOError, (errno, strerror):
    print "I/O error(%s): %s" % (errno, strerror)

この例だと、fは必ずcloseされることになります。
ブロック処理中に問題があった場合にも必ずcloseされます。


C#といったらusing

Pythonといったらwith

ですね。