python非法变量名,Python中要避免的变量名称

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()

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值