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?
Use a syntax-highlighting text editor that will highlight keywords in a different color from the rest of the code.
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).
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 = [ ... ]
pylint will find this error (among many others).
来源:https://stackoverflow.com/questions/5168830/how-to-stop-myself-overwriting-python-functions-when-coding