[python-sybase] dictionary-based fetch*() methods?

Skip Montanaro skip at pobox.com
Thu, 13 May 2004 11:34:34 -0500


I'm new to Sybase and the Object Craft Sybase module, but have used both
MySQL and PostgreSQL from Python extensively.  Both the MySQLdb and psycopg
packages allow users to get select results as lists of dictionaries instead
of just as lists of tuples.  Predictably, since this behavior isn't
specified in the Python DB API, the two wrappers implemented this feature in
different ways.

Something like the following only lightly tested extension seems like a
reasonable step in that direction for the Sybase module.  It's more akin to
the way MySQLdb does things (instantiate different cursors instead of
replicating the fetch* methods for list-of-dict), though to avoid messing
with Sybase.Connection.cursor() I simply sublcassed Sybase.Connection and
instantiate that.

    import Sybase

    class Connection(Sybase.Connection):
        def dictcursor(self):
            return DictCursor(self)

    class DictCursor(Sybase.Cursor):
        def row2dict(self, row):
            d = {}
            for i,elt in enumerate(row):
                d[self.description[i][0]] = elt
            return d

        def fetchall(self):
            rows = Sybase.Cursor.fetchall(self)
            result = [] 
            for row in rows:
                result.append(self.row2dict(row))
            return result

        def fetchone(self):
            return row2dict(Sybase.Cursor.fetchone(self))

        def fetchmany(self):
            rows = Sybase.Cursor.fetchmany(self)
            result = [] 
            for row in rows:
                result.append(self.row2dict(row))
            return result

While it's obviously not hard to implement lists of dicts results (and thus
all Sybase users could do it should they choose) manipulating lists of dicts
makes code so much more readable that I never use the lists of tuples form
anymore.  I think this would be a handy addition to the Sybase module.  If
it's deemed reasonable, I'd suggest just changing the signature of the
Connection.cursor() method to take an optional cursorclass argument which
would default to the current Sybase.Cursor class and add a DictCursor class
akin to the above to Sybase.py.

-- 
Skip Montanaro
Got gigs? http://www.musi-cal.com/submit.html
Got spam? http://www.spambayes.org/
skip@pobox.com