2017-02-21 67 views
2

是否有某個列表(或者更好的模塊!),我可以使用它來檢查字符串是否是變量名稱的「壞」選項,其中「bad」被定義爲像「是關鍵字還是內置函數等」?要在Python中避免使用的變量名稱

我有一個從神社模板生成Python類的腳本(Django模型要準確),我想解決這個問題不適合像我上面提到的那些原因的任何字段名。

到目前爲止,我已經有了一個檢查,看起來像這樣:

def is_bad_name(name): 
    return keyword.iskeyword(name) or (name in ["type"]) 

所以措辭,我的問題的另一種方法是:還有什麼要我把在該列表中有「型」相處?

我認識到,不能有任何完整的清單,因爲這將取決於什麼是我使用的其他模塊定義有所不同,但我不知道是否有應該幾乎從未被使用的東西好名單。謝謝!

+2

'__builtins__'是一個良好的開端。 –

+2

要獲取保留字列表請參閱http://stackoverflow.com/questions/22864221/is-the-list-of-python-reserved-words-and-builtins-available-in-a-library –

+2

如果你是即使考慮到一個變量名可能與內置的內容衝突,你已經給你的變量弄壞了名字......使它們具有描述性 – Sayse

回答

3

你可能想覈對__builtins__鍵:

>>> __builtins__.keys() 

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

您可能要添加__builtins__.__dict__.keys()sys.builtin_module_names這一名單