有没有人知道是否有任何内置的python方法会检查某些东西是否是一个有效的python变量名,包括对保留关键字的检查? (所以,就像'in'或'for'之类的东西会失败......)
如果不这样做,是否有人知道我在哪里可以获得保留关键字的列表(即,从python中的动态,而不是从在线文档中复制和粘贴某些内容)?或者,有另一种写自己支票的好方法吗?
令人惊讶的是,通过在try / except中包装setattr进行测试不起作用,如下所示:
setattr(myObj, 'My Sweet Name!', 23)
......实际上有效! (...甚至可以用getattr检索!)
答案 0 :(得分:44)
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标识符是让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个元素的测试集上进行,1000 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
答案 1 :(得分: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']
请注意,根据您使用的主要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']
请注意,其中一些(例如copyright
)实际上并不是一个很重要的交易。
还有一点需要注意:请注意,在Python 2中,True
,False
和None
不被视为关键字。但是,分配给None
是一个SyntaxError。允许分配给True
或False
,但不推荐(与任何其他内置相同)。在Python 3中,它们是关键字,因此这不是问题。
答案 2 :(得分:12)
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)
答案 3 :(得分: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!"
答案 4 :(得分: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。