Hut8 Hut8 - 7 months ago 16
Python Question

Python MySQLdb "with" syntax and DictCursor

I'm trying to use a DictCursor with a

with
block. I would think that by using:

with MySQLdb.connect(...) as c:


c
would be a connection object, because that's what connect() returns. But alas, it is not! All of a sudden,
c
is a cursor! While this is usually convenient, I really like using a
DictCursor
- is this not designed that way at all? Enclosing the DictCursor as the "scoped object" causes an error (
__exit__
wasn't defined)

Answer

c is a cursor because that's what is returned from the __enter__ method of the context manager.
If you browse Mysqldb's source code, you'll be able to see in line 245 of connections.py:

def __enter__(self): return self.cursor()

As for DictCursor, it does not support context management.

Comments