Skip to content

namedtuple row factory for sqlite3 #57508

Closed

Description

@ncoghlan
BPO 13299
Nosy @rhettinger, @ncoghlan, @merwok, @akheron, @serhiy-storchaka, @dlenski, @YoSTEALTH, @erlend-aasland
Files
  • issue_13299.patch
  • issue_13299.1.patch
  • issue_13299.2.patch
  • sqlite_namedtuplerow.patch
  • Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

    Show more details

    GitHub fields:

    assignee = None
    closed_at = None
    created_at = <Date 2011-10-31.00:32:25.001>
    labels = ['type-feature']
    title = 'namedtuple row factory for sqlite3'
    updated_at = <Date 2021-08-05.07:15:53.393>
    user = 'https://github.com/ncoghlan'

    bugs.python.org fields:

    activity = <Date 2021-08-05.07:15:53.393>
    actor = 'intellimath'
    assignee = 'ghaering'
    closed = False
    closed_date = None
    closer = None
    components = []
    creation = <Date 2011-10-31.00:32:25.001>
    creator = 'ncoghlan'
    dependencies = []
    files = ['26909', '26945', '26946', '37673']
    hgrepos = []
    issue_num = 13299
    keywords = ['patch']
    message_count = 19.0
    messages = ['146670', '146738', '147474', '168617', '168748', '168761', '168762', '168763', '218657', '218668', '223704', '223725', '224702', '224707', '233839', '234424', '394912', '395065', '398970']
    nosy_count = 11.0
    nosy_names = ['rhettinger', 'ghaering', 'ncoghlan', 'eric.araujo', 'petri.lehtinen', 'serhiy.storchaka', 'dlenski', 'Russell.Sim', 'YoSTEALTH', 'erlendaasland', 'intellimath']
    pr_nums = []
    priority = 'normal'
    resolution = None
    stage = 'patch review'
    status = 'open'
    superseder = None
    type = 'enhancement'
    url = 'https://bugs.python.org/issue13299'
    versions = ['Python 3.5']

    Activity

    1. self-assigned this
      on Jan 11, 2015
    2. serhiy-storchaka commented on Jan 11, 2015

      @serhiy-storchaka
      Member

      Here is faster implementation.

      $ ./python -m timeit -s "import sqlite3; con = sqlite3.connect(':memory:'); con.row_factory = sqlite3.NamedTupleRow; con.execute('create table t (a, b)')" -s "for i in range(100): con.execute('insert into t values (1, 2)')" -- "con.execute('select * from t').fetchall()"
      100 loops, best of 3: 2.74 msec per loop

      But it is still 3 times slower than sqlite3.Row.

    3. YoSTEALTH commented on Jan 21, 2015

      YoSTEALTHmannequin
      Mannequin

      note: sqlite_namedtuplerow.patch _cache method conflicts with attached database with say common table.column name like "id"

      Using namedtuple method over sqlite3.Row was a terrible idea for me. I thought namedtuple is like tuple so should be faster then dict! wrong. I wasted 2 days change my work to namedtuple and back to sqlite3.Row, the speed difference on my working project was:

      namedtuple 0.035s/result
      sqlite3.Rows 0.0019s/result

      for(speed test) range: 10000
      namedtuple 17.3s
      sqlite3.Rows 0.4s

      My solution was to use sqlite3.Row (for speed) but to get named like usage by convert dict keys() with setattr names:

      class dict2named(dict):
          def __init__(self, *args, **kwargs):
              super(dict2named, self).__init__(*args, **kwargs)
              self.__dict__ = self

      Usage:

      for i in con.execute('SELECT * FROM table'):
          yield dict2named(i)

      Now i can use:

      print(i.title)

      and handy dict methods for dash column names:

      print(i['my-title'])
      print(i.get('my-title', 'boo'))

      Now working project speed:
      sqlite3.Rows 0.0020s/result

      for(speed test) range: 10000
      sqlite3.Rows 0.8s with dict2named converting

      This i can work with, tiny compromise in speed with better usage.

    4. erlend-aasland commented on Jun 2, 2021

      @erlend-aasland
      Contributor

      See also bpo-39170

    5. rhettinger commented on Jun 4, 2021

      @rhettinger
      Contributor

      FWIW, namedtuple speed improved considerably since these posts were made. When I last checked, their lookup speed was about the same as a dict lookup.

      See: https://docs.python.org/3/whatsnew/3.9.html#optimizations

    6. intellimath commented on Aug 5, 2021

      intellimathmannequin
      Mannequin

      Instead of using cache, maybe better to use mutable default argument?

      For example:

      def make_row_factory(cls_factory, **kw):
          def row_factory(cursor, row, cls=[None]):
              rf = cls[0]
              if rf is None:
                  fields = [col[0] for col in cursor.description]
                  cls[0] = cls_factory("Row", fields, **kw)
                  return cls[0](*row)
              return rf(*row)
          return row_factory
      
      namedtuple_row_factory = make_row_factory(namedtuple)

      Seem it should add less overhead.

    7. transferred this issue fromon Apr 10, 2022
    8. moved this to Decision needed in sqlite3 issueson May 21, 2022
    9. moved this from Decision needed to No status in sqlite3 issueson May 21, 2022
    10. erlend-aasland commented on Jul 17, 2022

      @erlend-aasland
      Contributor

      FTR, here's a benchmark using @serhiy-storchaka's approach w/LRU cache:

      Lib/sqlite3/dbapi2.py patch
      diff --git a/Lib/sqlite3/dbapi2.py b/Lib/sqlite3/dbapi2.py
      index 3b6d2f7ba2..216895c53a 100644
      --- a/Lib/sqlite3/dbapi2.py
      +++ b/Lib/sqlite3/dbapi2.py
      @@ -89,6 +89,19 @@ def convert_timestamp(val):
       
       del(register_adapters_and_converters)
       
      +
      +import functools
      +@functools.lru_cache(maxsize=128)
      +def _make_class(fields):
      +    return collections.namedtuple("Row", fields)
      +
      +def NamedTupleRow(cursor, row):
      +    """Return a namedtuple row factory for connection objects."""
      +    fields = tuple([c[0] for c in cursor.description])
      +    cls = _make_class(fields)
      +    return cls._make(row)
      +
      +
       def __getattr__(name):
           if name in _deprecated_names:
               from warnings import warn
      bench-row.py
      import pyperf
      
      from textwrap import dedent
      
      
      SETUP_DEF=dedent("""
          import sqlite3
          cx = sqlite3.connect(":memory:")
      """)
      SETUP_ROW=dedent("""
          import sqlite3
          cx = sqlite3.connect(":memory:")
          cx.row_factory = sqlite3.Row
      """)
      SETUP_NAMED=dedent("""
          import sqlite3
          cx = sqlite3.connect(":memory:")
          cx.row_factory = sqlite3.NamedTupleRow
      """)
      STMT=dedent("""
          cx.execute("select 1 as 'a', 2 as 'b'").fetchall()
      """)
      
      runner = pyperf.Runner()
      runner.timeit(name="default", stmt=STMT, setup=SETUP_DEF)
      runner.timeit(name="row", stmt=STMT, setup=SETUP_ROW)
      runner.timeit(name="named", stmt=STMT, setup=SETUP_NAMED)
      $ python ../cpython-stuff/bench-row.py
      .....................
      default: Mean +- std dev: 2.48 us +- 0.02 us
      .....................
      row: Mean +- std dev: 2.60 us +- 0.02 us
      .....................
      named: Mean +- std dev: 3.71 us +- 0.03 us
      

      Following up Serhiy's suggestion to add a cursor.fieldnames() method shows a small improvement:

      $ python ../cpython-stuff/bench-row.py
      .....................
      default: Mean +- std dev: 2.48 us +- 0.02 us
      .....................
      row: Mean +- std dev: 2.60 us +- 0.02 us
      .....................
      named: Mean +- std dev: 3.26 us +- 0.05 us
      
    11. merwok commented on Jul 17, 2022

      @merwok
      Member

      These years, I would prefer a dataclass conversion rather than a named tuple.

    12. erlend-aasland commented on Jul 18, 2022

      @erlend-aasland
      Contributor

      These years, I would prefer a dataclass conversion rather than a named tuple.

      I'm curious why?

      IMO, named tuples are a better fit. A dataclass factory would be considerably slower than using named tuples1, and it does not offer subscripting nor slicing out of the box.

      benchmark
      $ python ../cpython-stuff/bench-row.py    
      .....................
      default: Mean +- std dev: 1.35 us +- 0.02 us
      .....................
      row: Mean +- std dev: 1.44 us +- 0.03 us
      .....................
      namedtuple: Mean +- std dev: 2.00 us +- 0.04 us
      .....................
      dataclass: Mean +- std dev: 1.92 us +- 0.08 us
      

      Footnotes

      1. I re-ran the benchmark with an optimised build, and now it performed exactly like the namedtuple factory. ↩

    13. merwok commented on Jul 18, 2022

      @merwok
      Member

      I don’t like using named tuples after all! I prefer having attribute access only, it’s more explicit than tuple positions.
      Nowadays I see named tuples as a great thing to add attributes to some data structure that used to be a tuple only, but as a tool to define new lightweight data classes I prefer the dataclasses module.

    14. erlend-aasland commented on Jul 19, 2022

      @erlend-aasland
      Contributor

      More importantly; is it worth it to pursue this issue further? Is the performance acceptable?

    15. merwok commented on Jul 19, 2022

      @merwok
      Member

      I think that named tuples still make sense for a row factory. But I am the wrong person to evaluate performance numbers.

    16. erlend-aasland commented on Jul 20, 2022

      @erlend-aasland
      Contributor

      An alternative approach is simply to add attribute access to sqlite3.Row.

    17. erlend-aasland commented on Nov 15, 2022

      @erlend-aasland
      Contributor

      FYI, I've added a namedtuple row factory as an example in the proposed "row factory how-to" in gh-99507. Perhaps it is suffictient to keep this as an example/recipe in the docs instead of adding it as a new feature.

    18. erlend-aasland commented on Nov 25, 2022

      @erlend-aasland
      Contributor

      The sqlite3 docs now include a "row factory how-to" that includes a recipe for a simple namedtuple row factory (though without the class creation cache optimisation). I'm not sure it is worth it to add the namedtuple row factory as a feature, thought; some users want a named tuple, some want a dataclass, some want something else.

      In the light of the docs update, I now suggest to close this feature request.

    19. added
      pending
      on Nov 25, 2022
    20. removed
      pending
      on Nov 27, 2022
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Metadata

    Metadata

    Assignees

    No one assigned

      Labels

      topic-sqlite3type-feature

      Projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions