我打开两个数据库的时候,都是
with xxx as conn1:
with yyy as conn2:
code
真是蠢如老狗呀,其实可以:
with xxx as conn1, yyy as conn2:
code
from contextlib import closing
from urllib2 import urlopen
with closing(urlopen('http://www.python.org';)) as page:
for line in page:
print(line)
class Door(object):
def open(self):
print 'Door is opened'
def close(self):
print 'Door is closed'
with Door() as d:
d.open()
结果:
# 报错:
Traceback (most recent call last):
File "1.py", line 38, in
with Door() as d:
AttributeError: __exit__
class Door(object):
def open(self):
print 'Door is opened'
def close(self):
print 'Door is closed'
with contextlib.closing(Door()) as door:
door.open()
结果:
Door is opened
Door is closed
contextlib.closing(xxx),原理如下:
class closing(object):
"""Context to automatically close something at the end of a block.
Code like this:
with closing(.open()) as f:
is equivalent to this:
f = .open()
try:
finally:
f.close()
"""
def __init__(self, thing):
self.thing = thing
def __enter__(self):
return self.thing
def __exit__(self, *exc_info):
self.thing.close()
这个contextlib.closing()会帮它加上__enter__()和__exit__(),使其满足with的条件。
from contextlib import contextmanager
@contextmanager
def tag(name):
print("<%s>" % name)
yield
print("%s>" % name)
with tag("h1"):
print 'hello world!'
结果:
hello world!
import time
def wrapper(func):
def new_func(*args, **kwargs):
t1 = time.time()
ret = func(*args, **kwargs)
t2 = time.time()
print 'cost time=', (t2-t1)
return ret
return new_func
@wrapper
def hello(a,b):
time.sleep(1)
print 'a + b = ', a+b
hello(100,200)
结果:
a + b = 300
cost time= 1.00243401527
from contextlib import contextmanager
@contextmanager
def cost_time():
t1 = time.time()
yield
t2 = time.time()
print 'cost time=',t2-t1
with cost_time():
time.sleep(1)
a = 100
b = 200
print 'a + b = ', a + b
结果:
a + b = 300
cost time= 1.00032901764
class GeneratorContextManager(object):
"""Helper for @contextmanager decorator."""
def __init__(self, gen):
self.gen = gen
def __enter__(self):
try:
return self.gen.next()
except StopIteration:
raise RuntimeError("generator didn't yield")
def __exit__(self, type, value, traceback):
if type is None:
try:
self.gen.next()
except StopIteration:
return
else:
raise RuntimeError("generator didn't stop")
else:
if value is None:
# Need to force instantiation so we can reliably
# tell if we get the same exception back
value = type()
try:
self.gen.throw(type, value, traceback)
raise RuntimeError("generator didn't stop after throw()")
except StopIteration, exc:
return exc is not value
except:
if sys.exc_info()[1] is not value:
raise
def contextmanager(func):
@wraps(func)
def helper(*args, **kwds):
return GeneratorContextManager(func(*args, **kwds))
return helper