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!
You probably want to check against __builtins__ keys:
>>> __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',
'_']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With