Closed hzhu212 closed 3 years ago
Hi @hzhu212 - thanks a lot for your suggestion. I have now implemented this in the main branch. If it looks good to you, I can create a new release with this change.
Hello @Cito ! hope you are fine! I was reading the source code from the main branch and tried to use the connection in a context manager. After some really confused faces I figured it out that the branch wasn't released yet! Are you planning to release it soon?
@BrunoMarengo I have released a new version 2.0.2 with this change now.
How to reproduce:
Will throw an
AttributeError
inwith
statement:What's wrong:
It seems
conn
(PooledDedicatedDBConnection
object) has no attribute__enter__
.But when I type
it gives
So
conn.__enter__
do exist, but it comes from internalSteadyDBConnection
object, notconn
itself.After digging into source code, I find the
__enter__
attribute is proxied fromconn._con
object with__getattr__
:So the reason of the
AttributeError
is that__getattr__
won't take effect inwith
statement. I Googled this problem and find this: Why doesn't getattr work with exit?. It seems like a designed feature that we can't proxy__enter__
and__exit__
with__getattr__
inwith
statement.Furthermore, even though
__getattr__
works fine with__enter__
and__exit__
,PooledDedicatedDBConnection
shouldn't proxy them fromSteadyDBConnection
, because they act the wrong way.The right effect of
PooledDedicatedDBConnection.__exit__
should be return current connection to pool, like itsclose
method. But whatSteadyDBConnection
's__enter__
and__exit__
methods do are very different.A simple way to fix
A simple way to enable
with
statement onPooledDedicatedDBConnection
object is putting__enter__
and__exit__
method into its definition, like this:Or, we can use
contextlib.closing
as an alternative solution, like this:This works fine, but not as convenient as other DB API 2 connections, because of the
import
thing.