16 Dec 2011 16 Dec '11
while I was implementing a connection pool i've noticed a pitfall of our beloved with statements:
with pool.get_connection() as conn: ....conn.execute(...) conn.execute(...) # the connection has been returned to the pool and does not belong to the user!
a proposed solution:
with protected_context(pool.get_connection()) as conn: ....conn.execute(...) conn.execute(...) # raises OutOfContextError()
with protected_context(file("/tmp/bla.txt", "w")) as f: ....file.write("blo") file.write("blu") # raises OutOfContextError()
the solution is to basically proxy all methods to the real object until the context ends and then the proxy expires. what do you think about adding it to contextlib?
Thanks, Alon Horev