2012年8月11日 星期六

with as

要打開文件,我習慣照書本教的
fobj = open(filename, 'r')

怕文件不存在,可能還得再加個捕捉錯誤

  1 
  2 
  3 
  4 
  5 
try:
    fobj = open(filename, 'r')
except IOError:
    pass
 
 
但有了with as 就方便多了,可以

  1 
  2 
with open(filename, 'r') as fobj:
    do something

為了讓class 也能使用,需添加二個函數__enter__和 __exit__
  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
class A:
    def __enter__(self):
        print 'in enter'
    def __exit__(self, e_t, e_v, t_b):
        print 'in exit'

with A() as a:
    print 'in with'


in enter
in with
in exit


使用模組contextlib,便不用構造__enter__和 __exit__

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
>>> from contextlib import contextmanager
>>> from __future__ import with_statement
>>> @contextmanager
... def context():
...     print 'entering the zone'
...     try:
...         yield
...     except Exception, e:
...         print 'with an error %s'%e
...         raise e
...     else:
...         print 'with no error'
...
>>> with context():
...     print '----in context call------'
...
entering the zone
----in context call------
with no error
官方範例
  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
from contextlib import contextmanager

@contextmanager
def tag(name):
    print "<%s>" % name
    yield
    print "</%s>" % name

>>> with tag("h1"):
...    print "foo"
...
<h1>
foo
</h1>

還有一個closing可在抓網頁資料時使用


  1 
  2 
  3 
  4 
  5 
  6 
from contextlib import closing
import urllib

with closing(urllib.urlopen('http://www.python.org')) as page:
    for line in page:
        print line



沒有留言:

張貼留言