diff options
author | Daniele Varrazzo <daniele.varrazzo@gmail.com> | 2018-01-29 02:41:44 +0000 |
---|---|---|
committer | Daniele Varrazzo <daniele.varrazzo@gmail.com> | 2018-01-29 03:30:46 +0000 |
commit | ddb87b7727793ef1d49f3915ad4b2399aeb6ef78 (patch) | |
tree | 09d6d256f8f01916ff04f917e1e039b32e7992e3 /lib | |
parent | 3354bbd1b6c9d4cdc4b34bf0a13b81b4e4cd15e7 (diff) | |
download | psycopg2-ddb87b7727793ef1d49f3915ad4b2399aeb6ef78.tar.gz |
Convert fields names into valid Python identifiers in NamedTupleCursor
Close #211.
Diffstat (limited to 'lib')
-rw-r--r-- | lib/extras.py | 12 |
1 files changed, 11 insertions, 1 deletions
diff --git a/lib/extras.py b/lib/extras.py index 68df344..1f85d53 100644 --- a/lib/extras.py +++ b/lib/extras.py @@ -363,7 +363,17 @@ class NamedTupleCursor(_cursor): return def _make_nt(self): - 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): |