Python 中要避免的变量名

Joh*_*n B 2 python code-generation reserved-words

某处是否有一个列表(或者更好的是一个模块!),我可以用它来检查字符串是否是变量名称的“坏”选择,其中“坏”被定义为“是关键字或内置 -在功能等”?

我有一个从 Jinja 模板(准确地说是 Django 模型)生成 Python 类的脚本,我想修复由于我上面提到的原因而不适合的任何字段名称。

到目前为止,我有一张看起来像这样的支票:

def is_bad_name(name):
    return keyword.iskeyword(name) or (name in ["type"])
Run Code Online (Sandbox Code Playgroud)

因此,表达我的问题的另一种方式是:除了“类型”之外,我还应该在该列表中添加什么?

我意识到不可能有任何完整的列表,因为它会根据我正在使用的其他模块中定义的内容而有所不同,但我想知道是否有一个很好的列表,列出了几乎永远不会使用的东西。谢谢!

Jea*_*bre 5

您可能想要检查__builtins__密钥:

>>> __builtins__.keys()

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