Why Connection.__exit__ doesn't use Cursor.close

100 views
Skip to first unread message

adcro...@gmail.com

unread,
Dec 6, 2014, 6:52:04 AM12/6/14
to pymysq...@googlegroups.com
Hy,

I'm using
with self.connection as cur:

and was expecting Cursor.close to be called automatically at the end, but isn't. Why is that?

Thanks!

INADA Naoki

unread,
Dec 6, 2014, 8:34:57 AM12/6/14
to pymysq...@googlegroups.com
Since it's not defined in DB-API 2.0 <https://www.python.org/dev/peps/pep-0249>

I've added __enter__ and __exit__ to MySQLdb (and mysqlclient), but it
is for transaction.
https://github.com/PyMySQL/mysqlclient-python/blob/master/MySQLdb/connections.py

Now, I'm afraid to add it without DB-API recommendation.
> --
> You received this message because you are subscribed to the Google Groups
> "PyMySQL Users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to pymysql-user...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.



--
INADA Naoki <songof...@gmail.com>

adcro...@gmail.com

unread,
Dec 6, 2014, 10:03:33 AM12/6/14
to pymysq...@googlegroups.com
So, I'm new to PyMysql, so I'm a little confused.

I'm talking about this code:

    def __enter__(self):
       if self.get_autocommit():
           self.query("BEGIN")
       return self.cursor()


    def __exit__(self, exc, value, tb):
       if exc:
           self.rollback()
       else:
           self.commit()


On __enter__ self.cursor() is called and a new Cursor is created. Shouldn't it be closed on __exit__?

Naoki INADA

unread,
Dec 12, 2014, 8:02:25 AM12/12/14
to pymysq...@googlegroups.com
Uh, You're right.

Since PyMySQL's cursor doesn't grasp any resource, not closing it doesn't cause leak.

adcro...@gmail.com

unread,
Dec 22, 2014, 6:01:35 AM12/22/14
to pymysq...@googlegroups.com
So, why does a close() method exist at all, if its not used/useful?
And why is it "public"?

INADA Naoki

unread,
Dec 22, 2014, 9:33:29 AM12/22/14
to pymysq...@googlegroups.com
It's necessary since it's defined in DB-API 2.0.

adcro...@gmail.com

unread,
Dec 22, 2014, 2:10:00 PM12/22/14
to pymysq...@googlegroups.com
Thanks for your time!
It's really helpful to learn from a good source :)
Reply all
Reply to author
Forward
0 new messages