Variable names to avoid in Python [duplicate]

孤街醉人 提交于 2019-12-18 09:24:24

问题


Is there a list somewhere (or better yet, a module!) that I can use to check whether a string is a "bad" choice for a variable name, where "bad" is defined as something like "is a keyword or built-in function etc."?

I have a script that generates Python classes from a Jinja template (Django models to be precise) and I'd like to fix any field names that are unsuitable for reasons like the ones I mentioned above.

So far, I've got a check that looks like this:

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

So another way of phrasing my question would be: what else should I put in that list along with "type" ?

I realize that there can't be any complete list since it will vary depending on what is defined in other modules I'm using, but I wonder if there is a good list of things that should pretty much never be used. Thanks!


回答1:


You probably want to check against __builtins__ keys:

>>> __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'])



回答2:


You might want to add __builtins__.__dict__.keys() and sys.builtin_module_names to that list



来源:https://stackoverflow.com/questions/42378996/variable-names-to-avoid-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!