Row factories

Cursor’s fetch* methods return tuples of column values by default. This can be changed to adapt the needs of the programmer by using custom row factories.

A row factory is a callable that accepts a cursor object and returns another callable accepting a values tuple and returning a row in the desired form. This can be implemented as a class, for instance:

class DictRowFactory:
    def __init__(self, cursor):
        self.fields = [c.name for c in cursor.description]

    def __call__(self, values):
        return dict(zip(self.fields, values))

or as a plain function:

def dict_row_factory(cursor):
    fields = [c.name for c in cursor.description]

    def make_row(values):
        return dict(zip(fields, values))

    return make_row

These can then be used by specifying a row_factory argument in Connection.connect(), Connection.cursor(), or by writing to Connection.row_factory attribute.

conn = psycopg3.connect(row_factory=DictRowFactory)
cur = conn.execute("SELECT first_name, last_name, age FROM persons")
person = cur.fetchone()
print(f"{person['first_name']} {person['last_name']}")

Later usages of row_factory override earlier definitions; for instance, the row_factory specified at Connection.connect() can be overridden by passing another value at Connection.cursor().

Available row factories

The module psycopg3.rows provides the implementation for a few row factories:

psycopg3.rows.tuple_row(cursor: BaseCursor[Any]) → Callable[[Sequence[Any]], Tuple[Any, ]]

Row factory to represent rows as simple tuples.

This is the default factory.

psycopg3.rows.dict_row(cursor: BaseCursor[Any]) → Callable[[Sequence[Any]], Dict[str, Any]]

Row factory to represent rows as dicts.

Note that this is not compatible with the DBAPI, which expects the records to be sequences.

psycopg3.rows.namedtuple_row(cursor: BaseCursor[Any]) → Callable[[Sequence[Any]], NamedTuple]

Row factory to represent rows as namedtuple.