6

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?

Nick Loman
  • 71
  • 4
  • 2
    I'm pretty sure the real solution is not to use variables with dummy names like `list` in your actual code... after a while descriptive variable naming becomes a habit and it's much easier to read later. – Katriel Mar 02 '11 at 14:35
  • 1
    Agreed. Something like `possible_duplicates` (or even `letters`) would be better in your example. Give things names based on what they represent, not what they are. Calling it `list` does not help the reader: they can *see* it's a list. – kindall Mar 02 '11 at 15:42
  • Part of me thinks that why they are not restriced and cause syntax errors. – Jakob Bowyer Mar 02 '11 at 15:55

5 Answers5

9

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

Botond Béres
  • 16,057
  • 2
  • 37
  • 50
3

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

Community
  • 1
  • 1
eat
  • 7,440
  • 1
  • 19
  • 27
  • Thanks - it's a good suggestion but I found it was hard to get working with my Django project. Also it picks up a lot of other code problems that I may or may not want to fix. – Nick Loman Mar 07 '11 at 11:42
3

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

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
2

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 = [ ... ]
Ekkehard.Horner
  • 38,498
  • 2
  • 45
  • 96
  • This is a good point, particularly for larger projects, but I am in the habit of writing short scripts to carry out a defined purpose and in this context sometimes calling a variable set (or "map" or "list") is not an absolute coding crime. – Nick Loman Mar 07 '11 at 11:41
0

pylint will find this error (among many others).

kindall
  • 178,883
  • 35
  • 278
  • 309