Last active
September 7, 2022 16:08
-
-
Save dvarrazzo/9c874e212406150a1acd8f657a4d914b to your computer and use it in GitHub Desktop.
DictCursor for psycopg 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DictTuple(tuple): | |
"""Tuple class with added item getting by name. | |
""" | |
def __new__(cls, d): | |
rv = super().__new__(cls, d.values()) | |
rv._map = d | |
return rv | |
def __repr__(self): | |
return f"{type(self).__qualname__}({self._map!r})" | |
def __getitem__(self, key): | |
if isinstance(key, str): | |
return self._map[key] | |
else: | |
return super().__getitem__(key) | |
def dicttuple_row(cursor): | |
"""psycopg 3 row factory to return DictTuple. | |
Simulate psycopg2 DictCursor. | |
""" | |
desc = cursor.description | |
assert desc, "no result available" | |
names = [c.name for c in desc] | |
def dicttuple_row_(values): | |
return DictTuple(dict(zip(names, values))) | |
return dicttuple_row_ | |
if __name__ == "__main__": | |
import psycopg | |
conn = psycopg.connect("", row_factory=dicttuple_row) | |
row = conn.execute("select 10 as foo, 20 as bar").fetchone() | |
print(f"{row=}") | |
# row=DictTuple({'foo': 10, 'bar': 20}) | |
print(f"{row['foo']=}") | |
# row['foo']=10 | |
print(f"{row[1]=}") | |
# row[1]=20 | |
a, b = row | |
print(f"{a=}, {b=}") | |
# a=10, b=20 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment