Hut8 Hut8 - 2 years ago 60
Python Question

Python MySQLdb "with" syntax and DictCursor

I'm trying to use a DictCursor with a

block. I would think that by using:

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

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

Answer Source

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

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

As for DictCursor, it does not support context management.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download