Skip to content

Instantly share code, notes, and snippets.

@dvarrazzo
Created March 24, 2016 16:20
Show Gist options
  • Save dvarrazzo/da1e98df4d3691a57aeb to your computer and use it in GitHub Desktop.
Save dvarrazzo/da1e98df4d3691a57aeb to your computer and use it in GitHub Desktop.
A psycopg2 namedtuple cursor de-duplicating repeated fields names
"""
An example of named tuple cursor de-duplicating repeated fields names.
This is **not** a good idea: it makes the program unpredictable. But if you put
the foot and really look for a gun...
See https://github.com/psycopg/psycopg2/issues/418
"""
from itertools import count
from collections import OrderedDict, namedtuple
from psycopg2.extras import NamedTupleCursor
class DedupingNamedTupleCursor(NamedTupleCursor):
def _make_nt(self):
return namedtuple("Record",
self.dedupe([d[0] for d in self.description or ()]))
def dedupe(self, l):
rv = OrderedDict()
for i in l:
if i not in rv:
rv[i] = True
else:
for n in count(1):
ii = "%s_%d" % (i, n)
if ii not in rv:
rv[ii] = True
break
return list(rv)
if __name__ == '__main__':
import psycopg2
cnn = psycopg2.connect("dbname=postgres",
cursor_factory=DedupingNamedTupleCursor)
cur = cnn.cursor()
cur.execute("select 10 as a, 20 as b, 30 as c, 40 as c, 50 as c")
print cur.fetchone()
# Record(a=10, b=20, c=30, c_1=40, c_2=50)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment