Note that there are some explanatory texts on larger screens.

plurals
  1. POCommon pitfalls in Python
    text
    copied!<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/530530/python-2-x-gotchas-and-landmines">Python 2.x gotcha&rsquo;s and landmines</a> </p> </blockquote> <p>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. Today in the application I added tocElements=[] in a PDF generation function's argument list and now "Table of Contents" gets longer and longer after each invocation of "generate pdf". :)</p> <p>What else should I add to my list of things to MUST avoid?</p> <ul> <li><p>Always import modules the same way, e.g. <code>from y import x</code> and <code>import x</code> are <a href="https://stackoverflow.com/questions/1459236/module-reimported-if-imported-from-different-path">treated as different modules</a>.</p></li> <li><p>Do not use <em>range</em> in place of lists because <code>range()</code> will become an iterator anyway, the following will fail:</p> <pre><code>myIndexList = [0, 1, 3] isListSorted = myIndexList == range(3) # will fail in 3.0 isListSorted = myIndexList == list(range(3)) # will not </code></pre> <p>Same thing can be mistakenly done with <em>xrange:</em></p> <pre><code>myIndexList == xrange(3) </code></pre></li> <li><p>Be careful catching multiple exception types:</p> <pre><code>try: raise KeyError("hmm bug") except KeyError, TypeError: print TypeError </code></pre> <p>This prints "hmm bug", though it is not a bug; it looks like we are catching exceptions of both types, but instead we are catching KeyError only as variable <em>TypeError,</em> use this instead:</p> <pre><code>try: raise KeyError("hmm bug") except (KeyError, TypeError): print TypeError </code></pre></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload