函数在循环内的行为差异是一个坏主意,请尝试context manager
改用。这是一种更好的方法,而且更容易理解。
http://www.python.org/dev/peps/pep-0343/
例如:
with sqlite3.connect(":memory:") as conn:
# update will hold in transaction.
for i in xrange(100):
conn.execute("insert ....")
pass
# sqlite3 will commit now
以同样的方式:
with a() as b:
# data won't store
for i in xrange(100):
# don't store data
b[i] = i + 5
pass
# data store while leave context
编辑 1
ContextManager 有enter和exit方法
class MemoryManager(object):
def __init__(self):
self.cache = {}
self.buffer = False
def __enter__(self):
self.buffer = True
def __store(self):
# store data
pass
def __setitem__(self, key, value):
self.cache[key] = value
if not self.buffer:
self.__store()
def __exit__(self, exc_type, exc_value, traceback):
self.__store()
self.buffer = False
所以
m = MemoryManager()
with m as b:
# __enter__ got called, set the manager to buffer mode
# data won't store
for i in xrange(100):
# don't store data
m[i] = i + 5 # in with block, so __store won't be called
pass
# __exit__ got called, __store automatically and leave buffer mode
m[0] = 10 # not in buffer mode, __store will be called