Common Pitfalls in Python
Posted
by Anurag Uniyal
on Stack Overflow
See other posts from Stack Overflow
or by Anurag Uniyal
Published on 2009-06-18T08:19:11Z
Indexed on
2010/05/02
15:18 UTC
Read the original article
Hit count: 417
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
andimport x
are different things, they are treated as different modules.Do not use
range
in place oflists
becauserange()
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
© Stack Overflow or respective owner