apicard@google.com | 7dbc495 | 2009-07-23 20:19:09 +0000 | [diff] [blame] | 1 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/REC-html4/strict.dtd"> |
apicard@google.com | 9d23408 | 2009-07-23 20:29:34 +0000 | [diff] [blame] | 2 | <HTML> |
apicard@google.com | f900c2c | 2009-07-23 20:09:56 +0000 | [diff] [blame] | 3 | <HEAD> |
| 4 | <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> |
| 5 | <TITLE>Google Python Style Guide</TITLE> |
| 6 | <LINK HREF="http://www.google.com/favicon.ico" type="image/x-icon" rel="shortcut icon"> |
| 7 | <LINK HREF="styleguide.css" type="text/css" rel="stylesheet"> |
| 8 | <SCRIPT language="javascript" type="text/javascript"> |
| 9 | |
| 10 | function ShowHideByName(bodyName, buttonName) { |
| 11 | var bodyElements; |
| 12 | if (document.getElementsByName) { |
| 13 | bodyElements = document.getElementsByName(bodyName); |
| 14 | } else { |
| 15 | bodyElements = [document.getElementById(bodyName)]; |
| 16 | } |
| 17 | if (bodyElements.length != 1) { |
| 18 | alert("ShowHideByName() got the wrong number of bodyElements: " + bodyElements.length); |
| 19 | } else { |
| 20 | var bodyElement = bodyElements[0]; |
| 21 | var buttonElement; |
| 22 | if (document.getElementsByName) { |
| 23 | var buttonElements = document.getElementsByName(buttonName); |
| 24 | buttonElement = buttonElements[0]; |
| 25 | } else { |
| 26 | buttonElement = document.getElementById(buttonName); |
| 27 | } |
| 28 | if (bodyElement.style.display == "none" || bodyElement.style.display == "") { |
| 29 | bodyElement.style.display = "inline"; |
| 30 | buttonElement.innerHTML = '▽'; |
| 31 | } else { |
| 32 | bodyElement.style.display = "none"; |
| 33 | buttonElement.innerHTML = '▶'; |
| 34 | } |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | function ShowHideAll() { |
| 39 | var allButton; |
| 40 | if (document.getElementsByName) { |
| 41 | var allButtons = document.getElementsByName("show_hide_all_button"); |
| 42 | allButton = allButtons[0]; |
| 43 | } else { |
| 44 | allButton = document.getElementById("show_hide_all_button"); |
| 45 | } |
| 46 | if (allButton.innerHTML == '▽') { |
| 47 | allButton.innerHTML = '▶'; |
| 48 | SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "none", '▶'); |
| 49 | } else { |
| 50 | allButton.innerHTML = '▽'; |
| 51 | SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "inline", '▽'); |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | // Recursively sets state of all children |
| 56 | // of a particular node. |
| 57 | function SetHiddenState(root, newState, newButton) { |
| 58 | for (var i = 0; i != root.length; i++) { |
| 59 | SetHiddenState(root[i].childNodes, newState, newButton); |
| 60 | if (root[i].className == 'showhide_button') { |
| 61 | root[i].innerHTML = newButton; |
| 62 | } |
| 63 | if (root[i].className == 'stylepoint_body') { |
| 64 | root[i].style.display = newState; |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | |
| 70 | window.onload = function() { |
| 71 | // if the URL contains "?showall=y", expand the details of all children |
| 72 | { |
| 73 | var showHideAllRegex = new RegExp("[\\?&](showall)=([^&#]*)"); |
| 74 | var showHideAllValue = showHideAllRegex.exec(window.location.href); |
| 75 | if (showHideAllValue != null) { |
| 76 | if (showHideAllValue[2] == "y") { |
| 77 | SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "inline", '▽'); |
| 78 | } else { |
| 79 | SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "none", '▶'); |
| 80 | } |
| 81 | } |
| 82 | var showOneRegex = new RegExp("[\\?&](showone)=([^&#]*)"); |
| 83 | var showOneValue = showOneRegex.exec(window.location.href); |
| 84 | if (showOneValue != null) { |
| 85 | var body_name = showOneValue[2] + '__body'; |
| 86 | var button_name = showOneValue[2] + '__button'; |
| 87 | ShowHideByName(body_name, button_name); |
| 88 | } |
| 89 | |
| 90 | } |
| 91 | } |
| 92 | </SCRIPT> |
| 93 | </HEAD> |
| 94 | <BODY> |
| 95 | <H1>Google Python Style Guide</H1> |
| 96 | <p align="right"> |
| 97 | |
| 98 | Revision 2.12 |
| 99 | </p> |
| 100 | |
| 101 | <address> |
| 102 | Amit Patel<br> |
| 103 | Antoine Picard<br> |
| 104 | Eugene Jhong<br> |
| 105 | Jeremy Hylton<br> |
| 106 | Matt Smart<br> |
| 107 | Mike Shields<br> |
| 108 | </address> |
| 109 | <DIV style="margin-left: 50%; font-size: 75%;"> |
| 110 | <P> |
| 111 | Each style point has a summary for which additional information is available |
| 112 | by toggling the accompanying arrow button that looks this way: |
| 113 | <SPAN class="showhide_button" style="margin-left: 0;">▶</SPAN>. |
| 114 | You may toggle all summaries with the big arrow button: |
| 115 | </P> |
| 116 | <DIV style=" font-size: larger; margin-left: +2em;"> |
| 117 | <SPAN class="showhide_button" style="font-size: 180%;" onclick="javascript:ShowHideAll()" name="show_hide_all_button" id="show_hide_all_button">▶</SPAN> |
| 118 | Toggle all summaries |
| 119 | </DIV> |
| 120 | </DIV> |
| 121 | <DIV class="toc"> |
| 122 | <DIV class="toc_title">Table of Contents</DIV> |
| 123 | <TABLE> |
| 124 | <TR valign="top" class=""> |
| 125 | <TD><DIV class="toc_category"><A href="#Python_Language_Rules">Python Language Rules</A></DIV></TD> |
| 126 | <TD><DIV class="toc_stylepoint"> |
| 127 | <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#pychecker">pychecker</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Imports">Imports</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Packages">Packages</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Exceptions">Exceptions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Global_variables">Global variables</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Nested/Local/Inner_Classes_and_Functions">Nested/Local/Inner Classes and Functions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#List_Comprehensions">List Comprehensions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Default_Iterators_and_Operators">Default Iterators and Operators</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Generators">Generators</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Using_apply,_filter,_map,_reduce">Using apply, filter, map, reduce</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Lambda_Functions">Lambda Functions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Default_Argument_Values">Default Argument Values</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Properties">Properties</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#True/False_evaluations">True/False evaluations</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#String_Methods">String Methods</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Lexical_Scoping">Lexical Scoping</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Function_and_Method_Decorators">Function and Method Decorators</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Threading">Threading</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Power_Features">Power Features</A></SPAN> </DIV></TD> |
| 128 | </TR> |
| 129 | <TR valign="top" class=""> |
| 130 | <TD><DIV class="toc_category"><A href="#Python_Style_Rules">Python Style Rules</A></DIV></TD> |
| 131 | <TD><DIV class="toc_stylepoint"> |
| 132 | <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Semicolons">Semicolons</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Line_length">Line length</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Parentheses">Parentheses</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Indentation">Indentation</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Blank_Lines">Blank Lines</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Whitespace">Whitespace</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Python_Interpreter">Python Interpreter</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Comments">Comments</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Classes">Classes</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Strings">Strings</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#TODO_Comments">TODO Comments</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Imports_formatting">Imports formatting</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Statements">Statements</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Access_Control">Access Control</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Naming">Naming</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Main">Main</A></SPAN> </DIV></TD> |
| 133 | </TR> |
| 134 | </TABLE> |
| 135 | </DIV> |
| 136 | <H2>Overview</H2> |
| 137 | <SPAN class=""><H2 name="Important_Note" id="Important_Note">Important Note</H2> |
| 138 | <SPAN class=""><H3><A name="Displaying_Hidden_Details_in_this_Guide" id="Displaying_Hidden_Details_in_this_Guide">Displaying Hidden Details in this Guide</A></H3> |
| 139 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Displaying_Hidden_Details_in_this_Guide__body','Displaying_Hidden_Details_in_this_Guide__button')" name="Displaying_Hidden_Details_in_this_Guide__button" id="Displaying_Hidden_Details_in_this_Guide__button">▶</SPAN> |
| 140 | <SPAN class=""> |
| 141 | This style guide contains many details that are initially |
| 142 | hidden from view. They are marked by the triangle icon, which you |
| 143 | see here on your left. Click it now. |
| 144 | You should see "Hooray" appear below. |
| 145 | </SPAN> |
| 146 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Displaying_Hidden_Details_in_this_Guide__body" id="Displaying_Hidden_Details_in_this_Guide__body" style="display: none"><SPAN class="link_button"><A href="?showone=Displaying_Hidden_Details_in_this_Guide#Displaying_Hidden_Details_in_this_Guide"> |
| 147 | link |
| 148 | </A></SPAN> |
| 149 | <p> |
| 150 | Hooray! Now you know you can expand points to get more |
| 151 | details. Alternatively, there's a "toggle all" at the |
| 152 | top of this document. |
| 153 | </p> |
| 154 | </SPAN></SPAN> |
| 155 | </SPAN> |
| 156 | </SPAN> |
| 157 | <SPAN class=""><H2 name="Background" id="Background">Background</H2> |
| 158 | <p> |
| 159 | Python is the main scripting language used at Google. This |
| 160 | style guide is a list of <em>do</em>s and <em>don't</em>s for Python |
| 161 | programs. |
| 162 | </p> |
| 163 | |
| 164 | |
| 165 | |
| 166 | </SPAN> |
| 167 | |
| 168 | <SPAN class=""><H2 name="Python_Language_Rules" id="Python_Language_Rules">Python Language Rules</H2> |
| 169 | |
| 170 | <SPAN class=""><H3><A name="pychecker" id="pychecker">pychecker</A></H3> |
| 171 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('pychecker__body','pychecker__button')" name="pychecker__button" id="pychecker__button">▶</SPAN> |
| 172 | <SPAN class=""> |
| 173 | Run <code>pychecker</code> over your code. |
| 174 | </SPAN> |
| 175 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="pychecker__body" id="pychecker__body" style="display: none"><SPAN class="link_button"><A href="?showone=pychecker#pychecker"> |
| 176 | link |
| 177 | </A></SPAN> |
| 178 | <P class=""> |
| 179 | <SPAN class="stylepoint_section">Definition: </SPAN> |
| 180 | PyChecker is a tool for finding bugs in Python source code. It finds |
| 181 | problems that are typically caught by a compiler for less dynamic |
| 182 | languages like C and C++. It is similar to lint. Because of the |
| 183 | dynamic nature of Python, some warnings may be incorrect; however, |
| 184 | spurious warnings should be fairly infrequent. |
| 185 | </P> |
| 186 | <P class=""> |
| 187 | <SPAN class="stylepoint_section">Pros: </SPAN> |
| 188 | Catches easy-to-miss errors like typos, use-vars-before-assignment, etc. |
| 189 | </P> |
| 190 | <P class=""> |
| 191 | <SPAN class="stylepoint_section">Cons: </SPAN> |
| 192 | <code>pychecker</code> isn't perfect. To take |
| 193 | advantage of it, we'll need to sometimes: a) Write around it b) |
| 194 | Suppress its warnings c) Improve it or d) Ignore it. |
| 195 | </P> |
| 196 | <P class=""> |
| 197 | <SPAN class="stylepoint_section">Decision: </SPAN> |
| 198 | Make sure you run <code>pychecker</code> on your code. |
| 199 | </P> |
| 200 | |
| 201 | <p> |
| 202 | For information on how to run <code>pychecker</code>, see the |
| 203 | <a HREF="http://pychecker.sourceforge.net">pychecker |
| 204 | homepage</a> |
| 205 | </p> |
| 206 | <p> |
| 207 | To suppress warnings, you can set a module-level variable named |
| 208 | <code>__pychecker__</code> to suppress appropriate warnings. |
| 209 | For example: |
| 210 | </p> |
| 211 | <SPAN class=""><PRE> |
| 212 | <span class="external"></span>__pychecker__ = 'no-callinit no-classattr'</PRE></SPAN> |
| 213 | <p> |
| 214 | Suppressing in this way has the advantage that we can easily search |
| 215 | for suppressions and revisit them. |
| 216 | </p> |
| 217 | <p> |
| 218 | You can get a list of pychecker warnings by doing |
| 219 | <code>pychecker --help</code>. |
| 220 | </p> |
| 221 | <p> |
| 222 | Unused argument warnings can be suppressed by using `_' as the |
| 223 | identifier for the unused argument or prefixing the argument name with |
| 224 | `unused_'. In situations where changing the argument names is |
| 225 | infeasible, you can mention them at the beginning of the function. |
| 226 | For example: |
| 227 | </p> |
| 228 | <SPAN class=""><PRE> |
| 229 | <span class="external"></span>def foo(a, unused_b, unused_c, d=None, e=None): |
| 230 | <span class="external"> </span>(d, e) = (d, e) # Silence pychecker |
| 231 | <span class="external"> </span>return a |
| 232 | <span class="external"></span> |
| 233 | </PRE></SPAN> |
| 234 | <p> |
| 235 | Ideally, pychecker would be extended to ensure that such `unused |
| 236 | declarations' were true. |
| 237 | </p> |
| 238 | |
| 239 | </SPAN></SPAN> |
| 240 | </SPAN> |
| 241 | <SPAN class=""><H3><A name="Imports" id="Imports">Imports</A></H3> |
| 242 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Imports__body','Imports__button')" name="Imports__button" id="Imports__button">▶</SPAN> |
| 243 | <SPAN class=""> |
| 244 | Use <code>import</code>s for packages and modules only. |
| 245 | </SPAN> |
| 246 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Imports__body" id="Imports__body" style="display: none"><SPAN class="link_button"><A href="?showone=Imports#Imports"> |
| 247 | link |
| 248 | </A></SPAN> |
| 249 | <P class=""> |
| 250 | <SPAN class="stylepoint_section">Definition: </SPAN> |
| 251 | Reusability mechanism for sharing code from one module to another. |
| 252 | </P> |
| 253 | <P class=""> |
| 254 | <SPAN class="stylepoint_section">Pros: </SPAN> |
| 255 | Simplest and most commonly used way of sharing things. |
| 256 | </P> |
| 257 | <P class=""> |
| 258 | <SPAN class="stylepoint_section">Cons: </SPAN> <code>from foo import *</code> or |
| 259 | <code>from foo import Bar</code> is |
| 260 | very nasty and can lead to serious maintenance issues because |
| 261 | it makes it hard to find module dependencies. |
| 262 | </P> |
| 263 | <P class=""> |
| 264 | <SPAN class="stylepoint_section">Decision: </SPAN> |
| 265 | Use <code>import x</code> for importing packages and modules. |
| 266 | Use <code>from x import y</code> only when <code>x</code> is a |
| 267 | package and <code>y</code> is a module. This allows the |
| 268 | importer to refer to the module without specifying the full |
| 269 | package prefix. For example the module |
| 270 | <code>sound.effects.echo</code> may be imported as follows: |
| 271 | </P> |
| 272 | <SPAN class=""><PRE> |
| 273 | <span class="external"></span>from sound.effects import echo |
| 274 | <span class="external"></span>... |
| 275 | <span class="external"></span>echo.echofilter(input, output, delay=0.7, atten=4) |
| 276 | <span class="external"></span> |
| 277 | </PRE></SPAN> |
| 278 | <p> |
| 279 | Even if the module is in the same package, do not directly import |
| 280 | the module without the full package name. This might cause the |
| 281 | package to be imported twice (with unintended side effects) when the |
| 282 | "main" module that is used to start an application lives inside a |
| 283 | package (and uses modules from that same package). |
| 284 | </p> |
| 285 | </SPAN></SPAN> |
| 286 | </SPAN> |
| 287 | <SPAN class=""><H3><A name="Packages" id="Packages">Packages</A></H3> |
| 288 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Packages__body','Packages__button')" name="Packages__button" id="Packages__button">▶</SPAN> |
| 289 | <SPAN class=""> |
| 290 | Import and refer to each module using the full pathname location of |
| 291 | that module. |
| 292 | </SPAN> |
| 293 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Packages__body" id="Packages__body" style="display: none"><SPAN class="link_button"><A href="?showone=Packages#Packages"> |
| 294 | link |
| 295 | </A></SPAN> |
| 296 | <P class=""> |
| 297 | <SPAN class="stylepoint_section">Pros: </SPAN> |
| 298 | Avoids conflicts in module names. Makes it easier to find modules. |
| 299 | </P> |
| 300 | <P class=""> |
| 301 | <SPAN class="stylepoint_section">Cons: </SPAN> |
| 302 | Makes it harder to deploy code because you have to replicate the |
| 303 | package hierarchy. |
| 304 | </P> |
| 305 | <P class=""> |
| 306 | <SPAN class="stylepoint_section">Decision: </SPAN> |
| 307 | All new code should refer to modules based on their package |
| 308 | name. |
| 309 | </P> |
| 310 | <p> |
| 311 | Imports should be as follows: |
| 312 | </p> |
| 313 | |
| 314 | |
| 315 | <SPAN class=""><PRE># Reference in code with complete name. |
| 316 | import sound.effects.echo |
| 317 | |
| 318 | # Reference in code with just module name. |
| 319 | from sound.effects import echo |
| 320 | </PRE></SPAN> |
| 321 | |
| 322 | </SPAN></SPAN> |
| 323 | </SPAN> |
| 324 | <SPAN class=""><H3><A name="Exceptions" id="Exceptions">Exceptions</A></H3> |
| 325 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Exceptions__body','Exceptions__button')" name="Exceptions__button" id="Exceptions__button">▶</SPAN> |
| 326 | <SPAN class=""> |
| 327 | Exceptions are allowed but must be used carefully. |
| 328 | </SPAN> |
| 329 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Exceptions__body" id="Exceptions__body" style="display: none"><SPAN class="link_button"><A href="?showone=Exceptions#Exceptions"> |
| 330 | link |
| 331 | </A></SPAN> |
| 332 | <P class=""> |
| 333 | <SPAN class="stylepoint_section">Definition: </SPAN> |
| 334 | Exceptions are a means of breaking out of the normal flow of control |
| 335 | of a code block to handle errors or other exceptional conditions. |
| 336 | </P> |
| 337 | <P class=""> |
| 338 | <SPAN class="stylepoint_section">Pros: </SPAN> |
| 339 | The control flow of normal operation code is not cluttered by |
| 340 | error-handling code. It also allows the control flow to skip multiple |
| 341 | frames when a certain condition occurs, e.g., returning from N |
| 342 | nested functions in one step instead of having to carry-through |
| 343 | error codes. |
| 344 | </P> |
| 345 | <P class=""> |
| 346 | <SPAN class="stylepoint_section">Cons: </SPAN> |
| 347 | May cause the control flow to be confusing. Easy to miss error |
| 348 | cases when making library calls. |
| 349 | </P> |
| 350 | <P class=""> |
| 351 | <SPAN class="stylepoint_section">Decision: </SPAN> |
| 352 | |
| 353 | |
| 354 | Exceptions must follow certain conditions: |
| 355 | |
| 356 | <ul> |
| 357 | <li>Raise exceptions like this: <code>raise MyException("Error |
| 358 | message")</code> or <code>raise MyException</code>. Do not |
| 359 | use the two-argument form (<code>raise MyException, "Error |
| 360 | message"</code>) or deprecated string-based exceptions |
| 361 | (<code>raise "Error message"</code>).</li> |
| 362 | <li>Modules or packages should define their own domain-specific |
| 363 | base exception class, which should inherit from the built-in |
| 364 | Exception class. The base exception for a module should be called |
| 365 | <code>Error</code>. |
| 366 | <SPAN class=""><PRE> |
| 367 | <span class="external"></span>class Error(Exception): |
| 368 | <span class="external"> </span>pass</PRE></SPAN> |
| 369 | </li> |
| 370 | <li>Never use catch-all <code>except:</code> statements, or |
| 371 | catch <code>Exception</code> or <code>StandardError</code>, |
| 372 | unless you are re-raising the exception or in the outermost |
| 373 | block in your thread (and printing an error message). Python |
| 374 | is very tolerant in this regard and <code>except:</code> will |
| 375 | really catch everything including Python syntax errors. It is |
| 376 | easy to hide real bugs using <code>except:</code>.</li> |
| 377 | <li>Minimize the amount of code in a |
| 378 | <code>try</code>/<code>except</code> block. The larger the |
| 379 | body of the <code>try</code>, the more likely that an |
| 380 | exception will be raised by a line of code that you didn't |
| 381 | expect to raise an exception. In those cases, |
| 382 | the <code>try</code>/<code>except</code> block hides a real |
| 383 | error.</li> |
| 384 | <li>Use the <code>finally</code> clause to execute code whether |
| 385 | or not an exception is raised in the <code>try</code> block. |
| 386 | This is often useful for cleanup, i.e., closing a file.</li> |
| 387 | </ul> |
| 388 | </P> |
| 389 | </SPAN></SPAN> |
| 390 | </SPAN> |
| 391 | <SPAN class=""><H3><A name="Global_variables" id="Global_variables">Global variables</A></H3> |
| 392 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Global_variables__body','Global_variables__button')" name="Global_variables__button" id="Global_variables__button">▶</SPAN> |
| 393 | <SPAN class=""> |
| 394 | Avoid global variables. |
| 395 | </SPAN> |
| 396 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Global_variables__body" id="Global_variables__body" style="display: none"><SPAN class="link_button"><A href="?showone=Global_variables#Global_variables"> |
| 397 | link |
| 398 | </A></SPAN> |
| 399 | <P class=""> |
| 400 | <SPAN class="stylepoint_section">Definition: </SPAN> |
| 401 | Variables that are declared at the module level. |
| 402 | </P> |
| 403 | <P class=""> |
| 404 | <SPAN class="stylepoint_section">Pros: </SPAN> |
| 405 | Occasionally useful. |
| 406 | </P> |
| 407 | <P class=""> |
| 408 | <SPAN class="stylepoint_section">Cons: </SPAN> |
| 409 | Has the potential to change module behavior during the import, |
| 410 | because assignments to module-level variables are done when the |
| 411 | module is imported. |
| 412 | </P> |
| 413 | <P class=""> |
| 414 | <SPAN class="stylepoint_section">Decision: </SPAN> |
| 415 | Avoid global variables in favor of class variables. Some |
| 416 | exceptions are: |
| 417 | <ul> |
| 418 | <li>Default options for scripts.</li> |
| 419 | <li>Module-level constants. For example: <code>PI = 3.14159</code>. |
| 420 | Constants should be named using all caps with underscores; |
| 421 | see <a HREF="#Naming">Naming</a> below.</li> |
| 422 | <li>It is sometimes useful for globals to cache values needed |
| 423 | or returned by functions.</li> |
| 424 | <li>If needed, globals should be made internal to the module |
| 425 | and accessed through public module level functions; |
| 426 | see <a HREF="#Naming">Naming</a> below.</li> |
| 427 | </ul> |
| 428 | </P> |
| 429 | </SPAN></SPAN> |
| 430 | </SPAN> |
| 431 | <SPAN class=""><H3><A name="Nested/Local/Inner_Classes_and_Functions" id="Nested/Local/Inner_Classes_and_Functions">Nested/Local/Inner Classes and Functions</A></H3> |
| 432 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Nested/Local/Inner_Classes_and_Functions__body','Nested/Local/Inner_Classes_and_Functions__button')" name="Nested/Local/Inner_Classes_and_Functions__button" id="Nested/Local/Inner_Classes_and_Functions__button">▶</SPAN> |
| 433 | <SPAN class=""> |
| 434 | Nested/local/inner classes and functions are fine. |
| 435 | </SPAN> |
| 436 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Nested/Local/Inner_Classes_and_Functions__body" id="Nested/Local/Inner_Classes_and_Functions__body" style="display: none"><SPAN class="link_button"><A href="?showone=Nested/Local/Inner_Classes_and_Functions#Nested/Local/Inner_Classes_and_Functions"> |
| 437 | link |
| 438 | </A></SPAN> |
| 439 | <P class=""> |
| 440 | <SPAN class="stylepoint_section">Definition: </SPAN> |
| 441 | A class can be defined inside of a function or class. A function |
| 442 | can be defined inside a function. Nested functions have read-only |
| 443 | access to variables defined in enclosing scopes. |
| 444 | </P> |
| 445 | <P class=""> |
| 446 | <SPAN class="stylepoint_section">Pros: </SPAN> |
| 447 | Allows definition of utility classes and functions that are only |
| 448 | used inside of a very limited scope. Very <a HREF="http://en.wikipedia.org/wiki/Abstract_data_type">ADT</a>-y. |
| 449 | </P> |
| 450 | <P class=""> |
| 451 | <SPAN class="stylepoint_section">Cons: </SPAN> |
| 452 | Instances of nested or local classes cannot be pickled. |
| 453 | </P> |
| 454 | <P class=""> |
| 455 | <SPAN class="stylepoint_section">Decision: </SPAN> |
| 456 | They are fine. |
| 457 | </P> |
| 458 | </SPAN></SPAN> |
| 459 | </SPAN> |
| 460 | <SPAN class=""><H3><A name="List_Comprehensions" id="List_Comprehensions">List Comprehensions</A></H3> |
| 461 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('List_Comprehensions__body','List_Comprehensions__button')" name="List_Comprehensions__button" id="List_Comprehensions__button">▶</SPAN> |
| 462 | <SPAN class=""> |
| 463 | Okay to use for simple cases. |
| 464 | </SPAN> |
| 465 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="List_Comprehensions__body" id="List_Comprehensions__body" style="display: none"><SPAN class="link_button"><A href="?showone=List_Comprehensions#List_Comprehensions"> |
| 466 | link |
| 467 | </A></SPAN> |
| 468 | <P class=""> |
| 469 | <SPAN class="stylepoint_section">Definition: </SPAN> |
| 470 | List comprehensions and generator expressions provide a concise |
| 471 | and efficient way to create lists and iterators without |
| 472 | resorting to the use of <code>map()</code>, |
| 473 | <code>filter()</code>, or <code>lambda</code>. |
| 474 | </P> |
| 475 | <P class=""> |
| 476 | <SPAN class="stylepoint_section">Pros: </SPAN> |
| 477 | Simple list comprehensions can be clearer and simpler than |
| 478 | other list creation techniques. Generator expressions can be |
| 479 | very efficient, since they avoid the creation of a list |
| 480 | entirely. |
| 481 | </P> |
| 482 | <P class=""> |
| 483 | <SPAN class="stylepoint_section">Cons: </SPAN> |
| 484 | Complicated list comprehensions or generator expressions can be |
| 485 | hard to read. |
| 486 | </P> |
| 487 | <P class=""> |
| 488 | <SPAN class="stylepoint_section">Decision: </SPAN> |
| 489 | Okay to use for simple cases. Each portion must fit on one line: |
| 490 | mapping expression, <code>for</code> clause, filter expression. |
| 491 | Multiple <code>for</code> clauses or filter expressions are not |
| 492 | permitted. Use loops instead when things get more complicated. |
| 493 | </P> |
| 494 | |
| 495 | <SPAN class=""><PRE class="badcode">No<span class="external"></span>: |
| 496 | <span class="external"></span>result = [(x, y) for x in range(10) for y in range(5) if x * y > 10] |
| 497 | |
| 498 | <span class="external"></span>return ((x, y, z) |
| 499 | <span class="external"></span> for x in xrange(5) |
| 500 | <span class="external"></span> for y in xrange(5) |
| 501 | <span class="external"></span> if x != y |
| 502 | <span class="external"></span> for z in xrange(5) |
| 503 | <span class="external"></span> if y != z)</PRE></SPAN> |
| 504 | <SPAN class=""><PRE>Ye<span class="external"></span>s: |
| 505 | <span class="external"></span>result = [] |
| 506 | <span class="external"></span>for x in range(10): |
| 507 | <span class="external"> </span>for y in range(5): |
| 508 | <span class="external"> </span>if x * y > 10: |
| 509 | <span class="external"> </span>result.append((x, y)) |
| 510 | |
| 511 | <span class="external"></span>for x in xrange(5): |
| 512 | <span class="external"> </span>for y in xrange(5): |
| 513 | <span class="external"> </span>if x != y: |
| 514 | <span class="external"> </span>for z in xrange(5): |
| 515 | <span class="external"> </span>if y != z: |
| 516 | <span class="external"> </span>yield (x, y, z) |
| 517 | |
| 518 | <span class="external"></span>return ((x, complicated_transform(x)) |
| 519 | <span class="external"></span> for x in long_generator_function(parameter) |
| 520 | <span class="external"></span> if x is not None) |
| 521 | |
| 522 | <span class="external"></span>squares = [x * x for x in range(10)] |
| 523 | |
| 524 | <span class="external"></span>eat(jelly_bean for jelly_bean in jelly_beans |
| 525 | <span class="external"></span> if jelly_bean.color == 'black')</PRE></SPAN> |
| 526 | </SPAN></SPAN> |
| 527 | </SPAN> |
| 528 | <SPAN class=""><H3><A name="Default_Iterators_and_Operators" id="Default_Iterators_and_Operators">Default Iterators and Operators</A></H3> |
| 529 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Default_Iterators_and_Operators__body','Default_Iterators_and_Operators__button')" name="Default_Iterators_and_Operators__button" id="Default_Iterators_and_Operators__button">▶</SPAN> |
| 530 | <SPAN class=""> |
| 531 | Use default iterators and operators for types that support them, |
| 532 | like lists, dictionaries, and files. |
| 533 | </SPAN> |
| 534 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Default_Iterators_and_Operators__body" id="Default_Iterators_and_Operators__body" style="display: none"><SPAN class="link_button"><A href="?showone=Default_Iterators_and_Operators#Default_Iterators_and_Operators"> |
| 535 | link |
| 536 | </A></SPAN> |
| 537 | <P class=""> |
| 538 | <SPAN class="stylepoint_section">Definition: </SPAN> |
| 539 | Container types, like dictionaries and lists, define default |
| 540 | iterators and membership test operators ("in" and "not in"). |
| 541 | </P> |
| 542 | <P class=""> |
| 543 | <SPAN class="stylepoint_section">Pros: </SPAN> |
| 544 | The default iterators and operators are simple and efficient. |
| 545 | They express the operation directly, without extra method calls. |
| 546 | A function that uses default operators is generic. It can be |
| 547 | used with any type that supports the operation. |
| 548 | </P> |
| 549 | <P class=""> |
| 550 | <SPAN class="stylepoint_section">Cons: </SPAN> |
| 551 | You can't tell the type of objects by reading the method names |
| 552 | (e.g. has_key() means a dictionary). This is also an advantage. |
| 553 | </P> |
| 554 | <P class=""> |
| 555 | <SPAN class="stylepoint_section">Decision: </SPAN> Use default iterators and operators for types |
| 556 | that support them, like lists, dictionaries, and files. The |
| 557 | built-in types define iterator methods, too. Prefer these |
| 558 | methods to methods that return lists, except that you should not |
| 559 | mutate a container while iterating over it. |
| 560 | |
| 561 | <SPAN class=""><PRE>Yes: <span class="external"></span>for key in adict: ... |
| 562 | <span class="external"></span>if key not in adict: ... |
| 563 | <span class="external"></span>if obj in alist: ... |
| 564 | <span class="external"></span>for line in afile: ... |
| 565 | <span class="external"></span>for k, v in dict.iteritems(): ...</PRE></SPAN> |
| 566 | <SPAN class=""><PRE class="badcode">No: <span class="external"></span>for key in adict.keys(): ... |
| 567 | <span class="external"></span>if not adict.has_key(key): ... |
| 568 | <span class="external"></span>for line in afile.readlines(): ...</PRE></SPAN> |
| 569 | </P> |
| 570 | </SPAN></SPAN> |
| 571 | </SPAN> |
| 572 | <SPAN class=""><H3><A name="Generators" id="Generators">Generators</A></H3> |
| 573 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Generators__body','Generators__button')" name="Generators__button" id="Generators__button">▶</SPAN> |
| 574 | <SPAN class=""> |
| 575 | Use generators as needed. |
| 576 | </SPAN> |
| 577 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Generators__body" id="Generators__body" style="display: none"><SPAN class="link_button"><A href="?showone=Generators#Generators"> |
| 578 | link |
| 579 | </A></SPAN> |
| 580 | <P class=""> |
| 581 | <SPAN class="stylepoint_section">Definition: </SPAN> |
| 582 | A generator function returns an iterator that yields a value each |
| 583 | time it executes a yield statement. After it yields a value, the |
| 584 | runtime state of the generator function is suspended until the |
| 585 | next value is needed. |
| 586 | </P> |
| 587 | <P class=""> |
| 588 | <SPAN class="stylepoint_section">Pros: </SPAN> |
| 589 | Simpler code, because the state of local variables and control flow |
| 590 | are preserved for each call. A generator uses less memory than a |
| 591 | function that creates an entire list of values at once. |
| 592 | </P> |
| 593 | <P class=""> |
| 594 | <SPAN class="stylepoint_section">Cons: </SPAN> |
| 595 | None. |
| 596 | </P> |
| 597 | <P class=""> |
| 598 | <SPAN class="stylepoint_section">Decision: </SPAN> |
| 599 | Fine. Use "Yields:" rather than "Returns:" in the |
| 600 | doc string for generator functions. |
| 601 | </P> |
| 602 | </SPAN></SPAN> |
| 603 | </SPAN> |
| 604 | <SPAN class=""><H3><A name="Using_apply,_filter,_map,_reduce" id="Using_apply,_filter,_map,_reduce">Using apply, filter, map, reduce</A></H3> |
| 605 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Using_apply,_filter,_map,_reduce__body','Using_apply,_filter,_map,_reduce__button')" name="Using_apply,_filter,_map,_reduce__button" id="Using_apply,_filter,_map,_reduce__button">▶</SPAN> |
| 606 | <SPAN class=""> |
| 607 | Avoid in favor of list comprehensions and for-loops. |
| 608 | </SPAN> |
| 609 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Using_apply,_filter,_map,_reduce__body" id="Using_apply,_filter,_map,_reduce__body" style="display: none"><SPAN class="link_button"><A href="?showone=Using_apply,_filter,_map,_reduce#Using_apply,_filter,_map,_reduce"> |
| 610 | link |
| 611 | </A></SPAN> |
| 612 | <P class=""> |
| 613 | <SPAN class="stylepoint_section">Definition: </SPAN> Built-in functions useful for manipulating |
| 614 | lists. Commonly used in conjunction with <code>lambda</code> |
| 615 | functions. |
| 616 | </P> |
| 617 | <P class=""> |
| 618 | <SPAN class="stylepoint_section">Pros: </SPAN> |
| 619 | Code is compact. |
| 620 | </P> |
| 621 | <P class=""> |
| 622 | <SPAN class="stylepoint_section">Cons: </SPAN> |
| 623 | Higher-order functional programming tends to be harder to understand. |
| 624 | </P> |
| 625 | <P class=""> |
| 626 | <SPAN class="stylepoint_section">Decision: </SPAN> Use list comprehensions when possible and limit |
| 627 | use to simple code and one-liners. In general, if such code |
| 628 | grows longer than 60–80 chars or if it uses |
| 629 | multi-level function calls (e.g., <code>map(lambda x: x[1], |
| 630 | filter(…))</code>), that's a signal that you are better |
| 631 | off writing a regular loop instead. Compare: |
| 632 | <SPAN class=""><PRE>Yes: <span class="external"></span>list comprehensions: [x[1] for x in my_list if x[2] == 5]</PRE></SPAN> |
| 633 | <SPAN class=""><PRE class="badcode">No: <span class="external"></span>map/filter: map(lambda x: x[1], filter(lambda x: x[2] == 5, my_list))</PRE></SPAN> |
| 634 | </P> |
| 635 | </SPAN></SPAN> |
| 636 | </SPAN> |
| 637 | <SPAN class=""><H3><A name="Lambda_Functions" id="Lambda_Functions">Lambda Functions</A></H3> |
| 638 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Lambda_Functions__body','Lambda_Functions__button')" name="Lambda_Functions__button" id="Lambda_Functions__button">▶</SPAN> |
| 639 | <SPAN class=""> |
| 640 | Okay for one-liners. |
| 641 | </SPAN> |
| 642 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Lambda_Functions__body" id="Lambda_Functions__body" style="display: none"><SPAN class="link_button"><A href="?showone=Lambda_Functions#Lambda_Functions"> |
| 643 | link |
| 644 | </A></SPAN> |
| 645 | <P class=""> |
| 646 | <SPAN class="stylepoint_section">Definition: </SPAN> |
| 647 | Lambdas define anonymous functions in an expression, as |
| 648 | opposed to a statement. They are often used to define callbacks or |
| 649 | operators for higher-order functions like <code>map()</code> and |
| 650 | <code>filter()</code>. |
| 651 | </P> |
| 652 | <P class=""> |
| 653 | <SPAN class="stylepoint_section">Pros: </SPAN> |
| 654 | Convenient. |
| 655 | </P> |
| 656 | <P class=""> |
| 657 | <SPAN class="stylepoint_section">Cons: </SPAN> Harder to read and debug than local functions. The |
| 658 | lack of names means stack traces are more difficult to |
| 659 | understand. Expressiveness is limited because the function may |
| 660 | only contain an expression. |
| 661 | </P> |
| 662 | <P class=""> |
| 663 | <SPAN class="stylepoint_section">Decision: </SPAN> |
| 664 | Okay to use them for one-liners. If the code inside the lambda |
| 665 | function is any longer than 60–80 chars, it's probably better to |
| 666 | define it as a regular (nested) function. |
| 667 | <p> |
| 668 | For common operations like multiplication, use the functions from the |
| 669 | <code>operator</code> module instead of lambda functions. For |
| 670 | example, prefer <code>operator.mul</code> to <code>lambda |
| 671 | x, y: x * y</code>. |
| 672 | </p> |
| 673 | </P> |
| 674 | </SPAN></SPAN> |
| 675 | </SPAN> |
| 676 | <SPAN class=""><H3><A name="Default_Argument_Values" id="Default_Argument_Values">Default Argument Values</A></H3> |
| 677 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Default_Argument_Values__body','Default_Argument_Values__button')" name="Default_Argument_Values__button" id="Default_Argument_Values__button">▶</SPAN> |
| 678 | <SPAN class=""> |
| 679 | Okay in most cases. |
| 680 | </SPAN> |
| 681 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Default_Argument_Values__body" id="Default_Argument_Values__body" style="display: none"><SPAN class="link_button"><A href="?showone=Default_Argument_Values#Default_Argument_Values"> |
| 682 | link |
| 683 | </A></SPAN> |
| 684 | <P class=""> |
| 685 | <SPAN class="stylepoint_section">Definition: </SPAN> |
| 686 | You can specify values for variables at the end of a function's |
| 687 | parameter list, e.g., <code>def foo(a, b=0):</code>. If |
| 688 | <code>foo</code> is called with only one argument, |
| 689 | <code>b</code> is set to 0. If it is called with two arguments, |
| 690 | <code>b</code> has the value of the second argument. |
| 691 | </P> |
| 692 | <P class=""> |
| 693 | <SPAN class="stylepoint_section">Pros: </SPAN> |
| 694 | Often you have a function that uses lots of default values, |
| 695 | but—rarely—you want to override the |
| 696 | defaults. Default argument values provide an easy way to do this, |
| 697 | without having to define lots of functions for the rare |
| 698 | exceptions. Also, Python does not support overloaded |
| 699 | methods/functions and default arguments are an easy way of |
| 700 | "faking" the overloading behavior. |
| 701 | </P> |
| 702 | <P class=""> |
| 703 | <SPAN class="stylepoint_section">Cons: </SPAN> |
| 704 | Default arguments are evaluated once at module load |
| 705 | time. This may cause problems if the argument is a mutable |
| 706 | object such as a list or a dictionary. If the function modifies |
| 707 | the object (e.g., by appending an item to a list), the default |
| 708 | value is modified. |
| 709 | </P> |
| 710 | <P class=""> |
| 711 | <SPAN class="stylepoint_section">Decision: </SPAN> |
| 712 | Okay to use with the following caveats: |
| 713 | <p> |
| 714 | Do not use mutable objects as default values in the function or method |
| 715 | definition. |
| 716 | </p> |
| 717 | <SPAN class=""><PRE>Yes: <span class="external"></span>def foo(a, b=None): |
| 718 | <span class="external"> </span>if b is None: |
| 719 | <span class="external"> </span>b = []</PRE></SPAN> |
| 720 | <SPAN class=""><PRE class="badcode">No: <span class="external"></span>def foo(a, b=[]): |
| 721 | <span class="external"> </span>...</PRE></SPAN> |
| 722 | <p> |
| 723 | Calling code must use named values for the default args. This |
| 724 | helps document the code somewhat and helps prevent and detect |
| 725 | interface breakage when more arguments are added. |
| 726 | </p> |
| 727 | <SPAN class=""><PRE> |
| 728 | <span class="external"></span>def foo(a, b=1): |
| 729 | <span class="external"> </span>...</PRE></SPAN> |
| 730 | <SPAN class=""><PRE>Yes: <span class="external"></span>foo(1) |
| 731 | <span class="external"></span>foo(1, b=2)</PRE></SPAN> |
| 732 | <SPAN class=""><PRE class="badcode">No: <span class="external"></span>foo(1, 2)</PRE></SPAN> |
| 733 | </P> |
| 734 | </SPAN></SPAN> |
| 735 | </SPAN> |
| 736 | <SPAN class=""><H3><A name="Properties" id="Properties">Properties</A></H3> |
| 737 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Properties__body','Properties__button')" name="Properties__button" id="Properties__button">▶</SPAN> |
| 738 | <SPAN class=""> |
| 739 | Use properties for accessing or setting data where you would |
| 740 | normally have used simple, lightweight accessor or setter methods. |
| 741 | </SPAN> |
| 742 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Properties__body" id="Properties__body" style="display: none"><SPAN class="link_button"><A href="?showone=Properties#Properties"> |
| 743 | link |
| 744 | </A></SPAN> |
| 745 | <P class=""> |
| 746 | <SPAN class="stylepoint_section">Definition: </SPAN> A way to wrap method calls for getting and |
| 747 | setting an attribute as a standard attribute access when the |
| 748 | computation is lightweight. |
| 749 | </P> |
| 750 | <P class=""> |
| 751 | <SPAN class="stylepoint_section">Pros: </SPAN> Readability is increased by eliminating explicit |
| 752 | get and set method calls for simple attribute access. Allows |
| 753 | calculations to be lazy. Considered the Pythonic way to |
| 754 | maintain the interface of a class. In terms of performance, |
| 755 | allowing properties bypasses needing trivial accessor methods |
| 756 | when a direct variable access is reasonable. This also allows |
| 757 | accessor methods to be added in the future without breaking the |
| 758 | interface. |
| 759 | </P> |
| 760 | <P class=""> |
| 761 | <SPAN class="stylepoint_section">Cons: </SPAN> Properties are specified after the getter and |
| 762 | setter methods are declared, requiring one to notice they are |
| 763 | used for properties farther down in the code (except for readonly |
| 764 | properties created with the <code>@property</code> decorator - see |
| 765 | below). Must inherit from |
| 766 | <code>object</code>. Can hide side-effects much like operator |
| 767 | overloading. Can be confusing for subclasses. |
| 768 | </P> |
| 769 | <P class=""> |
| 770 | <SPAN class="stylepoint_section">Decision: </SPAN> Use properties in new code to access or |
| 771 | set data where you would normally have used simple, lightweight |
| 772 | accessor or setter methods. Read-only properties should be created |
| 773 | with the <code>@property</code> |
| 774 | <a HREF="#Function_and_Method_Decorators">decorator</a>. |
| 775 | |
| 776 | <p><a id="properties-template-dp"> |
| 777 | Inheritance with properties can be non-obvious if the property itself is |
| 778 | not overridden. Thus one must make sure that accessor methods are |
| 779 | called indirectly to ensure methods overridden in subclasses are called |
| 780 | by the property (using the Template Method DP). |
| 781 | </a></p> |
| 782 | |
| 783 | <SPAN class=""><PRE>Yes: <span class="external"></span>import math |
| 784 | |
| 785 | <span class="external"></span>class Square(object): |
| 786 | <span class="external"> </span>"""A square with two properties: a writable area and a read-only perimeter. |
| 787 | |
| 788 | <span class="external"> </span>To use: |
| 789 | <span class="external"> </span>>>> sq = Square(3) |
| 790 | <span class="external"> </span>>>> sq.area |
| 791 | <span class="external"> </span>9 |
| 792 | <span class="external"> </span>>>> sq.perimeter |
| 793 | <span class="external"> </span>12 |
| 794 | <span class="external"> </span>>>> sq.area = 16 |
| 795 | <span class="external"> </span>>>> sq.side |
| 796 | <span class="external"> </span>4 |
| 797 | <span class="external"> </span>>>> sq.perimeter |
| 798 | <span class="external"> </span>16 |
| 799 | <span class="external"> </span>""" |
| 800 | |
| 801 | <span class="external"> </span>def __init__(self, side): |
| 802 | <span class="external"> </span>self.side = side |
| 803 | |
| 804 | <span class="external"> </span>def __get_area(self): |
| 805 | <span class="external"> </span>"""Calculates the 'area' property.""" |
| 806 | <span class="external"> </span>return self.side ** 2 |
| 807 | |
| 808 | <span class="external"> </span>def ___get_area(self): |
| 809 | <span class="external"> </span>"""Indirect accessor for 'area' property.""" |
| 810 | <span class="external"> </span>return self.__get_area() |
| 811 | |
| 812 | <span class="external"> </span>def __set_area(self, area): |
| 813 | <span class="external"> </span>"""Sets the 'area' property.""" |
| 814 | <span class="external"> </span>self.side = math.sqrt(area) |
| 815 | |
| 816 | <span class="external"> </span>def ___set_area(self, area): |
| 817 | <span class="external"> </span>"""Indirect setter for 'area' property.""" |
| 818 | <span class="external"> </span>self._SetArea(area) |
| 819 | |
| 820 | <span class="external"> </span>area = property(___get_area, ___set_area, |
| 821 | <span class="external"> </span> doc="""Gets or sets the area of the square.""") |
| 822 | |
| 823 | <span class="external"> </span>@property |
| 824 | <span class="external"> </span>def perimeter(self): |
| 825 | <span class="external"> </span>return self.side * 4 |
| 826 | <span class="external"></span> |
| 827 | </PRE></SPAN> |
| 828 | </P> |
| 829 | </SPAN></SPAN> |
| 830 | </SPAN> |
| 831 | <SPAN class=""><H3><A name="True/False_evaluations" id="True/False_evaluations">True/False evaluations</A></H3> |
| 832 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('True/False_evaluations__body','True/False_evaluations__button')" name="True/False_evaluations__button" id="True/False_evaluations__button">▶</SPAN> |
| 833 | <SPAN class=""> |
| 834 | Use the "implicit" false if at all possible. |
| 835 | </SPAN> |
| 836 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="True/False_evaluations__body" id="True/False_evaluations__body" style="display: none"><SPAN class="link_button"><A href="?showone=True/False_evaluations#True/False_evaluations"> |
| 837 | link |
| 838 | </A></SPAN> |
| 839 | <P class=""> |
| 840 | <SPAN class="stylepoint_section">Definition: </SPAN> Python evaluates certain values as <code>false</code> |
| 841 | when in a boolean context. A quick "rule of thumb" is that all |
| 842 | "empty" values are considered <code>false</code> so <code>0, None, [], {}, |
| 843 | ""</code> all evaluate as <code>false</code> in a boolean context. |
| 844 | </P> |
| 845 | <P class=""> |
| 846 | <SPAN class="stylepoint_section">Pros: </SPAN> Conditions using Python booleans are easier to read |
| 847 | and less error-prone. In most cases, they're also faster. |
| 848 | </P> |
| 849 | <P class=""> |
| 850 | <SPAN class="stylepoint_section">Cons: </SPAN> |
| 851 | May look strange to C/C++ developers. |
| 852 | </P> |
| 853 | <P class=""> |
| 854 | <SPAN class="stylepoint_section">Decision: </SPAN> |
| 855 | Use the "implicit" false if at all possible, e.g., <code>if |
| 856 | foo:</code> rather than <code>if foo != []:</code>. There are a |
| 857 | few caveats that you should keep in mind though: |
| 858 | <ul> |
| 859 | <li> |
| 860 | Never use <code>==</code> or <code>!=</code> to compare |
| 861 | singletons like <code>None</code>. Use <code>is</code> |
| 862 | or <code>is not</code>.</li> |
| 863 | |
| 864 | <li>Beware of writing <code>if x:</code> when you really mean |
| 865 | <code>if x is not None:</code>—e.g., when testing whether |
| 866 | a variable or argument that defaults to <code>None</code> was |
| 867 | set to some other value. The other value might be a value |
| 868 | that's false in a boolean context!</li> |
| 869 | |
| 870 | <li> |
| 871 | Never compare a boolean variable to <code>False</code> using |
| 872 | <code>==</code>. Use <code>if not x:</code> instead. If |
| 873 | you need to distinguish <code>False</code> from |
| 874 | <code>None</code> then chain the expressions, |
| 875 | such as <code>if not x and x is not None:</code>. |
| 876 | </li> |
| 877 | |
| 878 | <li> |
| 879 | For sequences (strings, lists, tuples), use the fact that |
| 880 | empty sequences are false, so <code>if not seq:</code> or |
| 881 | <code>if seq:</code> is preferable to <code>if |
| 882 | len(seq):</code> or <code>if not |
| 883 | len(seq):</code>.</li> |
| 884 | |
| 885 | <li> |
| 886 | When handling integers, implicit false may involve more risk than |
| 887 | benefit (i.e., accidentally handling <code>None</code> as 0). You may |
| 888 | compare a value which is known to be an integer (and is not the |
| 889 | result of <code>len()</code>) against the integer 0. |
| 890 | <SPAN class=""><PRE>Yes: <span class="external"></span>if not users: |
| 891 | <span class="external"> </span>print 'no users' |
| 892 | |
| 893 | <span class="external"></span>if foo == 0: |
| 894 | <span class="external"> </span>self.handle_zero() |
| 895 | |
| 896 | <span class="external"></span>if i % 10 == 0: |
| 897 | <span class="external"> </span>self.handle_multiple_of_ten()</PRE></SPAN> |
| 898 | <SPAN class=""><PRE class="badcode">No: <span class="external"></span>if len(users) == 0: |
| 899 | <span class="external"> </span>print 'no users' |
| 900 | |
| 901 | <span class="external"></span>if foo is not None and not foo: |
| 902 | <span class="external"> </span>self.handle_zero() |
| 903 | |
| 904 | <span class="external"></span>if not i % 10: |
| 905 | <span class="external"> </span>self.handle_multiple_of_ten()</PRE></SPAN> |
| 906 | </li> |
| 907 | |
| 908 | <li> |
| 909 | Note that <code>'0'</code> (i.e., <code>0</code> as string) |
| 910 | evaluates to true.</li> |
| 911 | </ul> |
| 912 | </P> |
| 913 | </SPAN></SPAN> |
| 914 | </SPAN> |
| 915 | <SPAN class=""><H3><A name="String_Methods" id="String_Methods">String Methods</A></H3> |
| 916 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('String_Methods__body','String_Methods__button')" name="String_Methods__button" id="String_Methods__button">▶</SPAN> |
| 917 | <SPAN class=""> |
| 918 | Use string methods instead of the <code>string</code> module where |
| 919 | possible. |
| 920 | </SPAN> |
| 921 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="String_Methods__body" id="String_Methods__body" style="display: none"><SPAN class="link_button"><A href="?showone=String_Methods#String_Methods"> |
| 922 | link |
| 923 | </A></SPAN> |
| 924 | <P class=""> |
| 925 | <SPAN class="stylepoint_section">Definition: </SPAN> String objects include methods for most |
| 926 | functions in the <code>string</code> module. |
| 927 | </P> |
| 928 | <P class=""> |
| 929 | <SPAN class="stylepoint_section">Pros: </SPAN> No need to import the <code>string</code> module; |
| 930 | methods work with both regular byte-strings and Unicode-strings. |
| 931 | </P> |
| 932 | <P class=""> |
| 933 | <SPAN class="stylepoint_section">Cons: </SPAN> |
| 934 | None. |
| 935 | </P> |
| 936 | <P class=""> |
| 937 | <SPAN class="stylepoint_section">Decision: </SPAN> Use string object methods. The <code>string</code> module is |
| 938 | deprecated in favor of string methods. |
| 939 | <SPAN class=""><PRE class="badcode">No: <span class="external"></span>words = string.split(foo, ':')</PRE></SPAN> |
| 940 | <SPAN class=""><PRE>Yes: <span class="external"></span>words = foo.split(':')</PRE></SPAN> |
| 941 | </P> |
| 942 | </SPAN></SPAN> |
| 943 | </SPAN> |
| 944 | <SPAN class=""><H3><A name="Lexical_Scoping" id="Lexical_Scoping">Lexical Scoping</A></H3> |
| 945 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Lexical_Scoping__body','Lexical_Scoping__button')" name="Lexical_Scoping__button" id="Lexical_Scoping__button">▶</SPAN> |
| 946 | <SPAN class=""> |
| 947 | Okay to use. |
| 948 | </SPAN> |
| 949 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Lexical_Scoping__body" id="Lexical_Scoping__body" style="display: none"><SPAN class="link_button"><A href="?showone=Lexical_Scoping#Lexical_Scoping"> |
| 950 | link |
| 951 | </A></SPAN> |
| 952 | <P class=""> |
| 953 | <SPAN class="stylepoint_section">Definition: </SPAN> |
| 954 | A nested Python function can refer to variables defined in |
| 955 | enclosing functions, but can not assign to them. Variable |
| 956 | bindings are resolved using lexical scoping, that is, based on |
| 957 | the static program text. Any assignment to a name in a block |
| 958 | will cause Python to treat all references to that name as a |
| 959 | local variable, even if the use precedes the assignment. If a |
| 960 | global declaration occurs, the name is treated as a global |
| 961 | variable. |
| 962 | |
| 963 | <p> |
| 964 | An example of the use of this feature is: |
| 965 | </p> |
| 966 | |
| 967 | <SPAN class=""><PRE> |
| 968 | <span class="external"></span>def get_adder(summand1): |
| 969 | <span class="external"> </span>"""Returns a function that adds numbers to a given number.""" |
| 970 | <span class="external"> </span>def adder(summand2): |
| 971 | <span class="external"> </span>return summand1 + summand2 |
| 972 | |
| 973 | <span class="external"> </span>return adder |
| 974 | <span class="external"></span> |
| 975 | </PRE></SPAN> |
| 976 | </P> |
| 977 | <P class=""> |
| 978 | <SPAN class="stylepoint_section">Pros: </SPAN> |
| 979 | Often results in clearer, more elegant code. Especially comforting |
| 980 | to experienced Lisp and Scheme (and Haskell and ML and …) |
| 981 | programmers. |
| 982 | </P> |
| 983 | <P class=""> |
| 984 | <SPAN class="stylepoint_section">Cons: </SPAN> |
| 985 | Can lead to confusing bugs. Such as this example based on |
| 986 | <a HREF="http://www.python.org/dev/peps/pep-0227/">PEP-0227</a>: |
| 987 | <SPAN class=""><PRE class="badcode"> |
| 988 | <span class="external"></span>i = 4 |
| 989 | <span class="external"></span>def foo(x): |
| 990 | <span class="external"> </span>def bar(): |
| 991 | <span class="external"> </span>print i, |
| 992 | <span class="external"> </span># ... |
| 993 | <span class="external"> </span># A bunch of code here |
| 994 | <span class="external"> </span># ... |
| 995 | <span class="external"> </span>for i in x: # Ah, i *is* local to Foo, so this is what Bar sees |
| 996 | <span class="external"> </span>print i, |
| 997 | <span class="external"> </span>bar()</PRE></SPAN> |
| 998 | <p> |
| 999 | So <code>foo([1, 2, 3])</code> will print <code>1 2 3 3</code>, not |
| 1000 | <code>1 2 3 4</code>. |
| 1001 | </p> |
| 1002 | </P> |
| 1003 | <P class=""> |
| 1004 | <SPAN class="stylepoint_section">Decision: </SPAN> |
| 1005 | Okay to use. |
| 1006 | </P> |
| 1007 | </SPAN></SPAN> |
| 1008 | </SPAN> |
| 1009 | <SPAN class=""><H3><A name="Function_and_Method_Decorators" id="Function_and_Method_Decorators">Function and Method Decorators</A></H3> |
| 1010 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Function_and_Method_Decorators__body','Function_and_Method_Decorators__button')" name="Function_and_Method_Decorators__button" id="Function_and_Method_Decorators__button">▶</SPAN> |
| 1011 | <SPAN class=""> |
| 1012 | Use decorators judiciously when there is a clear advantage. |
| 1013 | </SPAN> |
| 1014 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Function_and_Method_Decorators__body" id="Function_and_Method_Decorators__body" style="display: none"><SPAN class="link_button"><A href="?showone=Function_and_Method_Decorators#Function_and_Method_Decorators"> |
| 1015 | link |
| 1016 | </A></SPAN> |
| 1017 | <P class=""> |
| 1018 | <SPAN class="stylepoint_section">Definition: </SPAN> |
| 1019 | |
| 1020 | <a HREF="http://www.python.org/doc/2.4.3/whatsnew/node6.html">Decorators |
| 1021 | for Functions and Methods</a> |
| 1022 | (a.k.a "the <code>@</code> notation"). |
| 1023 | The most common decorators are <code>@classmethod</code> and |
| 1024 | <code>@staticmethod</code>, for converting ordinary methods to class or |
| 1025 | static methods. However, the decorator syntax allows for |
| 1026 | user-defined decorators as well. Specifically, for some function |
| 1027 | <code>my_decorator</code>, this: |
| 1028 | <SPAN class=""><PRE> |
| 1029 | <span class="external"></span>class C(object): |
| 1030 | <span class="external"> </span>@my_decorator |
| 1031 | <span class="external"> </span>def method(self): |
| 1032 | <span class="external"> </span># method body ... |
| 1033 | <span class="external"></span> |
| 1034 | </PRE></SPAN> |
| 1035 | |
| 1036 | is equivalent to: |
| 1037 | <SPAN class=""><PRE> |
| 1038 | <span class="external"></span>class C(object): |
| 1039 | <span class="external"> </span>def method(self): |
| 1040 | <span class="external"> </span># method body ... |
| 1041 | <span class="external"> </span>method = my_decorator(method) |
| 1042 | <span class="external"></span> |
| 1043 | </PRE></SPAN> |
| 1044 | </P> |
| 1045 | <P class=""> |
| 1046 | <SPAN class="stylepoint_section">Pros: </SPAN> Elegantly specifies some transformation on a method; the |
| 1047 | transformation might eliminate some repetitive code, enforce invariants, |
| 1048 | etc. |
| 1049 | </P> |
| 1050 | <P class=""> |
| 1051 | <SPAN class="stylepoint_section">Cons: </SPAN> Decorators can perform arbitrary operations on a |
| 1052 | function's arguments or return values, resulting in surprising |
| 1053 | implicit behavior. |
| 1054 | Additionally, decorators execute at import time. Failures in decorator |
| 1055 | code are pretty much impossible to recover from. |
| 1056 | </P> |
| 1057 | <P class=""> |
| 1058 | <SPAN class="stylepoint_section">Decision: </SPAN> Use decorators judiciously when there is a clear |
| 1059 | advantage. Decorators should follow the same import and naming |
| 1060 | guidelines as functions. Decorator pydoc should clearly state that the |
| 1061 | function is a decorator. Write unit tests for decorators. |
| 1062 | |
| 1063 | <p> |
| 1064 | Avoid external dependencies in the decorator itself (e.g. don't rely on |
| 1065 | files, sockets, database connections, etc.), since they might not be |
| 1066 | available when the decorator runs (at import time, perhaps from |
| 1067 | <code>pychecker</code> or other tools). A decorator that is |
| 1068 | called with valid parameters should (as much as possible) be guaranteed |
| 1069 | to succeed in all cases. |
| 1070 | </p> |
| 1071 | <p> |
| 1072 | Decorators are a special case of "top level code" - see |
| 1073 | <a HREF="#Main">main</a> for more discussion. |
| 1074 | </p> |
| 1075 | </P> |
| 1076 | </SPAN></SPAN> |
| 1077 | </SPAN> |
| 1078 | <SPAN class=""><H3><A name="Threading" id="Threading">Threading</A></H3> |
| 1079 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Threading__body','Threading__button')" name="Threading__button" id="Threading__button">▶</SPAN> |
| 1080 | <SPAN class=""> |
| 1081 | Do not rely on the atomicity of built-in types. |
| 1082 | </SPAN> |
| 1083 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Threading__body" id="Threading__body" style="display: none"><SPAN class="link_button"><A href="?showone=Threading#Threading"> |
| 1084 | link |
| 1085 | </A></SPAN> |
| 1086 | <p> |
| 1087 | While Python's built-in data types such as dictionaries appear |
| 1088 | to have atomic operations, there are corner cases where they |
| 1089 | aren't atomic (e.g. if <code>__hash__</code> or |
| 1090 | <code>__eq__</code> are implemented as Python methods) and their |
| 1091 | atomicity should not be relied upon. Neither should you rely on |
| 1092 | atomic variable assignment (since this in turn depends on |
| 1093 | dictionaries). |
| 1094 | </p> |
| 1095 | |
| 1096 | <p> |
| 1097 | Use the Queue module's <code>Queue</code> data type as the preferred |
| 1098 | way to |
| 1099 | communicate data between threads. Otherwise, use the threading |
| 1100 | module and its locking primitives. Learn about the proper use |
| 1101 | of condition variables so you can use |
| 1102 | <code>threading.Condition</code> instead of using lower-level |
| 1103 | locks. |
| 1104 | </p> |
| 1105 | </SPAN></SPAN> |
| 1106 | </SPAN> |
| 1107 | <SPAN class=""><H3><A name="Power_Features" id="Power_Features">Power Features</A></H3> |
| 1108 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Power_Features__body','Power_Features__button')" name="Power_Features__button" id="Power_Features__button">▶</SPAN> |
| 1109 | <SPAN class=""> |
| 1110 | Avoid these features. |
| 1111 | </SPAN> |
| 1112 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Power_Features__body" id="Power_Features__body" style="display: none"><SPAN class="link_button"><A href="?showone=Power_Features#Power_Features"> |
| 1113 | link |
| 1114 | </A></SPAN> |
| 1115 | <P class=""> |
| 1116 | <SPAN class="stylepoint_section">Definition: </SPAN> Python is an extremely flexible language and |
| 1117 | gives you many fancy features such as metaclasses, access to bytecode, |
| 1118 | on-the-fly compilation, dynamic inheritance, object reparenting, |
| 1119 | import hacks, reflection, modification of system internals, |
| 1120 | etc. |
| 1121 | </P> |
| 1122 | <P class=""> |
| 1123 | <SPAN class="stylepoint_section">Pros: </SPAN> These are powerful language features. They can |
| 1124 | make your code more compact. |
| 1125 | </P> |
| 1126 | <P class=""> |
| 1127 | <SPAN class="stylepoint_section">Cons: </SPAN> It's very tempting to use these "cool" features |
| 1128 | when they're not absolutely necessary. It's harder to read, |
| 1129 | understand, and debug code that's using unusual features |
| 1130 | underneath. It doesn't seem that way at first (to the original |
| 1131 | author), but when revisiting the code, it tends to be more |
| 1132 | difficult than code that is longer but is straightforward. |
| 1133 | </P> |
| 1134 | <P class=""> |
| 1135 | <SPAN class="stylepoint_section">Decision: </SPAN> |
| 1136 | Avoid these features in |
| 1137 | your code. |
| 1138 | </P> |
| 1139 | </SPAN></SPAN> |
| 1140 | </SPAN> |
| 1141 | </SPAN> |
| 1142 | <SPAN class=""><H2 name="Python_Style_Rules" id="Python_Style_Rules">Python Style Rules</H2> |
| 1143 | <SPAN class=""><H3><A name="Semicolons" id="Semicolons">Semicolons</A></H3> |
| 1144 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Semicolons__body','Semicolons__button')" name="Semicolons__button" id="Semicolons__button">▶</SPAN> |
| 1145 | <SPAN class=""> |
| 1146 | Do not terminate your lines with semi-colons and do not use |
| 1147 | semi-colons to put two commands on the same line. |
| 1148 | </SPAN> |
| 1149 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Semicolons__body" id="Semicolons__body" style="display: none"><SPAN class="link_button"><A href="?showone=Semicolons#Semicolons"> |
| 1150 | link |
| 1151 | </A></SPAN> |
| 1152 | </SPAN></SPAN> |
| 1153 | </SPAN> |
| 1154 | <SPAN class=""><H3><A name="Line_length" id="Line_length">Line length</A></H3> |
| 1155 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Line_length__body','Line_length__button')" name="Line_length__button" id="Line_length__button">▶</SPAN> |
| 1156 | <SPAN class=""> |
| 1157 | Maximum line length is <em>80 characters</em>. |
| 1158 | </SPAN> |
| 1159 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Line_length__body" id="Line_length__body" style="display: none"><SPAN class="link_button"><A href="?showone=Line_length#Line_length"> |
| 1160 | link |
| 1161 | </A></SPAN> |
| 1162 | <p> |
| 1163 | Exception: lines importing modules may end up longer than 80 |
| 1164 | characters only if using Python 2.4 or |
| 1165 | earlier. |
| 1166 | </p> |
| 1167 | |
| 1168 | <p> |
| 1169 | Make use of Python's |
| 1170 | |
| 1171 | <a HREF="http://www.python.org/doc/ref/implicit-joining.html">implicit |
| 1172 | line joining inside parentheses, brackets and braces</a>. |
| 1173 | If necessary, you can add an extra pair of parentheses around an |
| 1174 | expression. |
| 1175 | </p> |
| 1176 | |
| 1177 | |
| 1178 | <SPAN class=""><PRE>Yes: foo_bar(self, width, height, color='black', design=None, x='foo', |
| 1179 | emphasis=None, highlight=0) |
| 1180 | |
| 1181 | if (width == 0 and height == 0 and |
| 1182 | color == 'red' and emphasis == 'strong'):</PRE></SPAN> |
| 1183 | |
| 1184 | |
| 1185 | <p> |
| 1186 | When a literal string won't fit on a single line, use parentheses for |
| 1187 | implicit line joining. |
| 1188 | </p> |
| 1189 | |
| 1190 | <SPAN class=""><PRE> |
| 1191 | <span class="external"></span>x = ('This will build a very long long ' |
| 1192 | <span class="external"></span> 'long long long long long long string')</PRE></SPAN> |
| 1193 | |
| 1194 | <p> |
| 1195 | Make note of the indentation of the elements in the line |
| 1196 | continuation examples above; see the |
| 1197 | <a HREF="#indentation">indentation</a> |
| 1198 | section for explanation. |
| 1199 | </p> |
| 1200 | </SPAN></SPAN> |
| 1201 | </SPAN> |
| 1202 | <SPAN class=""><H3><A name="Parentheses" id="Parentheses">Parentheses</A></H3> |
| 1203 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Parentheses__body','Parentheses__button')" name="Parentheses__button" id="Parentheses__button">▶</SPAN> |
| 1204 | <SPAN class=""> |
| 1205 | Use parentheses sparingly. |
| 1206 | </SPAN> |
| 1207 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Parentheses__body" id="Parentheses__body" style="display: none"><SPAN class="link_button"><A href="?showone=Parentheses#Parentheses"> |
| 1208 | link |
| 1209 | </A></SPAN> |
| 1210 | <p> |
| 1211 | Do not use them in return statements or conditional statements unless |
| 1212 | using parentheses for implied line continuation. (See above.) |
| 1213 | It is however fine to use parentheses around tuples. |
| 1214 | </p> |
| 1215 | |
| 1216 | <SPAN class=""><PRE>Yes: <span class="external"></span>if foo: |
| 1217 | <span class="external"> </span>bar() |
| 1218 | <span class="external"></span>while x: |
| 1219 | <span class="external"> </span>x = bar() |
| 1220 | <span class="external"></span>if x and y: |
| 1221 | <span class="external"> </span>bar() |
| 1222 | <span class="external"></span>if not x: |
| 1223 | <span class="external"> </span>bar() |
| 1224 | <span class="external"></span>return foo |
| 1225 | <span class="external"></span>for (x, y) in dict.items(): ...</PRE></SPAN> |
| 1226 | <SPAN class=""><PRE class="badcode">No: <span class="external"></span>if (x): |
| 1227 | <span class="external"> </span>bar() |
| 1228 | <span class="external"></span>if not(x): |
| 1229 | <span class="external"> </span>bar() |
| 1230 | <span class="external"></span>return (foo)</PRE></SPAN> |
| 1231 | </SPAN></SPAN> |
| 1232 | </SPAN> |
| 1233 | <SPAN class=""><H3><A name="Indentation" id="Indentation">Indentation</A></H3> |
| 1234 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Indentation__body','Indentation__button')" name="Indentation__button" id="Indentation__button">▶</SPAN> |
| 1235 | <SPAN class=""> |
| 1236 | Indent your code blocks with <em>4 spaces</em>. |
| 1237 | </SPAN> |
| 1238 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Indentation__body" id="Indentation__body" style="display: none"><SPAN class="link_button"><A href="?showone=Indentation#Indentation"> |
| 1239 | link |
| 1240 | </A></SPAN> |
| 1241 | <p> |
| 1242 | Never use tabs or mix tabs and spaces. |
| 1243 | In cases of implied line continuation, you should align wrapped elements |
| 1244 | either vertically, as per the examples in the |
| 1245 | <a HREF="#Line_length">line length</a> section; or using a hanging |
| 1246 | indent of 4 spaces, in which case there should be no argument on |
| 1247 | the first line. |
| 1248 | </p> |
| 1249 | |
| 1250 | |
| 1251 | <SPAN class=""><PRE>Yes: # Aligned with opening delimiter |
| 1252 | foo = long_function_name(var_one, var_two, |
| 1253 | var_three, var_four) |
| 1254 | |
| 1255 | # 4-space hanging indent; nothing on first line |
| 1256 | foo = long_function_name( |
| 1257 | var_one, var_two, var_three, |
| 1258 | var_four)</PRE></SPAN> |
| 1259 | <SPAN class=""><PRE class="badcode">No: <span class="external"></span># Stuff on first line forbidden |
| 1260 | <span class="external"></span>foo = long_function_name(var_one, var_two, |
| 1261 | <span class="external"></span> var_three, var_four) |
| 1262 | |
| 1263 | <span class="external"></span># 2-space hanging indent forbidden |
| 1264 | <span class="external"></span>foo = long_function_name( |
| 1265 | <span class="external"></span> var_one, var_two, var_three, |
| 1266 | <span class="external"></span> var_four)</PRE></SPAN> |
| 1267 | </SPAN></SPAN> |
| 1268 | </SPAN> |
| 1269 | <SPAN class=""><H3><A name="Blank_Lines" id="Blank_Lines">Blank Lines</A></H3> |
| 1270 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Blank_Lines__body','Blank_Lines__button')" name="Blank_Lines__button" id="Blank_Lines__button">▶</SPAN> |
| 1271 | <SPAN class=""> |
| 1272 | Two blank lines between top-level definitions, one blank line |
| 1273 | between method definitions. |
| 1274 | </SPAN> |
| 1275 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Blank_Lines__body" id="Blank_Lines__body" style="display: none"><SPAN class="link_button"><A href="?showone=Blank_Lines#Blank_Lines"> |
| 1276 | link |
| 1277 | </A></SPAN> |
| 1278 | <p> |
| 1279 | Two blank lines between top-level definitions, be they function |
| 1280 | or class definitions. One blank line between method definitions |
| 1281 | and between the <code>class</code> line and the first method. |
| 1282 | Use single blank lines as you judge appropriate within functions or |
| 1283 | methods. |
| 1284 | </p> |
| 1285 | </SPAN></SPAN> |
| 1286 | </SPAN> |
| 1287 | <SPAN class=""><H3><A name="Whitespace" id="Whitespace">Whitespace</A></H3> |
| 1288 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Whitespace__body','Whitespace__button')" name="Whitespace__button" id="Whitespace__button">▶</SPAN> |
| 1289 | <SPAN class=""> |
| 1290 | Follow standard typographic rules for the use of spaces around |
| 1291 | punctuation. |
| 1292 | </SPAN> |
| 1293 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Whitespace__body" id="Whitespace__body" style="display: none"><SPAN class="link_button"><A href="?showone=Whitespace#Whitespace"> |
| 1294 | link |
| 1295 | </A></SPAN> |
| 1296 | <p> |
| 1297 | No whitespace inside parentheses, brackets or braces. |
| 1298 | </p> |
| 1299 | <SPAN class=""><PRE>Yes: <span class="external"></span>spam(ham[1], {eggs: 2}, [])</PRE></SPAN> |
| 1300 | <SPAN class=""><PRE class="badcode">No: <span class="external"></span>spam( ham[ 1 ], { eggs: 2 }, [ ] )</PRE></SPAN> |
| 1301 | <p> |
| 1302 | No whitespace before a comma, semicolon, or colon. Do use |
| 1303 | whitespace after a comma, semicolon, or colon except at the end |
| 1304 | of the line. |
| 1305 | </p> |
| 1306 | <SPAN class=""><PRE>Yes: <span class="external"></span>if x == 4: |
| 1307 | <span class="external"> </span>print x, y |
| 1308 | <span class="external"></span>x, y = y, x</PRE></SPAN> |
| 1309 | <SPAN class=""><PRE class="badcode">No: <span class="external"></span>if x == 4 : |
| 1310 | <span class="external"> </span>print x , y |
| 1311 | <span class="external"></span>x , y = y , x</PRE></SPAN> |
| 1312 | <p> |
| 1313 | No whitespace before the open paren/bracket that starts an argument list, |
| 1314 | indexing or slicing. |
| 1315 | </p> |
| 1316 | <SPAN class=""><PRE>Yes: <span class="external"></span>spam(1)</PRE></SPAN> |
| 1317 | <SPAN class=""><PRE class="badcode">No: <span class="external"></span>spam (1)</PRE></SPAN> |
| 1318 | <SPAN class=""><PRE>Yes: <span class="external"></span>dict['key'] = list[index]</PRE></SPAN> |
| 1319 | <SPAN class=""><PRE class="badcode">No: <span class="external"></span>dict ['key'] = list [index]</PRE></SPAN> |
| 1320 | |
| 1321 | <p> |
| 1322 | Surround binary operators with a single space on either side for |
| 1323 | assignment (<code>=</code>), comparisons (<code>==, <, >, !=, |
| 1324 | <>, <=, >=, in, not in, is, is not</code>), and Booleans |
| 1325 | (<code>and, or, not</code>). Use your better judgment for the |
| 1326 | insertion of spaces around arithmetic operators but always be |
| 1327 | consistent about whitespace on either side of a binary operator. |
| 1328 | </p> |
| 1329 | <SPAN class=""><PRE>Yes: <span class="external"></span>x == 1</PRE></SPAN> |
| 1330 | <SPAN class=""><PRE class="badcode">No: <span class="external"></span>x<1</PRE></SPAN> |
| 1331 | <p> |
| 1332 | Don't use spaces around the '=' sign when used to indicate a |
| 1333 | keyword argument or a default parameter value. |
| 1334 | </p> |
| 1335 | <SPAN class=""><PRE>Yes: <span class="external"></span>def complex(real, imag=0.0): return magic(r=real, i=imag)</PRE></SPAN> |
| 1336 | <SPAN class=""><PRE class="badcode">No: <span class="external"></span>def complex(real, imag = 0.0): return magic(r = real, i = imag)</PRE></SPAN> |
| 1337 | |
| 1338 | <p> |
| 1339 | Don't use spaces to vertically align tokens on consecutive lines, since it |
| 1340 | becomes a maintenance burden (applies to <code>:</code>, <code>#</code>, |
| 1341 | <code>=</code>, etc.): |
| 1342 | </p> |
| 1343 | <SPAN class=""><PRE>Yes: |
| 1344 | foo = 1000 # comment |
| 1345 | long_name = 2 # comment that should not be aligned |
| 1346 | |
| 1347 | dictionary = { |
| 1348 | "foo": 1, |
| 1349 | "long_name": 2, |
| 1350 | }</PRE></SPAN> |
| 1351 | <SPAN class=""><PRE class="badcode">No: |
| 1352 | foo = 1000 # comment |
| 1353 | long_name = 2 # comment that should not be aligned |
| 1354 | |
| 1355 | dictionary = { |
| 1356 | "foo" : 1, |
| 1357 | "long_name": 2, |
| 1358 | }</PRE></SPAN> |
| 1359 | |
| 1360 | |
| 1361 | </SPAN></SPAN> |
| 1362 | </SPAN> |
| 1363 | <SPAN class=""><H3><A name="Python_Interpreter" id="Python_Interpreter">Python Interpreter</A></H3> |
| 1364 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Python_Interpreter__body','Python_Interpreter__button')" name="Python_Interpreter__button" id="Python_Interpreter__button">▶</SPAN> |
| 1365 | <SPAN class=""> |
| 1366 | Modules should begin with |
| 1367 | |
| 1368 | <code>#!/usr/bin/env python<version></code> |
| 1369 | </SPAN> |
| 1370 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Python_Interpreter__body" id="Python_Interpreter__body" style="display: none"><SPAN class="link_button"><A href="?showone=Python_Interpreter#Python_Interpreter"> |
| 1371 | link |
| 1372 | </A></SPAN> |
| 1373 | <p> |
| 1374 | Modules should begin with a "shebang" line specifying the Python |
| 1375 | interpreter used to execute the program: |
| 1376 | </p> |
| 1377 | |
| 1378 | <SPAN class=""><PRE> |
| 1379 | <span class="external"></span>#!/usr/bin/env python2.4</PRE></SPAN> |
| 1380 | |
| 1381 | <p> |
| 1382 | Always use the most specific version you can use, e.g., |
| 1383 | <code>/usr/bin/python2.4</code>, not |
| 1384 | <code>/usr/bin/python2</code>. This makes it easier to find |
| 1385 | dependencies when |
| 1386 | |
| 1387 | upgrading to a different Python version |
| 1388 | and also avoids confusion and breakage during use. E.g., Does |
| 1389 | <code>/usr/bin/python2</code> mean Python 2.0.1 or Python |
| 1390 | 2.3.0? |
| 1391 | </p> |
| 1392 | |
| 1393 | </SPAN></SPAN> |
| 1394 | </SPAN> |
| 1395 | <SPAN class=""><H3><A name="Comments" id="Comments">Comments</A></H3> |
| 1396 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Comments__body','Comments__button')" name="Comments__button" id="Comments__button">▶</SPAN> |
| 1397 | <SPAN class=""> |
| 1398 | Be sure to use the right style for module, function, method and in-line |
| 1399 | comments. |
| 1400 | </SPAN> |
| 1401 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Comments__body" id="Comments__body" style="display: none"><SPAN class="link_button"><A href="?showone=Comments#Comments"> |
| 1402 | link |
| 1403 | </A></SPAN> |
| 1404 | |
| 1405 | <P class=""> |
| 1406 | <SPAN class="stylepoint_subsection">Doc Strings</SPAN> |
| 1407 | |
| 1408 | <p> |
| 1409 | Python has a unique commenting style using doc strings. A doc |
| 1410 | string is a string that is the first statement in a package, |
| 1411 | module, class or function. These strings can be extracted |
| 1412 | automatically through the <code>__doc__</code> member of the |
| 1413 | object and are used by <code>pydoc</code>. (Try running |
| 1414 | <code>pydoc</code> on your module to see how it looks.) Our |
| 1415 | convention for doc strings is to use the three double-quote |
| 1416 | format for strings. A doc string should be organized as a |
| 1417 | summary line (one physical line) terminated by a period, |
| 1418 | question mark, or exclamation point, followed by a blank line, |
| 1419 | followed by the rest of the doc string starting at the same |
| 1420 | cursor position as the first quote of the first line. There are |
| 1421 | more formatting guidelines for doc strings below. |
| 1422 | </p> |
| 1423 | |
| 1424 | </P> |
| 1425 | <P class=""> |
| 1426 | <SPAN class="stylepoint_subsection">Modules</SPAN> |
| 1427 | |
| 1428 | |
| 1429 | |
| 1430 | <p> |
| 1431 | Every file should contain the following items, in order: |
| 1432 | <ul> |
| 1433 | <li>a copyright statement (for example, |
| 1434 | <code>Copyright 2008 Google Inc.</code>)</li> |
| 1435 | <li>a license boilerplate. Choose the appropriate boilerplate |
| 1436 | for the license used by the project (for example, Apache 2.0, BSD, |
| 1437 | LGPL, GPL)</li> |
| 1438 | <li>an author line to identify the original author of the file</li> |
| 1439 | </ul> |
| 1440 | </p> |
| 1441 | </P> |
| 1442 | <P class=""> |
| 1443 | <SPAN class="stylepoint_subsection">Functions and Methods</SPAN> |
| 1444 | |
| 1445 | <p> |
| 1446 | Any function or method which is not both obvious and very short |
| 1447 | needs a doc string. Additionally, any externally accessible |
| 1448 | function or method regardless of length or simplicity needs a |
| 1449 | doc string. The doc string should include what the function does |
| 1450 | and have detailed descriptions of the input and output. It |
| 1451 | should not, generally, describe how it does it unless it's some |
| 1452 | complicated algorithm. For tricky code block/inline comments |
| 1453 | within the code are more appropriate. The doc string should give |
| 1454 | enough information to write a call to the function without |
| 1455 | looking at a single line of the function's code. Args should be |
| 1456 | individually documented, an explanation following after a colon, |
| 1457 | and should use a uniform hanging indent of 2 or 4 spaces. The |
| 1458 | doc string should specify the expected types where specific types |
| 1459 | are required. A "Raises:" section should list all exceptions |
| 1460 | that can be raised by the function. The doc string for generator |
| 1461 | functions should use "Yields:" rather than "Returns:". |
| 1462 | </p> |
| 1463 | |
| 1464 | <SPAN class=""><PRE> |
| 1465 | <span class="external"></span>def fetch_bigtable_rows(big_table, keys, other_silly_variable=None): |
| 1466 | <span class="external"> </span>"""Fetches rows from a Bigtable. |
| 1467 | |
| 1468 | <span class="external"> </span>Retrieves rows pertaining to the given keys from the Table instance |
| 1469 | <span class="external"> </span>represented by big_table. Silly things may happen if |
| 1470 | <span class="external"> </span>other_silly_variable is not None. |
| 1471 | |
| 1472 | <span class="external"> </span>Args: |
| 1473 | <span class="external"> </span>big_table: An open Bigtable Table instance. |
| 1474 | <span class="external"> </span>keys: A sequence of strings representing the key of each table row |
| 1475 | <span class="external"> </span> to fetch. |
| 1476 | <span class="external"> </span>other_silly_variable: Another optional variable, that has a much |
| 1477 | <span class="external"> </span> longer name than the other args, and which does nothing. |
| 1478 | |
| 1479 | <span class="external"> </span>Returns: |
| 1480 | <span class="external"> </span>A dict mapping keys to the corresponding table row data |
| 1481 | <span class="external"> </span>fetched. Each row is represented as a tuple of strings. For |
| 1482 | <span class="external"> </span>example: |
| 1483 | |
| 1484 | <span class="external"> </span>{'Serak': ('Rigel VII', 'Preparer'), |
| 1485 | <span class="external"> </span> 'Zim': ('Irk', 'Invader'), |
| 1486 | <span class="external"> </span> 'Lrrr': ('Omicron Persei 8', 'Emperor')} |
| 1487 | |
| 1488 | <span class="external"> </span>If a key from the keys argument is missing from the dictionary, |
| 1489 | <span class="external"> </span>then that row was not found in the table. |
| 1490 | |
| 1491 | <span class="external"> </span>Raises: |
| 1492 | <span class="external"> </span>IOError: An error occurred accessing the bigtable.Table object. |
| 1493 | <span class="external"> </span>""" |
| 1494 | <span class="external"> </span>pass |
| 1495 | <span class="external"></span> |
| 1496 | </PRE></SPAN> |
| 1497 | </P> |
| 1498 | <P class=""> |
| 1499 | <SPAN class="stylepoint_subsection">Classes</SPAN> |
| 1500 | |
| 1501 | <p> |
| 1502 | Classes should have a doc string below the class definition describing |
| 1503 | the class. If your class has public attributes, they should be documented |
| 1504 | here in an Attributes section and follow the same formatting as a |
| 1505 | function's Args section. |
| 1506 | </p> |
| 1507 | |
| 1508 | <SPAN class=""><PRE> |
| 1509 | <span class="external"></span>class SampleClass(object): |
| 1510 | <span class="external"> </span>"""Summary of class here. |
| 1511 | |
| 1512 | <span class="external"> </span>Longer class information.... |
| 1513 | <span class="external"> </span>Longer class information.... |
| 1514 | |
| 1515 | <span class="external"> </span>Attributes: |
| 1516 | <span class="external"> </span>likes_spam: A boolean indicating if we like SPAM or not. |
| 1517 | <span class="external"> </span>eggs: An integer count of the eggs we have laid. |
| 1518 | <span class="external"> </span>""" |
| 1519 | |
| 1520 | <span class="external"> </span>def __init__(self, likes_spam=False): |
| 1521 | <span class="external"> </span>"""Inits SampleClass with blah.""" |
| 1522 | <span class="external"> </span>self.likes_spam = likes_spam |
| 1523 | <span class="external"> </span>self.eggs = 0 |
| 1524 | |
| 1525 | <span class="external"> </span>def public_method(self): |
| 1526 | <span class="external"> </span>"""Performs operation blah.""" |
| 1527 | <span class="external"></span> |
| 1528 | </PRE></SPAN> |
| 1529 | |
| 1530 | </P> |
| 1531 | <P class=""> |
| 1532 | <SPAN class="stylepoint_subsection">Block and Inline Comments</SPAN> |
| 1533 | |
| 1534 | <p> |
| 1535 | The final place to have comments is in tricky parts of the |
| 1536 | code. If you're going to have to explain it at the next |
| 1537 | <a HREF="http://en.wikipedia.org/wiki/Code_review">code review</a>, |
| 1538 | you should comment it now. Complicated operations get a few lines of |
| 1539 | comments before the operations |
| 1540 | commence. Non-obvious ones get comments at the end of the line. |
| 1541 | </p> |
| 1542 | |
| 1543 | <SPAN class=""><PRE> |
| 1544 | <span class="external"></span># We use a weighted dictionary search to find out where i is in |
| 1545 | <span class="external"></span># the array. We extrapolate position based on the largest num |
| 1546 | <span class="external"></span># in the array and the array size and then do binary search to |
| 1547 | <span class="external"></span># get the exact number. |
| 1548 | |
| 1549 | <span class="external"></span>if i & (i-1) == 0: # true iff i is a power of 2 |
| 1550 | <span class="external"></span> |
| 1551 | </PRE></SPAN> |
| 1552 | |
| 1553 | <p> |
| 1554 | To improve legibility, these comments should be at least 2 spaces away |
| 1555 | from the code. |
| 1556 | </p> |
| 1557 | |
| 1558 | <p> |
| 1559 | On the other hand, never describe the code. Assume the person |
| 1560 | reading the code knows Python (though not what you're trying to |
| 1561 | do) better than you do. |
| 1562 | </p> |
| 1563 | |
| 1564 | <SPAN class=""><PRE class="badcode"> |
| 1565 | <span class="external"></span># BAD COMMENT: Now go through the b array and make sure whenever i occurs |
| 1566 | <span class="external"></span># the next element is i+1 |
| 1567 | <span class="external"></span> |
| 1568 | </PRE></SPAN> |
| 1569 | |
| 1570 | </P> |
| 1571 | </SPAN></SPAN> |
| 1572 | </SPAN> |
| 1573 | <SPAN class=""><H3><A name="Classes" id="Classes">Classes</A></H3> |
| 1574 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Classes__body','Classes__button')" name="Classes__button" id="Classes__button">▶</SPAN> |
| 1575 | <SPAN class=""> |
| 1576 | If a class inherits from no other base classes, explicitly inherit |
| 1577 | from <code>object</code>. This also applies to nested classes. |
| 1578 | </SPAN> |
| 1579 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Classes__body" id="Classes__body" style="display: none"><SPAN class="link_button"><A href="?showone=Classes#Classes"> |
| 1580 | link |
| 1581 | </A></SPAN> |
| 1582 | <SPAN class=""><PRE class="badcode">No: <span class="external"></span>class SampleClass: |
| 1583 | <span class="external"> </span>pass |
| 1584 | |
| 1585 | |
| 1586 | <span class="external"></span>class OuterClass: |
| 1587 | |
| 1588 | <span class="external"> </span>class InnerClass: |
| 1589 | <span class="external"> </span>pass |
| 1590 | <span class="external"></span> |
| 1591 | </PRE></SPAN> |
| 1592 | |
| 1593 | <SPAN class=""><PRE>Yes: <span class="external"></span>class SampleClass(object): |
| 1594 | <span class="external"> </span>pass |
| 1595 | |
| 1596 | |
| 1597 | <span class="external"></span>class OuterClass(object): |
| 1598 | |
| 1599 | <span class="external"> </span>class InnerClass(object): |
| 1600 | <span class="external"> </span>pass |
| 1601 | |
| 1602 | |
| 1603 | <span class="external"></span>class ChildClass(ParentClass): |
| 1604 | <span class="external"> </span>"""Explicitly inherits from another class already.""" |
| 1605 | <span class="external"></span> |
| 1606 | </PRE></SPAN> |
| 1607 | |
| 1608 | <p>Inheriting from <code>object</code> is needed to make properties work |
| 1609 | properly, and it will protect your code from one particular potential |
| 1610 | incompatibility with Python 3000. It also defines |
| 1611 | special methods that implement the default semantics of objects including |
| 1612 | <code>__new__</code>, <code>__init__</code>, <code>__delattr__</code>, |
| 1613 | <code>__getattribute__</code>, <code>__setattr__</code>, |
| 1614 | <code>__hash__</code>, <code>__repr__</code>, and <code>__str__</code>. |
| 1615 | </p> |
| 1616 | </SPAN></SPAN> |
| 1617 | </SPAN> |
| 1618 | <SPAN class=""><H3><A name="Strings" id="Strings">Strings</A></H3> |
| 1619 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Strings__body','Strings__button')" name="Strings__button" id="Strings__button">▶</SPAN> |
| 1620 | <SPAN class=""> |
| 1621 | Use the <code>%</code> operator for formatting strings, |
| 1622 | even when the parameters are all strings. Use your best judgement |
| 1623 | to decide between <code>+</code> and <code>%</code> though. |
| 1624 | </SPAN> |
| 1625 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Strings__body" id="Strings__body" style="display: none"><SPAN class="link_button"><A href="?showone=Strings#Strings"> |
| 1626 | link |
| 1627 | </A></SPAN> |
| 1628 | <SPAN class=""><PRE class="badcode">No: <span class="external"></span>x = '%s%s' % (a, b) # use + in this case |
| 1629 | <span class="external"></span>x = imperative + ', ' + expletive + '!' |
| 1630 | <span class="external"></span>x = 'name: ' + name + '; score: ' + str(n)</PRE></SPAN> |
| 1631 | <SPAN class=""><PRE>Yes: <span class="external"></span>x = a + b |
| 1632 | <span class="external"></span>x = '%s, %s!' % (imperative, expletive) |
| 1633 | <span class="external"></span>x = 'name: %s; score: %d' % (name, n)</PRE></SPAN> |
| 1634 | |
| 1635 | <p> |
| 1636 | Avoid using the <code>+</code> and <code>+=</code> operators to |
| 1637 | accumulate a string within a loop. Since strings are immutable, this |
| 1638 | creates unnecessary temporary objects and results in quadratic rather |
| 1639 | than linear running time. Instead, add each substring to a list and |
| 1640 | <code>''.join</code> the list after the loop terminates (or, write each |
| 1641 | substring to a <code>cStringIO.StringIO</code> buffer). |
| 1642 | </p> |
| 1643 | |
| 1644 | <SPAN class=""><PRE class="badcode">No: <span class="external"></span>employee_table = '<table>' |
| 1645 | <span class="external"></span>for last_name, first_name in employee_list: |
| 1646 | <span class="external"> </span>employee_table += '<tr><td>%s, %s</td></tr>' % (last_name, first_name) |
| 1647 | <span class="external"></span>employee_table += '</table>'</PRE></SPAN> |
| 1648 | <SPAN class=""><PRE>Yes: <span class="external"></span>items = ['<table>'] |
| 1649 | <span class="external"></span>for last_name, first_name in employee_list: |
| 1650 | <span class="external"> </span>items.append('<tr><td>%s, %s</td></tr>' % (last_name, first_name)) |
| 1651 | <span class="external"></span>items.append('</table>') |
| 1652 | <span class="external"></span>employee_table = ''.join(items)</PRE></SPAN> |
| 1653 | |
| 1654 | <p> |
| 1655 | Use <code>"""</code> for multi-line strings rather than |
| 1656 | <code>'''</code>. Note, however, that it is often cleaner to |
| 1657 | use implicit line joining since multi-line strings do |
| 1658 | not flow with the indentation of the rest of the program: |
| 1659 | </p> |
| 1660 | |
| 1661 | <SPAN class=""><PRE class="badcode"> No<span class="external"></span>: |
| 1662 | <span class="external"></span>print """This is pretty ugly. |
| 1663 | Don'<span class="external"></span>t do this. |
| 1664 | """<span class="external"></span> |
| 1665 | </PRE></SPAN> |
| 1666 | <SPAN class=""><PRE>Ye<span class="external"></span>s: |
| 1667 | <span class="external"></span>print ("This is much nicer.\n" |
| 1668 | <span class="external"></span> "Do it this way.\n")</PRE></SPAN> |
| 1669 | </SPAN></SPAN> |
| 1670 | </SPAN> |
| 1671 | <SPAN class=""><H3><A name="TODO_Comments" id="TODO_Comments">TODO Comments</A></H3> |
| 1672 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('TODO_Comments__body','TODO_Comments__button')" name="TODO_Comments__button" id="TODO_Comments__button">▶</SPAN> |
| 1673 | <SPAN class=""> |
| 1674 | Use <code>TODO</code> comments for code that is temporary, a |
| 1675 | short-term solution, or good-enough but not perfect. |
| 1676 | </SPAN> |
| 1677 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="TODO_Comments__body" id="TODO_Comments__body" style="display: none"><SPAN class="link_button"><A href="?showone=TODO_Comments#TODO_Comments"> |
| 1678 | link |
| 1679 | </A></SPAN> |
| 1680 | <p> |
| 1681 | <code>TODO</code>s should include the string <code>TODO</code> in |
| 1682 | all caps, followed by your |
| 1683 | |
| 1684 | name, e-mail address, or other |
| 1685 | identifier |
| 1686 | in parentheses. A colon is optional. A comment explaining what there |
| 1687 | is to do is required. The main purpose is to have |
| 1688 | a consistent <code>TODO</code> format searchable by the person |
| 1689 | adding the comment (who can provide more details upon request). A |
| 1690 | <code>TODO</code> is not a commitment to provide the fix yourself. |
| 1691 | </p> |
| 1692 | |
| 1693 | <SPAN class=""><PRE># TODO(kl@gmail.com): Drop the use of "has_key". |
| 1694 | # TODO(Zeke) change this to use relations.</PRE></SPAN> |
| 1695 | <p> |
| 1696 | If your <code>TODO</code> is of the form "At a future date do |
| 1697 | something" make sure that you either include a very specific |
| 1698 | date ("Fix by November 2009") or a very specific event |
| 1699 | ("Remove this code when all clients can handle XML responses."). |
| 1700 | </p> |
| 1701 | </SPAN></SPAN> |
| 1702 | </SPAN> |
| 1703 | <SPAN class=""><H3><A name="Imports_formatting" id="Imports_formatting">Imports formatting</A></H3> |
| 1704 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Imports_formatting__body','Imports_formatting__button')" name="Imports_formatting__button" id="Imports_formatting__button">▶</SPAN> |
| 1705 | <SPAN class=""> |
| 1706 | Imports should be on separate lines. |
| 1707 | </SPAN> |
| 1708 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Imports_formatting__body" id="Imports_formatting__body" style="display: none"><SPAN class="link_button"><A href="?showone=Imports_formatting#Imports_formatting"> |
| 1709 | link |
| 1710 | </A></SPAN> |
| 1711 | <p> |
| 1712 | E.g.: |
| 1713 | </p> |
| 1714 | |
| 1715 | <SPAN class=""><PRE>Yes: <span class="external"></span>import os |
| 1716 | <span class="external"></span>import sys</PRE></SPAN> |
| 1717 | <SPAN class=""><PRE class="badcode">No: <span class="external"></span>import os, sys</PRE></SPAN> |
| 1718 | <p> |
| 1719 | Imports are always put at the top of the file, just after any |
| 1720 | module comments and doc strings and before module globals and |
| 1721 | constants. Imports should be grouped with the order being most generic |
| 1722 | to least generic: |
| 1723 | </p> |
| 1724 | <ul> |
| 1725 | <li>standard library imports</li> |
| 1726 | <li>third-party imports</li> |
| 1727 | |
| 1728 | <li>application-specific imports</li> |
| 1729 | </ul> |
| 1730 | <p> |
| 1731 | Within each grouping, imports should be sorted lexicographically, |
| 1732 | ignoring case, according to each module's full package path. |
| 1733 | </p> |
| 1734 | <SPAN class=""><PRE> |
| 1735 | <span class="external"></span>import foo |
| 1736 | <span class="external"></span>from foo import bar |
| 1737 | <span class="external"></span>from foo.bar import baz |
| 1738 | <span class="external"></span>from foo.bar import Quux |
| 1739 | <span class="external"></span>from Foob import ar</PRE></SPAN> |
| 1740 | |
| 1741 | |
| 1742 | </SPAN></SPAN> |
| 1743 | </SPAN> |
| 1744 | <SPAN class=""><H3><A name="Statements" id="Statements">Statements</A></H3> |
| 1745 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Statements__body','Statements__button')" name="Statements__button" id="Statements__button">▶</SPAN> |
| 1746 | <SPAN class=""> |
| 1747 | Generally only one statement per line. |
| 1748 | </SPAN> |
| 1749 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Statements__body" id="Statements__body" style="display: none"><SPAN class="link_button"><A href="?showone=Statements#Statements"> |
| 1750 | link |
| 1751 | </A></SPAN> |
| 1752 | <p> |
| 1753 | However, you may put the |
| 1754 | result of a test on the same line as the test only if the entire |
| 1755 | statement fits on one line. In particular, you can never do so |
| 1756 | with <code>try</code>/<code>except</code> since the |
| 1757 | <code>try</code> and <code>except</code> can't both fit on the |
| 1758 | same line, and you can only do so with an <code>if</code> if |
| 1759 | there is no <code>else</code>. |
| 1760 | </p> |
| 1761 | |
| 1762 | <SPAN class=""><PRE>Ye<span class="external"></span>s: |
| 1763 | |
| 1764 | <span class="external"></span>if foo: bar(foo)</PRE></SPAN> |
| 1765 | <SPAN class=""><PRE class="badcode">No<span class="external"></span>: |
| 1766 | |
| 1767 | <span class="external"></span>if foo: bar(foo) |
| 1768 | <span class="external"></span>else: baz(foo) |
| 1769 | |
| 1770 | <span class="external"></span>try: bar(foo) |
| 1771 | <span class="external"></span>except ValueError: baz(foo) |
| 1772 | |
| 1773 | <span class="external"></span>try: |
| 1774 | <span class="external"> </span>bar(foo) |
| 1775 | <span class="external"></span>except ValueError: baz(foo) |
| 1776 | <span class="external"></span> |
| 1777 | </PRE></SPAN> |
| 1778 | </SPAN></SPAN> |
| 1779 | </SPAN> |
| 1780 | <SPAN class=""><H3><A name="Access_Control" id="Access_Control">Access Control</A></H3> |
| 1781 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Access_Control__body','Access_Control__button')" name="Access_Control__button" id="Access_Control__button">▶</SPAN> |
| 1782 | <SPAN class=""> |
| 1783 | If an accessor function would be trivial you should use public variables |
| 1784 | instead of accessor functions to avoid the extra cost of function |
| 1785 | calls in Python. When more functionality is added you can use |
| 1786 | <code>property</code> to keep the syntax consistent. |
| 1787 | </SPAN> |
| 1788 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Access_Control__body" id="Access_Control__body" style="display: none"><SPAN class="link_button"><A href="?showone=Access_Control#Access_Control"> |
| 1789 | link |
| 1790 | </A></SPAN> |
| 1791 | <p> |
| 1792 | On the other hand, if access is more complex, or the cost of accessing |
| 1793 | the variable is significant, you should use function calls (following the |
| 1794 | <a HREF="#naming">Naming</a> guidelines) such as <code>get_foo()</code> |
| 1795 | and <code>set_foo()</code>. If the past behavior allowed access through a |
| 1796 | property, do not bind the new accessor functions to the property. Any |
| 1797 | code still attempting to access the variable by the old method should |
| 1798 | break visibly so they are made aware of the change in complexity. |
| 1799 | </p> |
| 1800 | </SPAN></SPAN> |
| 1801 | </SPAN> |
| 1802 | <SPAN class=""><H3><A name="Naming" id="Naming">Naming</A></H3> |
| 1803 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Naming__body','Naming__button')" name="Naming__button" id="Naming__button">▶</SPAN> |
| 1804 | <SPAN class=""> |
| 1805 | <code>module_name, package_name, ClassName, method_name, ExceptionName, |
| 1806 | function_name, GLOBAL_VAR_NAME, instance_var_name, |
| 1807 | function_parameter_name, local_var_name.</code> |
| 1808 | </SPAN> |
| 1809 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Naming__body" id="Naming__body" style="display: none"><SPAN class="link_button"><A href="?showone=Naming#Naming"> |
| 1810 | link |
| 1811 | </A></SPAN> |
| 1812 | <P class=""> |
| 1813 | <SPAN class="stylepoint_subsection">Names to Avoid</SPAN> |
| 1814 | |
| 1815 | <ul> |
| 1816 | <li>single character names except for counters or iterators</li> |
| 1817 | <li>dashes (<code>-</code>) in any package/module name</li> |
| 1818 | <li> |
| 1819 | <code>__double_leading_and_trailing_underscore__</code> names |
| 1820 | (reserved by Python)</li> |
| 1821 | </ul> |
| 1822 | |
| 1823 | </P> |
| 1824 | <P class=""> |
| 1825 | <SPAN class="stylepoint_subsection">Naming Convention</SPAN> |
| 1826 | |
| 1827 | <ul> |
| 1828 | <li> |
| 1829 | "Internal" means internal to a module or protected |
| 1830 | or private within a class.</li> |
| 1831 | <li> |
| 1832 | Prepending a single underscore (<code>_</code>) has some |
| 1833 | support for protecting module variables and functions (not included |
| 1834 | with <code>import * from</code>). Prepending a double underscore |
| 1835 | (<code>__</code>) to an instance variable or method |
| 1836 | effectively serves to make the variable or method private to its class |
| 1837 | (using name mangling).</li> |
| 1838 | <li> |
| 1839 | Place related classes and top-level functions together in a |
| 1840 | module. Unlike Java, |
| 1841 | there is no need to limit yourself to one class per module.</li> |
| 1842 | <li> |
| 1843 | Use CapWords for class names, but lower_with_under.py for module names. |
| 1844 | Although there are many existing modules named CapWords.py, this is now |
| 1845 | discouraged because it's confusing when the module happens to be |
| 1846 | named after a class. ("wait -- did I write |
| 1847 | <code>import StringIO</code> or <code>from StringIO import |
| 1848 | StringIO</code>?")</li> |
| 1849 | </ul> |
| 1850 | |
| 1851 | </P> |
| 1852 | <P class=""> |
| 1853 | <SPAN class="stylepoint_subsection">Guidelines derived from Guido's Recommendations</SPAN> |
| 1854 | |
| 1855 | <table rules="all" border="1" cellspacing="2" cellpadding="2"> |
| 1856 | |
| 1857 | <tr> |
| 1858 | <th>Type</th> |
| 1859 | <th>Public</th> |
| 1860 | <th>Internal</th> |
| 1861 | </tr> |
| 1862 | |
| 1863 | |
| 1864 | |
| 1865 | <tr> |
| 1866 | <td>Packages</td> |
| 1867 | <td><code>lower_with_under</code></td> |
| 1868 | <td></td> |
| 1869 | </tr> |
| 1870 | |
| 1871 | <tr> |
| 1872 | <td>Modules</td> |
| 1873 | <td><code>lower_with_under</code></td> |
| 1874 | <td><code>_lower_with_under</code></td> |
| 1875 | </tr> |
| 1876 | |
| 1877 | <tr> |
| 1878 | <td>Classes</td> |
| 1879 | <td><code>CapWords</code></td> |
| 1880 | <td><code>_CapWords</code></td> |
| 1881 | </tr> |
| 1882 | |
| 1883 | <tr> |
| 1884 | <td>Exceptions</td> |
| 1885 | <td><code>CapWords</code></td> |
| 1886 | <td></td> |
| 1887 | </tr> |
| 1888 | |
| 1889 | |
| 1890 | |
| 1891 | <tr> |
| 1892 | <td>Functions</td> |
| 1893 | <td><code>lower_with_under()</code></td> |
| 1894 | <td><code>_lower_with_under()</code></td> |
| 1895 | </tr> |
| 1896 | |
| 1897 | <tr> |
| 1898 | <td>Global/Class Constants</td> |
| 1899 | <td><code>CAPS_WITH_UNDER</code></td> |
| 1900 | <td><code>_CAPS_WITH_UNDER</code></td> |
| 1901 | </tr> |
| 1902 | |
| 1903 | <tr> |
| 1904 | <td>Global/Class Variables</td> |
| 1905 | <td><code>lower_with_under</code></td> |
| 1906 | <td><code>_lower_with_under</code></td> |
| 1907 | </tr> |
| 1908 | |
| 1909 | <tr> |
| 1910 | <td>Instance Variables</td> |
| 1911 | <td><code>lower_with_under</code></td> |
| 1912 | <td><code>_lower_with_under (protected) or __lower_with_under (private)</code></td> |
| 1913 | </tr> |
| 1914 | |
| 1915 | |
| 1916 | |
| 1917 | <tr> |
| 1918 | <td>Method Names</td> |
| 1919 | <td><code>lower_with_under()</code></td> |
| 1920 | <td><code>_lower_with_under() (protected) or __lower_with_under() (private)</code></td> |
| 1921 | </tr> |
| 1922 | |
| 1923 | <tr> |
| 1924 | <td>Function/Method Parameters</td> |
| 1925 | <td><code>lower_with_under</code></td> |
| 1926 | <td></td> |
| 1927 | </tr> |
| 1928 | |
| 1929 | <tr> |
| 1930 | <td>Local Variables</td> |
| 1931 | <td><code>lower_with_under</code></td> |
| 1932 | <td></td> |
| 1933 | </tr> |
| 1934 | |
| 1935 | |
| 1936 | </table> |
| 1937 | |
| 1938 | |
| 1939 | </P> |
| 1940 | </SPAN></SPAN> |
| 1941 | </SPAN> |
| 1942 | <SPAN class=""><H3><A name="Main" id="Main">Main</A></H3> |
| 1943 | <SPAN class="showhide_button" onclick="javascript:ShowHideByName('Main__body','Main__button')" name="Main__button" id="Main__button">▶</SPAN> |
| 1944 | <SPAN class=""> |
| 1945 | Even a file meant to be used as a script should be importable and a |
| 1946 | mere import should not have the side effect of executing the script's |
| 1947 | main functionality. The main functionality should be in a main() |
| 1948 | function. |
| 1949 | </SPAN> |
| 1950 | <SPAN class=""><BR><SPAN class="stylepoint_body" name="Main__body" id="Main__body" style="display: none"><SPAN class="link_button"><A href="?showone=Main#Main"> |
| 1951 | link |
| 1952 | </A></SPAN> |
| 1953 | <p> |
| 1954 | In Python, |
| 1955 | <code>pychecker</code>, <code>pydoc</code>, and unit tests |
| 1956 | require modules to be importable. Your code should always check |
| 1957 | <code>if __name__ == '__main__'</code> before executing your |
| 1958 | main program so that the main program is not executed when the |
| 1959 | module is imported. |
| 1960 | |
| 1961 | </p> |
| 1962 | |
| 1963 | |
| 1964 | |
| 1965 | |
| 1966 | |
| 1967 | |
| 1968 | |
| 1969 | <SPAN class=""><PRE> |
| 1970 | <span class="external"></span>def main(): |
| 1971 | <span class="external"> </span>... |
| 1972 | |
| 1973 | <span class="external"></span>if __name__ == '__main__': |
| 1974 | <span class="external"> </span>main() |
| 1975 | <span class="external"></span> |
| 1976 | </PRE></SPAN> |
| 1977 | |
| 1978 | <p> |
| 1979 | All code at the top level will be executed when the module is |
| 1980 | imported. Be careful not to call functions, create objects, or |
| 1981 | perform other operations that should not be executed when the |
| 1982 | file is being <code>pycheck</code>ed or <code>pydoc</code>ed. |
| 1983 | </p> |
| 1984 | </SPAN></SPAN> |
| 1985 | </SPAN> |
| 1986 | </SPAN> |
| 1987 | |
| 1988 | <H2>Parting Words</H2> |
| 1989 | <p> |
| 1990 | <em>BE CONSISTENT</em>. |
| 1991 | </p> |
| 1992 | |
| 1993 | <p> |
| 1994 | If you're editing code, take a few minutes to look at the code |
| 1995 | around you and determine its style. If they use spaces around |
| 1996 | all their arithmetic operators, you should too. If their |
| 1997 | comments have little boxes of hash marks around them, make your |
| 1998 | comments have little boxes of hash marks around them too. |
| 1999 | </p> |
| 2000 | |
| 2001 | <p> |
| 2002 | The point of having style guidelines is to have a common vocabulary |
| 2003 | of coding so people can concentrate on what you're saying rather |
| 2004 | than on how you're saying it. We present global style rules here so |
| 2005 | people know the vocabulary, but local style is also important. If |
| 2006 | code you add to a file looks drastically different from the existing |
| 2007 | code around it, it throws readers out of their rhythm when they go to |
| 2008 | read it. Avoid this. |
| 2009 | </p> |
| 2010 | |
| 2011 | |
| 2012 | |
| 2013 | <p align="right"> |
| 2014 | Revision 2.12 |
| 2015 | </p> |
| 2016 | |
| 2017 | |
| 2018 | <address> |
| 2019 | Amit Patel<br> |
| 2020 | Antoine Picard<br> |
| 2021 | Eugene Jhong<br> |
| 2022 | Jeremy Hylton<br> |
| 2023 | Matt Smart<br> |
| 2024 | Mike Shields<br> |
| 2025 | </address> |
| 2026 | </BODY> |
| 2027 | </HTML> |