【问题标题】:Variable names to avoid in Python [duplicate]Python中要避免的变量名[重复]
【发布时间】:2017-02-21 22:13:54
【问题描述】:

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

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

到目前为止,我的支票如下所示:

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

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

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

【问题讨论】:

  • __builtins__ 是一个很好的起点。
  • 如果您甚至考虑到变量名可能与内置的某些内容发生冲突,那么您已经给变量起坏名了.. 让它们具有描述性
  • 我想知道匹配你已经是什么,匹配你正在导入的所有模块,然后匹配dir(module)(即import os \n dir(os))是否有效

标签: python code-generation reserved-words


【解决方案1】:

您可能想要检查 __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',
 '_']

【讨论】:

  • SE 不会在块中软换行,在我的 56 英寸电视上,一次最多可以显示 85 个字符。为了便于阅读,请考虑硬换行为 80 个字符
  • 即使有漂亮的打印机也不是那么容易;
  • 哎呀,这是一个很长的列表!谢谢
  • 也许可以在中间加上...。只是让人们看到重点。不需要复制列表,这取决于python版本。
  • 是的,可能,如果它是最好动态生成的东西,因为它取决于版本,那么肯定有这种情况。然而,列表本身可能对人类和/或搜索引擎有用。身份证
【解决方案2】:

您可能希望将 __builtins__.__dict__.keys()sys.builtin_module_names 添加到该列表中

【讨论】:

    猜你喜欢
    • 2017-05-28
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    • 2010-09-07
    相关资源
    最近更新 更多