[Python-ideas] context managers used to allocate resources can be abused - a solution
alon at horev.net
Sat Dec 17 02:00:09 CET 2011
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(...) # 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(...) # raises OutOfContextError()
with protected_context(file("/tmp/bla.txt", "w")) as f:
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
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas