如何检查字符串是否是有效的Python标识符?包括关键字检查?

问题描述 投票:0回答:5

是否有任何内置的 python 方法可以检查某些内容是否是有效的 python 变量名,包括对保留关键字的检查? (即,像“in”或“for”之类的东西会失败)

如果做不到这一点,我在哪里可以获取保留关键字的列表(即动态地从 python 中获取,而不是从在线文档中复制粘贴某些内容)?或者,有什么好的方法可以自己写支票吗?

令人惊讶的是,通过在 try/ except 中包装 setattr 进行测试不起作用,如下所示:

setattr(myObj, 'My Sweet Name!', 23)

...确实有效! (...甚至可以使用 getattr 检索!)

python keyword identifier reserved
5个回答
64
投票

Python 3

Python 3 现在有了

'foo'.isidentifier()
,因此这似乎是最近 Python 版本的最佳解决方案(感谢同事 runciter@freenode 的建议)。然而,有点违反直觉,它不会检查关键字列表,因此必须使用两者的组合:

import keyword

def isidentifier(ident: str) -> bool:
    """Determines if string is valid Python identifier."""

    if not isinstance(ident, str):
        raise TypeError("expected str, but got {!r}".format(type(ident)))

    if not ident.isidentifier():
        return False

    if keyword.iskeyword(ident):
        return False

    return True

Python 2

对于 Python 2,检查给定字符串是否是有效的 Python 标识符的最简单方法是让 Python 自行解析它。

有两种可能的方法。最快的是使用

ast
,并检查单个表达式的 AST 是否具有所需的形状:

import ast

def isidentifier(ident):
    """Determines, if string is valid Python identifier."""

    # Smoke test — if it's not string, then it's not identifier, but we don't
    # want to just silence exception. It's better to fail fast.
    if not isinstance(ident, str):
        raise TypeError("expected str, but got {!r}".format(type(ident)))

    # Resulting AST of simple identifier is <Module [<Expr <Name "foo">>]>
    try:
        root = ast.parse(ident)
    except SyntaxError:
        return False

    if not isinstance(root, ast.Module):
        return False

    if len(root.body) != 1:
        return False

    if not isinstance(root.body[0], ast.Expr):
        return False

    if not isinstance(root.body[0].value, ast.Name):
        return False

    if root.body[0].value.id != ident:
        return False

    return True

另一种方法是让

tokenize
模块将标识符拆分到令牌流中,并检查它只包含我们的名字:

import keyword
import tokenize

def isidentifier(ident):
    """Determines if string is valid Python identifier."""

    # Smoke test - if it's not string, then it's not identifier, but we don't
    # want to just silence exception. It's better to fail fast.
    if not isinstance(ident, str):
        raise TypeError("expected str, but got {!r}".format(type(ident)))

    # Quick test - if string is in keyword list, it's definitely not an ident.
    if keyword.iskeyword(ident):
        return False

    readline = lambda g=(lambda: (yield ident))(): next(g)
    tokens = list(tokenize.generate_tokens(readline))

    # You should get exactly 2 tokens
    if len(tokens) != 2:
        return False

    # First is NAME, identifier.
    if tokens[0][0] != tokenize.NAME:
        return False

    # Name should span all the string, so there would be no whitespace.
    if ident != tokens[0][1]:
        return False

    # Second is ENDMARKER, ending stream
    if tokens[1][0] != tokenize.ENDMARKER:
        return False

    return True

相同的功能,但与Python 3兼容,如下所示:

import keyword
import tokenize

def isidentifier_py3(ident):
    """Determines if string is valid Python identifier."""

    # Smoke test — if it's not string, then it's not identifier, but we don't
    # want to just silence exception. It's better to fail fast.
    if not isinstance(ident, str):
        raise TypeError("expected str, but got {!r}".format(type(ident)))

    # Quick test — if string is in keyword list, it's definitely not an ident.
    if keyword.iskeyword(ident):
        return False

    readline = lambda g=(lambda: (yield ident.encode('utf-8-sig')))(): next(g)
    tokens = list(tokenize.tokenize(readline))

    # You should get exactly 3 tokens
    if len(tokens) != 3:
        return False

    # If using Python 3, first one is ENCODING, it's always utf-8 because 
    # we explicitly passed in UTF-8 BOM with ident.
    if tokens[0].type != tokenize.ENCODING:
        return False

    # Second is NAME, identifier.
    if tokens[1].type != tokenize.NAME:
        return False

    # Name should span all the string, so there would be no whitespace.
    if ident != tokens[1].string:
        return False

    # Third is ENDMARKER, ending stream
    if tokens[2].type != tokenize.ENDMARKER:
        return False

    return True

但是,请注意 Python 3

tokenize
实现中的错误,这些错误拒绝一些完全有效的标识符,例如
℘᧚
贈ᩭ
。不过
ast
工作得很好。一般来说,我建议不要使用基于
tokenize
的实现进行实际检查。

此外,有些人可能认为像 AST 解析器这样的重型机器有点过大了。这个简单的实现是独立的,并且保证可以在任何 Python 2 上工作:

import keyword
import string

def isidentifier(ident):
    """Determines if string is valid Python identifier."""

    if not isinstance(ident, str):
        raise TypeError("expected str, but got {!r}".format(type(ident)))

    if not ident:
        return False

    if keyword.iskeyword(ident):
        return False

    first = '_' + string.lowercase + string.uppercase
    if ident[0] not in first:
        return False

    other = first + string.digits
    for ch in ident[1:]:
        if ch not in other:
            return False

    return True

这里有一些测试来检查这些是否有效:

assert isidentifier('foo')
assert isidentifier('foo1_23')
assert not isidentifier('pass')    # syntactically correct keyword
assert not isidentifier('foo ')    # trailing whitespace
assert not isidentifier(' foo')    # leading whitespace
assert not isidentifier('1234')    # number
assert not isidentifier('1234abc') # number and letters
assert not isidentifier('👻')      # Unicode not from allowed range
assert not isidentifier('')        # empty string
assert not isidentifier('   ')     # whitespace only
assert not isidentifier('foo bar') # several tokens
assert not isidentifier('no-dashed-names-for-you') # no such thing in Python

# Unicode identifiers are only allowed in Python 3:
assert isidentifier('℘᧚') # Unicode $Other_ID_Start and $Other_ID_Continue

性能

所有测量均在我的机器上进行(MBPr 2014 年中),随机生成的测试集包含 1 500 000 个元素,其中 1 000 000 个元素有效,500 000 个元素无效。 YMMV

== Python 3:
method | calls/sec | faster
---------------------------
token  |    48 286 |  1.00x
ast    |   175 530 |  3.64x
native | 1 924 680 | 39.86x

== Python 2:
method | calls/sec | faster
---------------------------
token  |    83 994 |  1.00x
ast    |   208 206 |  2.48x
simple | 1 066 461 | 12.70x

14
投票

keyword
模块包含所有保留关键字的列表:

>>> import keyword
>>> keyword.iskeyword("in")
True
>>> keyword.kwlist
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

请注意,随着关键字列表的变化(尤其是在 Python 2 和 Python 3 之间),此列表将根据您使用的 Python 主要版本而有所不同。

如果您还想要所有内置名称,请使用

__builtins__

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

请注意,其中一些(例如

copyright
)并不是真正需要覆盖的大问题。

还有一个警告:请注意,在 Python 2 中,

True
False
None
不被视为关键字。然而,分配给
None
是一个语法错误。允许分配给
True
False
,但不推荐(与任何其他内置函数相同)。在 Python 3 中,它们是关键字,所以这不是问题。


13
投票

John:作为一个小小的改进,我在 re 中添加了 $,否则,测试不会检测到空格:

import keyword 
import re
my_var = "$testBadVar"
print re.match("[_A-Za-z][_a-zA-Z0-9]*$",my_var) and not keyword.iskeyword(my_var)

0
投票

Python 关键字列表很短,因此您只需使用简单的正则表达式检查语法以及相对较小的关键字列表中的成员资格

import keyword #thanks asmeurer
import re
my_var = "$testBadVar"
print re.match("[_A-Za-z][_a-zA-Z0-9]*",my_var) and not keyword.iskeyword(my_var)

更短但更危险的替代方案是

my_bad_var="%#ASD"
try:exec("{0}=1".format(my_bad_var))
except SyntaxError: #this maynot be right error
   print "Invalid variable name!"

最后一个稍微更安全的变体

my_bad_var="%#ASD"

try:
  cc = compile("{0}=1".format(my_bad_var),"asd","single")
  eval(cc)
  print "VALID"
 except SyntaxError: #maybe different error
  print "INVALID!"

0
投票

我需要从 Python 2 代码中检查 Python 3 标识符。我使用了基于 docs:

的正则表达式
import keyword
import regex


def is_py3_identifier(ident):
    """Checks that ident is a valid Python 3 identifier according to
    https://docs.python.org/3/reference/lexical_analysis.html#identifiers
    """
    return bool(
        ID_REGEX.match(unicodedata.normalize('NFKC', ident)) and
        not PY3_KEYWORDS.contains(ident))

# See https://docs.python.org/3/reference/lexical_analysis.html#identifiers
ID_START_REGEX = (
    r'\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}'
    r'_\u1885-\u1886\u2118\u212E\u309B-\u309C')
ID_CONTINUE_REGEX = ID_START_REGEX + (
    r'\p{Mn}\p{Mc}\p{Nd}\p{Pc}'
    r'\u00B7\u0387\u1369-\u1371\u19DA')
ID_REGEX = regex.compile(
    "[%s][%s]*$" % (ID_START_REGEX, ID_CONTINUE_REGEX), regex.UNICODE)


PY3_KEYWORDS = frozenset('False', 'None', 'True']).union(keyword.kwlist)

注意:这使用

regex
包,而不是内置
re
包来匹配 unicode 类别。另外:这将拒绝
nonlocal
,这是 Python 2 中的关键字,但不是 Python 3 中的关键字。

© www.soinside.com 2019 - 2024. All rights reserved.