[Python] Python 2.5 Changes

Conditional Expression

 # Conditional expression 
 value = (B if A else C)

 # 問題点: Aが真でも B が 偽 と判断された場合 C を返す
 value = (A and B or C)

 # 利点: lambda式 中に条件分岐が書ける

PEP 343 - 'with' statement (./Lib/test/test_with.py, ./Lib/contextlib.py参照)

 from __future__ import with_statement
 from contextlib import closing, nexted

 # 変数のスコープはブロック内ローカル ではない ので注意
 f = None
 with closing(file('test.txt', 'r')) as f:
     print f.read()
 print f.closed # True


 class wrap_stream(object):
     def __init__(self, create_func, *args, **kwds):
         self.create = create_func
         self.args = args
         self.kwds = kwds

     def __enter__(self):
         self.thing = self.func(*self.args, **self.kwds)
         return self.thing

     def __exit__(self, *exc_info):
         self.thing.close()

 with wrap_stream(file, 'test.txt', 'r') as stream:
     print stream.read()

  • try/except/finally ... exceptとfinallyブロックが同時に記述できる。(try/finally/elseはまだ無理らしい)
  • 例外クラスがnew-style classesを利用、例外クラスの階層が少し変更された。


TODO

  • functools