Python 变量名与语言关键字、内建函数冲突的解决办法

在写 Python 代码的时候有时候会遇到变量需要叫 typeclass 的情况。但 type 是一个 Python 的 👉 built-in functionclass 是一个 keyword

有一种解决方法是在变量后加单下划线得到 type_,代码里也已经有地方在用,符合 PEP8 的规范。参考:Can I use the variable name "type" as function argument in Python? - Stack Overflow


附:

判断是否是关键字,以及获取所有关键字(32.6. keyword — Testing for Python keywords — Python 2.7.14 documentation

import keyword
print(', '.join(keyword.kwlist))
# 'and, as, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while, with, yield'
posted @ 2017-09-30 18:20  常伟佳  阅读(1428)  评论(0编辑  收藏  举报