Skip to content

Sqlite3 row_factory for attribute access: NamedRow #83351

Closed as not planned
Closed as not planned

Description

@jidn
mannequin
BPO 39170
Nosy @erlend-aasland, @jidn
PRs
  • bpo-39170: Sqlite3 row_factory for attribute access: sqlite3.NamedRow #17768
  • 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 2019-12-31.06:57:54.312>
    labels = ['type-feature', 'library', '3.9']
    title = 'Sqlite3 row_factory for attribute access: NamedRow'
    updated_at = <Date 2021-06-02.14:17:40.379>
    user = 'https://github.com/jidn'

    bugs.python.org fields:

    activity = <Date 2021-06-02.14:17:40.379>
    actor = 'erlendaasland'
    assignee = 'none'
    closed = False
    closed_date = None
    closer = None
    components = ['Library (Lib)']
    creation = <Date 2019-12-31.06:57:54.312>
    creator = 'jidn'
    dependencies = []
    files = []
    hgrepos = []
    issue_num = 39170
    keywords = ['patch']
    message_count = 2.0
    messages = ['359104', '394911']
    nosy_count = 2.0
    nosy_names = ['erlendaasland', 'jidn']
    pr_nums = ['17768']
    priority = 'normal'
    resolution = None
    stage = 'patch review'
    status = 'open'
    superseder = None
    type = 'enhancement'
    url = 'https://bugs.python.org/issue39170'
    versions = ['Python 3.9']

    Activity

    1. jidn commented on Dec 31, 2019

      jidnmannequin
      MannequinAuthor

      Currently, sqlite3 returns rows by tuple or sqlite3.Row for dict-style, index access. I constantly find myself wanting attribute access like namedtuple for rows. I find attribute access cleaner
      without the brackets and quoting field names. However, unlike previous discussions (https://bugs.python.org/issue13299), I don't want to use the namedtuple object. I appreciate the simple API and minimal memory consumption of sqlite3.Row and used it as my guide in creating sqlite3.NamedRow to allow access by index and attribute.

      A pull request is ready

      Why a new object instead of adding attribute access to the existing sqlite3.Row?
      There is an existing member method keys and any table with the field "keys" would cause a hard to debug, easily avoidable, collision.

      Features:

      • Optimized in C, so it will be faster than any python implementation.
      • Access columns by attribute for all valid names and by index for all names.
      • Iterate over fields by name/value pairs.
      • Works with standard functions len and contains.
      • Identical memory consumption to sqlite3.Row with two references: the data tuple and the cursor description.
      • Identical speed to sqlite3.Row if not faster. Timing usually has it slightly faster for index by name or attribute, but it is almost identical.

      Examples:

      >>> import sqlite3
      >>> c = sqlite3.Connection(":memory:").cursor()
      >>> c.row_factory = sqlite3.NamedRow
      >>> named_row = c.execute("SELECT 'A' AS letter, '.-' AS morse, 65 AS ord").fetchone()
      
          >>> len(named_row)
          3
          >>> 'letter' in named_row
          true
          >>> named_row == named_row
          true
          >>> hash(named_row)
          5512444875192833987
      
      Index by number and range.
          >>> named_row[0]
          'A'
          >>> named_row[1:]
          ('.-', 65)
      
      Index by column name.
          >>> named_row["ord"]
          65
      
      Access by attribute.
          >>> named_row.morse
          '.-'
      
      Iterate row for name/value pairs.
          >>> dict(named_row)
          {'letter': 'A', 'morse': '.-', 'ord': 65}
          >>> tuple(named_row)
          (('letter', 'A'), ('morse', '.-'), ('ord', 65))

      How sqlite3.NamedRow differs from sqlite3.Row
      ----------------------------------------------

      The class only has class dunder methods to allow any valid field name. When the field name would be an invalid attribute name, you have two options: either use the SQL AS in the select statement or index by name.
      To get the field names use the iterator [x[0] for x in row] or do the same from the
      cursor.description.

          titles = [x[0] for x in row]
          titles = [x[0] for x in cursor.description]
          titles = dict(row).keys()

      Attribute and dict access are no longer case-insensitive. There are three reasons for this.
      1. Case-insensitive comparison only works well for ASCII characters. In a Unicode world, case-insensitive edge cases create unnecessary errors. Looking at a several existing codebases,
      this feature of Row is almost never used and I believe is not needed in NamedRow.
      2. Case-insensitivity is not allowed for attribute access. This "feature" would treat attribute access differently from the rest of Python and "special cases aren't special enough to break the rules". Where row.name, row.Name, and row.NAME are all the same it gives off the faint code smell of something wrong. When case-insensitively is needed and the query SELECT can not be modified, sqlite3.Row is still there.
      3. Code is simpler and easier to maintain.
      4. It is faster.

      Timing Results
      --------------

      NamedRow is faster than sqlite3.Row for index-by-name access.
      I have published a graph and the methodology of my testing. In the worst-case scenario, it is just as fast as sqlite3.Row without any extra memory. In most cases, it is faster.
      For more information, see the post at http://jidn.com/2019/10/namedrow-better-python-sqlite3-row-factory/

    2. added
      3.9 (EOL)
      stdlib
      type-feature
      on Dec 31, 2019
    3. erlend-aasland commented on Jun 2, 2021

      @erlend-aasland
      Contributor

      See also gh-57508 (bpo-13299)

    4. transferred this issue fromon Apr 10, 2022
    5. erlend-aasland commented on Jul 17, 2022

      @erlend-aasland
      Contributor

      I'm sorry, but I'm -1 to adding this to the sqlite3 extension module. If we are to add a named row class, I would prefer to go with the approach in gh-57508, because it is magnitudes simpler. If the namedtuple approach was implemented and performance is unacceptable, we could look into improving it by revisiting your PR1.

      For now, I recommend to close this issue and the linked PR as won't-fix.

      Thanks for your interest in improving CPython!

      Footnotes

      1. After a quick glance, the C code in your PR looks good, AFAICS. ↩

    6. added
      pending
      and removed
      3.9 (EOL)
      on Jul 17, 2022
    7. removed
      pending
      on Jul 19, 2022
    8. moved this from Done to Discarded in sqlite3 issueson Jul 19, 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

      stdlibtopic-sqlite3type-feature

      Projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions