Python - Things one MUST avoid
        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
            14:38 UTC
        
        
        Read the original article
        Hit count: 338
        
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?
1> Mutable default arguments
2> import modules always same way e.g. 'from y import x' and 'import x' are totally different things actually they are treated as different modules see http://stackoverflow.com/questions/1459236/module-reimported-if-imported-from-different-path
3> Do not use range in place of lists because range() will become an iterator anyway, so things like this will fail, so wrap it by list
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 e.g myIndexList == xrange(3).
4> 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, instead use
try:
    raise KeyError("hmm bug")
except (KeyError,TypeError):
    print TypeError
© Stack Overflow or respective owner