26

何かが有効なpython変数名であるかどうかをチェックする組み込みのpythonメソッドがあるかどうか、誰かが知っていますか?予約されたキーワードに対するチェックを含みますか? (つまり、'in' や 'for' のようなものは失敗します...)

それができない場合、予約済みキーワードのリストをどこで取得できるかを知っている人はいますか (つまり、オンライン ドキュメントから何かをコピー アンド ペーストするのではなく、Python 内から動的に)。または、独自の小切手を書く別の良い方法はありますか?

驚くべきことに、setattr を try/except でラップすることによるテストは、次のように機能しません。

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

...実際に動作します! (...そして、getattr で取得することもできます!)

4

5 に答える 5

57
于 2015-04-12T05:41:18.830 に答える
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) は、実際にはオーバーライドするほど大きな問題ではないことに注意してください。

Trueもう 1 つの警告: Python 2では、、、、FalseおよびNoneはキーワードとは見なされないことに注意してください。ただし、への代入Noneは SyntaxError です。Trueorへの代入Falseは許可されていますが、推奨されていません (他のビルトインと同様)。Python 3 ではキーワードであるため、これは問題になりません。

于 2012-10-03T01:59:40.320 に答える
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)
于 2013-03-22T12:41:08.570 に答える
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!"
于 2012-10-03T01:53:57.540 に答える
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)

注: これは、Unicode カテゴリとの照合regexに組み込みパッケージではなく、パッケージを使用します。また、これは Python 2 のキーワードであるが Python 3 のキーワードではないものreを拒否します。nonlocal

于 2021-03-05T13:32:41.770 に答える