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