Today I was bitten again by "Mutable default arguments" after many years. I usually don't use mutable default arguments unless needed but I think with time I forgot about that, and today in the application I added tocElements=[] in a pdf generation function's argument list and now 'Table of Content' gets longer and longer after each invocation of "generate pdf" :)
My question is what other things should I add to my list of things to MUST avoid?
Mutable default arguments
Import modules always same way e.g. from y import x and import x are different things, they are treated as different modules.
Do not use range in place of lists because range() will become an iterator anyway, the following will fail:
myIndexList = [0,1,3]
isListSorted = myIndexList == range(3) # will fail in 3.0
isListSorted = myIndexList == list(range(3)) # will not
same thing can be mistakenly done with xrange:
`myIndexList == xrange(3)`.
Catching multiple exceptions
try:
raise KeyError("hmm bug")
except KeyError,TypeError:
print TypeError
It prints "hmm bug", though it is not a bug, it looks like we are catching exceptions of type KeyError,TypeError but instead we are catching KeyError only as variable TypeError, use this instead:
try:
raise KeyError("hmm bug")
except (KeyError,TypeError):
print TypeError