Things you shouldn't do

Steve dippyd at yahoo.com
Wed Mar 30 05:44:00 CEST 2005


All names have been removed to protect the guilty :-)

In an earlier post, I read a piece of code:

>>> l1 = [1, 2, 3]
>>> l2 = [1, 2, 3]
>>> l1 == l2
True

I immediately gave a double-take: 11 equals 12? What 
gives? Can you re-bind literals in Python???

 >>> 11 = [1, 2, 3]
SyntaxError: can't assign to literal

And then it hit me. That wasn't eleven and twelve, the 
variable names were lowercase L with the digits one and 
two appended.

Imagine running a long piece of code on some test data 
and finding an off-by-one bug which you think is on the 
line "myvalue = something + l1". You change the eleven 
to 12 and now the code works on your test data but not 
for anything else.

If you have access to a syntax-aware  editor, it will 
help avoid such problems, but better to avoid them in 
the first place. You might be reading code printed in 
black and white on dead tree one day.

Lesson the first: remember that in many fonts, zero and 
capital O are identical, as are lowercase L and 1 and 
sometimes even uppercase I. Avoid using names which can 
be easily confused for literals or for each other.

What are some of other people's favourite tips for 
avoiding bugs in the first place, as opposed to finding 
them once you know they are there?


-- 
Steven





More information about the Python-list mailing list