How to stop myself overwriting Python functions when coding?

馋奶兔 提交于 2019-12-06 01:49:57

问题


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?


回答1:


Use a syntax-highlighting text editor that will highlight keywords in a different color from the rest of the code.




回答2:


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




回答3:


Tools like PyChecker may be valuable for you. See also this SO discussion.




回答4:


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

list_with_duplicates = [ ... ]



回答5:


pylint will find this error (among many others).



来源:https://stackoverflow.com/questions/5168830/how-to-stop-myself-overwriting-python-functions-when-coding

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