From: Jolbas <39026960+Jolbas@users.noreply.github.com> Date: Sun, 25 Sep 2022 14:11:36 +0000 (+0200) Subject: fix: restore pre-3.1 behaviour converting fields to named tuples attributes X-Git-Tag: 3.1.3~7^2~2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=9bb957dac6882b0eb076a23274ab848d93611e32;p=thirdparty%2Fpsycopg.git 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 --- 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