[issue13299] namedtuple row factory for sqlite3
Raymond Hettinger
report at bugs.python.org
Tue Aug 21 09:20:33 CEST 2012
Raymond Hettinger added the comment:
Caching based on the cursor going to be problematic because a single cursor can be used multiple times with different descriptions:
c = conn.cursor()
c.execute('select symbol from stocks')
print c.description
c.execute('select price from stocks')
print c.description # same cursor, different layout, needs a new named tuple
It might make more sense to cache the namedtuple() factory itself:
sql_namedtuple = lru_cache(maxsize=20)(namedtuple)
Also, the example in the docs is too lengthy and indirect. Cut-out the step for creating an populating the database -- just assume db created in the example at the top of the page:
For example::
>>> conn.row_factory = sqlite3.NamedTupleRow
>>> c = conn.cursor()
>>> for record in c.execute('select * from stocks'):
print record
Row(date='2006-01-05', trans='BUY', symbol='RHAT', qty=100.0, price=35.14)
Row(date='2006-01-05', trans='BUY', symbol='RHAT', qty=100, price=35.14)
Row(date='2006-03-28', trans='BUY', symbol='IBM', qty=1000, price-45.0)
No need to go into a further lesson on how to use named tuples.
Also, the patch uses star-unpacking: _namedtuple_row(cursor)(*row)
Instead, it should use _make: _namedtuple_row(cursor)._make(row)
(u'2006-04-05', u'BUY', u'MSFT', 1000, 72.0)
----------
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue13299>
_______________________________________
More information about the Python-bugs-list
mailing list