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