如何在编码时阻止自己覆盖 Python 函数?
在跟踪 Python 代码中的错误时,一个令人头疼的问题是看似无害的代码片段,如下所示:
list = ['a', 'b', 'c', 'c']
list(set(list))
由于我用变量列表覆盖了函数 list(),所以失败了。
显然是一个人为的例子,但重点是 Python 很高兴让我用变量覆盖内置函数。我意识到这是 Python 中的一个重要功能,但如果解释器在我在代码中执行此操作时能够警告我,我会非常希望它,因为我通常不想这样做。
任何人都可以提出一个解决方案(除了更加小心之外)-因为我一直被这个问题绊倒?
A source of constant headache when tracking down bugs in my Python code are seemingly innocuous snippets like this:
list = ['a', 'b', 'c', 'c']
list(set(list))
This fails because I've overwritten the function list() with the variable list.
A contrived example obviously, but the point is Python happily lets me overwrite built-in functions with variables. I realise this is a crucial feature in Python but I would quite like it if the interpreter would warn me when I do it in my code as I usually don't mean to do this.
Can anyone suggest a solution (other than just being more careful) - as I keep tripping over this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您应该使用 Pylint。如果您使用 Eclipse + PyDev,您可以将其配置为在 IDE 中自动运行并突出显示此问题(以及许多其他问题)。
You should use Pylint. If you are using Eclipse + PyDev, you can configure it to run automatically within the IDE and highlight this issue (and many many others).
使用语法突出显示文本编辑器,该编辑器将以与代码其余部分不同的颜色突出显示关键字。
Use a syntax-highlighting text editor that will highlight keywords in a different color from the rest of the code.
像 PyChecker 这样的工具可能对您很有价值。另请参阅此 SO讨论。
Tools like PyChecker may be valuable for you. See also this SO discussion.
不小心使用保留名称是一个普遍问题;一般的补救措施是为您自己的对象使用“好”名称(广义上)。这里的“好”是指名称可以根据要解决的问题的上下文告诉您有关命名对象的相关事实。
对于玩具问题,这可能看起来需要付出很大的努力,但是即使您只是编写代码来学习语言(的功能),为什么不训练良好的命名呢?所以使用你的版本
Accidentially using reserved names is a general problem; the general remedy is to use 'good' names for your own objects (in a broad sense). 'Good' here means names that tell you the relevant facts about the named object based on the context of the problem to solve.
For toy problems this may look like just to much effort, but why not train good naming even when you just write code to learn (features of) a language? So use your version of
pylint 将发现此错误(以及许多其他错误)。
pylint will find this error (among many others).