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