summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>2018-01-29 02:41:44 +0000
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>2018-01-29 02:41:44 +0000
commite5da79fcc8afb8ee46d364d39a60f9beef635b4d (patch)
treedbff893ac8784ead1b9606603b506d75c80ec671 /lib
parenta84c9723b46907288036938bc81e14a71b696935 (diff)
downloadpsycopg2-namedtuple-invalid-identifiers.tar.gz
Convert fields names into valid Python identifiers in NamedTupleCursornamedtuple-invalid-identifiers
Close #211.
Diffstat (limited to 'lib')
-rw-r--r--lib/extras.py13
1 files changed, 12 insertions, 1 deletions
diff --git a/lib/extras.py b/lib/extras.py
index bfac2df..f8a21e5 100644
--- a/lib/extras.py
+++ b/lib/extras.py
@@ -368,7 +368,18 @@ class NamedTupleCursor(_cursor):
raise self._exc
else:
def _make_nt(self, namedtuple=namedtuple):
- return namedtuple("Record", [d[0] for d in self.description or ()])
+ def f(s):
+ # NOTE: Python 3 actually allows unicode chars in fields
+ s = _re.sub('[^a-zA-Z0-9_]', '_', s)
+ # Python identifier cannot start with numbers, namedtuple fields
+ # cannot start with underscore. So...
+ if _re.match('^[0-9_]', s):
+ s = 'f' + s
+
+ return s
+
+ return namedtuple(
+ "Record", [f(d[0]) for d in self.description or ()])
class LoggingConnection(_connection):