From 9bb957dac6882b0eb076a23274ab848d93611e32 Mon Sep 17 00:00:00 2001 From: Jolbas <39026960+Jolbas@users.noreply.github.com> Date: Sun, 25 Sep 2022 16:11:36 +0200 Subject: [PATCH] fix: restore pre-3.1 behaviour converting fields to named tuples attributes Let more valid identifiers through _as_python_identifier(). Also 2.5x faster if no change is needed Close #386 --- psycopg/psycopg/_encodings.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/psycopg/psycopg/_encodings.py b/psycopg/psycopg/_encodings.py index d293949e3..b1b21267c 100644 --- a/psycopg/psycopg/_encodings.py +++ b/psycopg/psycopg/_encodings.py @@ -146,10 +146,13 @@ def _as_python_identifier(s: str, prefix: str = "f") -> str: Replace all non-valid chars with '_' and prefix the value with *prefix* if the first letter is an '_'. """ - s = _re_clean.sub("_", s) - # Python identifier cannot start with numbers, namedtuple fields - # cannot start with underscore. So... - if s[0] == "_" or "0" <= s[0] <= "9": + if not s.isidentifier(): + if s[0] in "1234567890": + s = prefix + s + if not s.isidentifier(): + s = _re_clean.sub("_", s) + # namedtuple fields cannot start with underscore. So... + if s[0] == "_": s = prefix + s return s -- 2.47.2