sak
sak

Reputation: 1298

How "dict_factory(cursor, row)" is called automatically from "dict_factory" while i am not passing any parameters?

I am very new to python development and having trouble while understanding one method used in one sample, the method is:

def dict_factory(cursor, row):

    d={}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]

    return d

and it is being called from:

conn = sqlite3.connect("books.db")
conn.row_factory = dict_factory
cur = conn.cursor()

Now the 2 questions are:

  1. How dict_factory(cursor, col) is being called from dict_factory without params?

  2. How dict_factory() is actually working? Does enumerate breaks the DB into the format of (c0,r0),(c0,r1) and so on?

The converted DB by dict_factory is:

[
  {
    "author": "Ann Leckie ", 
    "first_sentence": "The body lay naked and facedown, a deathly gray, spatters of blood staining the snow around it.", 
    "id": null, 
    "published": 2014, 
    "title": "Ancillary Justice"
  }, 
  {
    "author": "John Scalzi", 
    "first_sentence": "From the top of the large boulder he sat on, Ensign Tom Davis looked across the expanse of the cave, toward Captain Lucius Abernathy, Science Officer Q\u2019eeng and Chief Engineer Paul West perched on a second, larger boulder, and thought, Well, this sucks.", 
    "id": null, 
    "published": 2013, 
    "title": "Redshirts"
  }
]

Upvotes: 1

Views: 1663

Answers (1)

a_guest
a_guest

Reputation: 36329

  1. In the code you showed, dict_factory is not being called. conn.row_factory = dict_factory simply assigns that function to the attribute row_factory. That means you just told your database connection in which way to treat rows (as dictionaries).
  2. enumerate augments the "normal" iteration by the index of the element (it returns tuples (index, element)). If you did for col in cursor.description: then col simply holds the name of each column. Doing for idx, col in enumerate(cursor.description): instead provides tuples where the first element is the iteration index (starting at 0), i.e. (0, col0), (1, col1), .... Now the function dict_factory converts a row to a dict. It does so by iterating over the various columns and adding key-value pairs col_name: row_value_for_that_column to the dictionary.

Upvotes: 2

Related Questions