2017-02-21 61 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这一名单