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

Pau*_*tch 23 python identifier keyword reserved

有没有人知道是否有任何内置的python方法将检查某些东西是否是一个有效的python变量名称,包括对保留关键字的检查?(所以,就像'in'或'for'之类的东西会失败......)

如果不这样做,是否有人知道我在哪里可以获得保留关键字的列表(即,从python中的动态,而不是从在线文档中复制和粘贴某些内容)?或者,有另一种写自己支票的好方法吗?

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

setattr(myObj, 'My Sweet Name!', 23)
Run Code Online (Sandbox Code Playgroud)

......实际上有效!(...甚至可以用getattr检索!)

tor*_*gen 46

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

另一种方法是让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
Run Code Online (Sandbox Code Playgroud)

相同的功能,但与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
Run Code Online (Sandbox Code Playgroud)

但是,要知道在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
Run Code Online (Sandbox Code Playgroud)

以下是检查这些工作的几项测试:

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
Run Code Online (Sandbox Code Playgroud)

性能

所有测量都在我的机器上进行(MBPr 2014年中),在相同的随机生成的1 500 000个元素的测试集上进行,1000 000有效,500 000无效.因人而异

== 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
Run Code Online (Sandbox Code Playgroud)

  • 我不确定为什么我的答案被接受而不是这个答案.我的回答提供了有用的信息,但这个实际上回答了这个问题. (5认同)
  • 不是错误。根据语言定义,这些是有效的标识符。您必须使用“keyword.iskeyword”来测试“保留”标识符,例如 def、class、True、None、False。 (2认同)

小智 13

约翰:作为一个小小的改进,我在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)
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考,Unicode字符串是有效的标识符. (3认同)

asm*_*rer 12

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']
Run Code Online (Sandbox Code Playgroud)

请注意,此列表将根据您使用的主要Python版本而有所不同,因为关键字列表会发生变化(特别是在Python 2和Python 3之间).

如果您还想要所有内置名称,请使用 __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']
Run Code Online (Sandbox Code Playgroud)

并注意到其中一些(比如copyright)并不是真正重要的交易.

还有一个警告:注意,在Python 2 True,FalseNone不被视为关键字.但是,赋值None是一个SyntaxError.分配给True或被False允许,但不推荐(与任何其他内置相同).在Python 3中,它们是关键字,因此这不是问题.

  • 你可以在python中使用str作为变量名(你不应该,但你可以)... (2认同)
  • 我还在Python 2中添加了一个关于"None"的警告.它不被认为是关键字,但分配给它是一个SyntaxError. (2认同)