blob: 23939e18fca342b16c8515b90bf3ddd205c0c527 [file] [log] [blame]
mmentovaif7facf92009-10-23 21:01:49 +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">
apicard@google.comf900c2c2009-07-23 20:09:56 +00002<HEAD>
apicard@google.comf900c2c2009-07-23 20:09:56 +00003<TITLE>Google Python Style Guide</TITLE>
mmentovaib729e3c2010-08-10 18:40:41 +00004<META http-equiv="Content-Type" content="text/html; charset=utf-8">
apicard@google.comf900c2c2009-07-23 20:09:56 +00005<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;
mmentovai8411f0c2010-08-04 17:46:16 +000011 var linkElement;
apicard@google.comf900c2c2009-07-23 20:09:56 +000012 if (document.getElementsByName) {
13 bodyElements = document.getElementsByName(bodyName);
mmentovai8411f0c2010-08-04 17:46:16 +000014 linkElement = document.getElementsByName('link-' + buttonName)[0];
apicard@google.comf900c2c2009-07-23 20:09:56 +000015 } else {
16 bodyElements = [document.getElementById(bodyName)];
mmentovai8411f0c2010-08-04 17:46:16 +000017 linkElement = document.getElementById('link-' + buttonName);
apicard@google.comf900c2c2009-07-23 20:09:56 +000018 }
19 if (bodyElements.length != 1) {
20 alert("ShowHideByName() got the wrong number of bodyElements: " + bodyElements.length);
21 } else {
22 var bodyElement = bodyElements[0];
23 var buttonElement;
24 if (document.getElementsByName) {
25 var buttonElements = document.getElementsByName(buttonName);
26 buttonElement = buttonElements[0];
27 } else {
28 buttonElement = document.getElementById(buttonName);
29 }
30 if (bodyElement.style.display == "none" || bodyElement.style.display == "") {
31 bodyElement.style.display = "inline";
mmentovai8411f0c2010-08-04 17:46:16 +000032 linkElement.style.display = "block";
apicard@google.comf900c2c2009-07-23 20:09:56 +000033 buttonElement.innerHTML = '▽';
34 } else {
35 bodyElement.style.display = "none";
mmentovai8411f0c2010-08-04 17:46:16 +000036 linkElement.style.display = "none";
apicard@google.comf900c2c2009-07-23 20:09:56 +000037 buttonElement.innerHTML = '▶';
38 }
39 }
40 }
41
42 function ShowHideAll() {
43 var allButton;
44 if (document.getElementsByName) {
45 var allButtons = document.getElementsByName("show_hide_all_button");
46 allButton = allButtons[0];
47 } else {
48 allButton = document.getElementById("show_hide_all_button");
49 }
50 if (allButton.innerHTML == '▽') {
51 allButton.innerHTML = '▶';
52 SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "none", '▶');
53 } else {
54 allButton.innerHTML = '▽';
55 SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "inline", '▽');
56 }
57 }
58
59 // Recursively sets state of all children
60 // of a particular node.
61 function SetHiddenState(root, newState, newButton) {
62 for (var i = 0; i != root.length; i++) {
63 SetHiddenState(root[i].childNodes, newState, newButton);
64 if (root[i].className == 'showhide_button') {
65 root[i].innerHTML = newButton;
66 }
mmentovai8411f0c2010-08-04 17:46:16 +000067 if (root[i].className == 'stylepoint_body' ||
68 root[i].className == 'link_button') {
apicard@google.comf900c2c2009-07-23 20:09:56 +000069 root[i].style.display = newState;
70 }
71 }
72 }
73
74
75 window.onload = function() {
76 // if the URL contains "?showall=y", expand the details of all children
77 {
78 var showHideAllRegex = new RegExp("[\\?&](showall)=([^&#]*)");
79 var showHideAllValue = showHideAllRegex.exec(window.location.href);
80 if (showHideAllValue != null) {
81 if (showHideAllValue[2] == "y") {
82 SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "inline", '▽');
83 } else {
84 SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "none", '▶');
85 }
86 }
87 var showOneRegex = new RegExp("[\\?&](showone)=([^&#]*)");
88 var showOneValue = showOneRegex.exec(window.location.href);
89 if (showOneValue != null) {
90 var body_name = showOneValue[2] + '__body';
91 var button_name = showOneValue[2] + '__button';
92 ShowHideByName(body_name, button_name);
93 }
94
95 }
96 }
97 </SCRIPT>
98</HEAD>
99<BODY>
100<H1>Google Python Style Guide</H1>
101 <p align="right">
102
mmentovai9ec7bd62009-12-03 22:25:38 +0000103 Revision 2.15
apicard@google.comf900c2c2009-07-23 20:09:56 +0000104 </p>
105
106 <address>
107 Amit Patel<br>
108 Antoine Picard<br>
109 Eugene Jhong<br>
110 Jeremy Hylton<br>
111 Matt Smart<br>
112 Mike Shields<br>
113 </address>
114 <DIV style="margin-left: 50%; font-size: 75%;">
115<P>
116 Each style point has a summary for which additional information is available
117 by toggling the accompanying arrow button that looks this way:
mmentovai8411f0c2010-08-04 17:46:16 +0000118 <SPAN class="showhide_button" style="margin-left: 0; float: none"></SPAN>.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000119 You may toggle all summaries with the big arrow button:
120 </P>
121<DIV style=" font-size: larger; margin-left: +2em;">
mmentovai8411f0c2010-08-04 17:46:16 +0000122<SPAN class="showhide_button" style="font-size: 180%; float: none" onclick="javascript:ShowHideAll()" name="show_hide_all_button" id="show_hide_all_button"></SPAN>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000123 Toggle all summaries
124 </DIV>
125</DIV>
126<DIV class="toc">
127<DIV class="toc_title">Table of Contents</DIV>
128<TABLE>
129<TR valign="top" class="">
130<TD><DIV class="toc_category"><A href="#Python_Language_Rules">Python Language Rules</A></DIV></TD>
131<TD><DIV class="toc_stylepoint">
mmentovaif7facf92009-10-23 21:01:49 +0000132<SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#pychecker">pychecker</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Imports">Imports</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Packages">Packages</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Exceptions">Exceptions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Global_variables">Global variables</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Nested/Local/Inner_Classes_and_Functions">Nested/Local/Inner Classes and Functions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#List_Comprehensions">List Comprehensions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Default_Iterators_and_Operators">Default Iterators and Operators</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Generators">Generators</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Lambda_Functions">Lambda Functions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Default_Argument_Values">Default Argument Values</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Properties">Properties</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#True/False_evaluations">True/False evaluations</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Deprecated_Language_Features">Deprecated Language Features</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Lexical_Scoping">Lexical Scoping</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Function_and_Method_Decorators">Function and Method Decorators</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Threading">Threading</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Power_Features">Power Features</A></SPAN> </DIV></TD>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000133</TR>
134<TR valign="top" class="">
135<TD><DIV class="toc_category"><A href="#Python_Style_Rules">Python Style Rules</A></DIV></TD>
136<TD><DIV class="toc_stylepoint">
137<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>
138</TR>
139</TABLE>
140</DIV>
mmentovai9ec7bd62009-12-03 22:25:38 +0000141 <DIV class="">
142<H2 name="Important_Note" id="Important_Note">Important Note</H2>
143 <DIV class="">
144<H3><A name="Displaying_Hidden_Details_in_this_Guide" id="Displaying_Hidden_Details_in_this_Guide">Displaying Hidden Details in this Guide</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000145<SPAN class="link_button" id="link-Displaying_Hidden_Details_in_this_Guide__button" name="link-Displaying_Hidden_Details_in_this_Guide__button"><A href="?showone=Displaying_Hidden_Details_in_this_Guide#Displaying_Hidden_Details_in_this_Guide">
146 link
147 </A></SPAN><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>
mmentovai9ec7bd62009-12-03 22:25:38 +0000148 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000149 This style guide contains many details that are initially
150 hidden from view. They are marked by the triangle icon, which you
151 see here on your left. Click it now.
152 You should see "Hooray" appear below.
mmentovai9ec7bd62009-12-03 22:25:38 +0000153 </DIV>
154 <DIV class=""><DIV class="stylepoint_body" name="Displaying_Hidden_Details_in_this_Guide__body" id="Displaying_Hidden_Details_in_this_Guide__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000155 <p>
156 Hooray! Now you know you can expand points to get more
157 details. Alternatively, there's a "toggle all" at the
158 top of this document.
159 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000160 </DIV></DIV>
161 </DIV>
162 </DIV>
163 <DIV class="">
164<H2 name="Background" id="Background">Background</H2>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000165 <p>
166 Python is the main scripting language used at Google. This
167 style guide is a list of <em>do</em>s and <em>don't</em>s for Python
168 programs.
169 </p>
170
171
172
mmentovai9ec7bd62009-12-03 22:25:38 +0000173 </DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000174
mmentovai9ec7bd62009-12-03 22:25:38 +0000175 <DIV class="">
176<H2 name="Python_Language_Rules" id="Python_Language_Rules">Python Language Rules</H2>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000177
mmentovai9ec7bd62009-12-03 22:25:38 +0000178 <DIV class="">
179<H3><A name="pychecker" id="pychecker">pychecker</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000180<SPAN class="link_button" id="link-pychecker__button" name="link-pychecker__button"><A href="?showone=pychecker#pychecker">
181 link
182 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('pychecker__body','pychecker__button')" name="pychecker__button" id="pychecker__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000183 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000184 Run <code>pychecker</code> over your code.
mmentovai9ec7bd62009-12-03 22:25:38 +0000185 </DIV>
mmentovai8411f0c2010-08-04 17:46:16 +0000186 <DIV class=""><DIV class="stylepoint_body" name="pychecker__body" id="pychecker__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000187 <P class="">
188<SPAN class="stylepoint_section">Definition: </SPAN>
189 PyChecker is a tool for finding bugs in Python source code. It finds
190 problems that are typically caught by a compiler for less dynamic
191 languages like C and C++. It is similar to lint. Because of the
192 dynamic nature of Python, some warnings may be incorrect; however,
193 spurious warnings should be fairly infrequent.
194 </P>
195 <P class="">
196<SPAN class="stylepoint_section">Pros: </SPAN>
197 Catches easy-to-miss errors like typos, use-vars-before-assignment, etc.
198 </P>
199 <P class="">
200<SPAN class="stylepoint_section">Cons: </SPAN>
201 <code>pychecker</code> isn't perfect. To take
202 advantage of it, we'll need to sometimes: a) Write around it b)
203 Suppress its warnings c) Improve it or d) Ignore it.
204 </P>
205 <P class="">
206<SPAN class="stylepoint_section">Decision: </SPAN>
207 Make sure you run <code>pychecker</code> on your code.
208 </P>
209
210 <p>
211 For information on how to run <code>pychecker</code>, see the
212 <a HREF="http://pychecker.sourceforge.net">pychecker
213 homepage</a>
214 </p>
215 <p>
216 To suppress warnings, you can set a module-level variable named
217 <code>__pychecker__</code> to suppress appropriate warnings.
218 For example:
219 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000220 <DIV class=""><PRE>
221<span class="external"></span>__pychecker__ = 'no-callinit no-classattr'</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000222 <p>
223 Suppressing in this way has the advantage that we can easily search
224 for suppressions and revisit them.
225 </p>
226 <p>
227 You can get a list of pychecker warnings by doing
228 <code>pychecker --help</code>.
229 </p>
230 <p>
231 Unused argument warnings can be suppressed by using `_' as the
232 identifier for the unused argument or prefixing the argument name with
233 `unused_'. In situations where changing the argument names is
234 infeasible, you can mention them at the beginning of the function.
235 For example:
236 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000237 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000238<span class="external"></span>def foo(a, unused_b, unused_c, d=None, e=None):
239 <span class="external"> </span>(d, e) = (d, e) # Silence pychecker
240 <span class="external"> </span>return a
241<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000242</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000243 <p>
244 Ideally, pychecker would be extended to ensure that such `unused
245 declarations' were true.
246 </p>
247
mmentovai9ec7bd62009-12-03 22:25:38 +0000248 </DIV></DIV>
249 </DIV>
250 <DIV class="">
251<H3><A name="Imports" id="Imports">Imports</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000252<SPAN class="link_button" id="link-Imports__button" name="link-Imports__button"><A href="?showone=Imports#Imports">
253 link
254 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Imports__body','Imports__button')" name="Imports__button" id="Imports__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000255 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000256 Use <code>import</code>s for packages and modules only.
mmentovai9ec7bd62009-12-03 22:25:38 +0000257 </DIV>
258 <DIV class=""><DIV class="stylepoint_body" name="Imports__body" id="Imports__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000259 <P class="">
260<SPAN class="stylepoint_section">Definition: </SPAN>
261 Reusability mechanism for sharing code from one module to another.
262 </P>
263 <P class="">
264<SPAN class="stylepoint_section">Pros: </SPAN>
265 Simplest and most commonly used way of sharing things.
266 </P>
267 <P class="">
268<SPAN class="stylepoint_section">Cons: </SPAN> <code>from foo import *</code> or
269 <code>from foo import Bar</code> is
270 very nasty and can lead to serious maintenance issues because
271 it makes it hard to find module dependencies.
272 </P>
273 <P class="">
274<SPAN class="stylepoint_section">Decision: </SPAN>
275 Use <code>import x</code> for importing packages and modules.
276 Use <code>from x import y</code> only when <code>x</code> is a
277 package and <code>y</code> is a module. This allows the
278 importer to refer to the module without specifying the full
279 package prefix. For example the module
280 <code>sound.effects.echo</code> may be imported as follows:
281 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000282 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000283<span class="external"></span>from sound.effects import echo
284<span class="external"></span>...
285<span class="external"></span>echo.echofilter(input, output, delay=0.7, atten=4)
286<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000287</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000288 <p>
289 Even if the module is in the same package, do not directly import
290 the module without the full package name. This might cause the
291 package to be imported twice (with unintended side effects) when the
292 "main" module that is used to start an application lives inside a
293 package (and uses modules from that same package).
294 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000295 </DIV></DIV>
296 </DIV>
297 <DIV class="">
298<H3><A name="Packages" id="Packages">Packages</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000299<SPAN class="link_button" id="link-Packages__button" name="link-Packages__button"><A href="?showone=Packages#Packages">
300 link
301 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Packages__body','Packages__button')" name="Packages__button" id="Packages__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000302 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000303 Import and refer to each module using the full pathname location of
304 that module.
mmentovai9ec7bd62009-12-03 22:25:38 +0000305 </DIV>
306 <DIV class=""><DIV class="stylepoint_body" name="Packages__body" id="Packages__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000307 <P class="">
308<SPAN class="stylepoint_section">Pros: </SPAN>
309 Avoids conflicts in module names. Makes it easier to find modules.
310 </P>
311 <P class="">
312<SPAN class="stylepoint_section">Cons: </SPAN>
313 Makes it harder to deploy code because you have to replicate the
314 package hierarchy.
315 </P>
316 <P class="">
317<SPAN class="stylepoint_section">Decision: </SPAN>
318 All new code should refer to modules based on their package
319 name.
320 </P>
321 <p>
322 Imports should be as follows:
323 </p>
324
325
mmentovai9ec7bd62009-12-03 22:25:38 +0000326 <DIV class=""><PRE># Reference in code with complete name.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000327import sound.effects.echo
328
329# Reference in code with just module name.
330from sound.effects import echo
mmentovai9ec7bd62009-12-03 22:25:38 +0000331</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000332
mmentovai9ec7bd62009-12-03 22:25:38 +0000333 </DIV></DIV>
334 </DIV>
335 <DIV class="">
336<H3><A name="Exceptions" id="Exceptions">Exceptions</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000337<SPAN class="link_button" id="link-Exceptions__button" name="link-Exceptions__button"><A href="?showone=Exceptions#Exceptions">
338 link
339 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Exceptions__body','Exceptions__button')" name="Exceptions__button" id="Exceptions__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000340 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000341 Exceptions are allowed but must be used carefully.
mmentovai9ec7bd62009-12-03 22:25:38 +0000342 </DIV>
343 <DIV class=""><DIV class="stylepoint_body" name="Exceptions__body" id="Exceptions__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000344 <P class="">
345<SPAN class="stylepoint_section">Definition: </SPAN>
346 Exceptions are a means of breaking out of the normal flow of control
347 of a code block to handle errors or other exceptional conditions.
348 </P>
349 <P class="">
350<SPAN class="stylepoint_section">Pros: </SPAN>
351 The control flow of normal operation code is not cluttered by
352 error-handling code. It also allows the control flow to skip multiple
353 frames when a certain condition occurs, e.g., returning from N
354 nested functions in one step instead of having to carry-through
355 error codes.
356 </P>
357 <P class="">
358<SPAN class="stylepoint_section">Cons: </SPAN>
359 May cause the control flow to be confusing. Easy to miss error
360 cases when making library calls.
361 </P>
362 <P class="">
363<SPAN class="stylepoint_section">Decision: </SPAN>
364
365
366 Exceptions must follow certain conditions:
367
368 <ul>
369 <li>Raise exceptions like this: <code>raise MyException("Error
370 message")</code> or <code>raise MyException</code>. Do not
371 use the two-argument form (<code>raise MyException, "Error
372 message"</code>) or deprecated string-based exceptions
373 (<code>raise "Error message"</code>).</li>
374 <li>Modules or packages should define their own domain-specific
375 base exception class, which should inherit from the built-in
376 Exception class. The base exception for a module should be called
377 <code>Error</code>.
mmentovai9ec7bd62009-12-03 22:25:38 +0000378 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000379<span class="external"></span>class Error(Exception):
mmentovai9ec7bd62009-12-03 22:25:38 +0000380 <span class="external"> </span>pass</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000381</li>
382 <li>Never use catch-all <code>except:</code> statements, or
383 catch <code>Exception</code> or <code>StandardError</code>,
384 unless you are re-raising the exception or in the outermost
385 block in your thread (and printing an error message). Python
386 is very tolerant in this regard and <code>except:</code> will
387 really catch everything including Python syntax errors. It is
388 easy to hide real bugs using <code>except:</code>.</li>
389 <li>Minimize the amount of code in a
390 <code>try</code>/<code>except</code> block. The larger the
391 body of the <code>try</code>, the more likely that an
392 exception will be raised by a line of code that you didn't
393 expect to raise an exception. In those cases,
394 the <code>try</code>/<code>except</code> block hides a real
395 error.</li>
396 <li>Use the <code>finally</code> clause to execute code whether
397 or not an exception is raised in the <code>try</code> block.
398 This is often useful for cleanup, i.e., closing a file.</li>
399 </ul>
400 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000401 </DIV></DIV>
402 </DIV>
403 <DIV class="">
404<H3><A name="Global_variables" id="Global_variables">Global variables</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000405<SPAN class="link_button" id="link-Global_variables__button" name="link-Global_variables__button"><A href="?showone=Global_variables#Global_variables">
406 link
407 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Global_variables__body','Global_variables__button')" name="Global_variables__button" id="Global_variables__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000408 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000409 Avoid global variables.
mmentovai9ec7bd62009-12-03 22:25:38 +0000410 </DIV>
411 <DIV class=""><DIV class="stylepoint_body" name="Global_variables__body" id="Global_variables__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000412 <P class="">
413<SPAN class="stylepoint_section">Definition: </SPAN>
414 Variables that are declared at the module level.
415 </P>
416 <P class="">
417<SPAN class="stylepoint_section">Pros: </SPAN>
418 Occasionally useful.
419 </P>
420 <P class="">
421<SPAN class="stylepoint_section">Cons: </SPAN>
422 Has the potential to change module behavior during the import,
423 because assignments to module-level variables are done when the
424 module is imported.
425 </P>
426 <P class="">
427<SPAN class="stylepoint_section">Decision: </SPAN>
428 Avoid global variables in favor of class variables. Some
429 exceptions are:
430 <ul>
431 <li>Default options for scripts.</li>
432 <li>Module-level constants. For example: <code>PI = 3.14159</code>.
433 Constants should be named using all caps with underscores;
434 see <a HREF="#Naming">Naming</a> below.</li>
435 <li>It is sometimes useful for globals to cache values needed
436 or returned by functions.</li>
437 <li>If needed, globals should be made internal to the module
438 and accessed through public module level functions;
439 see <a HREF="#Naming">Naming</a> below.</li>
440 </ul>
441 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000442 </DIV></DIV>
443 </DIV>
444 <DIV class="">
445<H3><A name="Nested/Local/Inner_Classes_and_Functions" id="Nested/Local/Inner_Classes_and_Functions">Nested/Local/Inner Classes and Functions</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000446<SPAN class="link_button" id="link-Nested/Local/Inner_Classes_and_Functions__button" name="link-Nested/Local/Inner_Classes_and_Functions__button"><A href="?showone=Nested/Local/Inner_Classes_and_Functions#Nested/Local/Inner_Classes_and_Functions">
447 link
448 </A></SPAN><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>
mmentovai9ec7bd62009-12-03 22:25:38 +0000449 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000450 Nested/local/inner classes and functions are fine.
mmentovai9ec7bd62009-12-03 22:25:38 +0000451 </DIV>
452 <DIV class=""><DIV class="stylepoint_body" name="Nested/Local/Inner_Classes_and_Functions__body" id="Nested/Local/Inner_Classes_and_Functions__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000453 <P class="">
454<SPAN class="stylepoint_section">Definition: </SPAN>
mmentovaif7facf92009-10-23 21:01:49 +0000455 A class can be defined inside of a method, function, or class. A
456 function can be defined inside a method or function. Nested functions
457 have read-only access to variables defined in enclosing scopes.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000458 </P>
459 <P class="">
460<SPAN class="stylepoint_section">Pros: </SPAN>
461 Allows definition of utility classes and functions that are only
462 used inside of a very limited scope. Very <a HREF="http://en.wikipedia.org/wiki/Abstract_data_type">ADT</a>-y.
463 </P>
464 <P class="">
465<SPAN class="stylepoint_section">Cons: </SPAN>
466 Instances of nested or local classes cannot be pickled.
467 </P>
468 <P class="">
469<SPAN class="stylepoint_section">Decision: </SPAN>
470 They are fine.
471 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000472 </DIV></DIV>
473 </DIV>
474 <DIV class="">
475<H3><A name="List_Comprehensions" id="List_Comprehensions">List Comprehensions</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000476<SPAN class="link_button" id="link-List_Comprehensions__button" name="link-List_Comprehensions__button"><A href="?showone=List_Comprehensions#List_Comprehensions">
477 link
478 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('List_Comprehensions__body','List_Comprehensions__button')" name="List_Comprehensions__button" id="List_Comprehensions__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000479 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000480 Okay to use for simple cases.
mmentovai9ec7bd62009-12-03 22:25:38 +0000481 </DIV>
482 <DIV class=""><DIV class="stylepoint_body" name="List_Comprehensions__body" id="List_Comprehensions__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000483 <P class="">
484<SPAN class="stylepoint_section">Definition: </SPAN>
485 List comprehensions and generator expressions provide a concise
486 and efficient way to create lists and iterators without
487 resorting to the use of <code>map()</code>,
488 <code>filter()</code>, or <code>lambda</code>.
489 </P>
490 <P class="">
491<SPAN class="stylepoint_section">Pros: </SPAN>
492 Simple list comprehensions can be clearer and simpler than
493 other list creation techniques. Generator expressions can be
494 very efficient, since they avoid the creation of a list
495 entirely.
496 </P>
497 <P class="">
498<SPAN class="stylepoint_section">Cons: </SPAN>
499 Complicated list comprehensions or generator expressions can be
500 hard to read.
501 </P>
502 <P class="">
503<SPAN class="stylepoint_section">Decision: </SPAN>
504 Okay to use for simple cases. Each portion must fit on one line:
505 mapping expression, <code>for</code> clause, filter expression.
506 Multiple <code>for</code> clauses or filter expressions are not
507 permitted. Use loops instead when things get more complicated.
508 </P>
509
mmentovai9ec7bd62009-12-03 22:25:38 +0000510<DIV class=""><PRE class="badcode">No<span class="external"></span>:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000511 <span class="external"></span>result = [(x, y) for x in range(10) for y in range(5) if x * y &gt; 10]
512
513 <span class="external"></span>return ((x, y, z)
514 <span class="external"></span> for x in xrange(5)
515 <span class="external"></span> for y in xrange(5)
516 <span class="external"></span> if x != y
517 <span class="external"></span> for z in xrange(5)
mmentovai9ec7bd62009-12-03 22:25:38 +0000518 <span class="external"></span> if y != z)</PRE></DIV>
519<DIV class=""><PRE>Ye<span class="external"></span>s:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000520 <span class="external"></span>result = []
521 <span class="external"></span>for x in range(10):
522 <span class="external"> </span>for y in range(5):
523 <span class="external"> </span>if x * y &gt; 10:
524 <span class="external"> </span>result.append((x, y))
525
526 <span class="external"></span>for x in xrange(5):
527 <span class="external"> </span>for y in xrange(5):
528 <span class="external"> </span>if x != y:
529 <span class="external"> </span>for z in xrange(5):
530 <span class="external"> </span>if y != z:
531 <span class="external"> </span>yield (x, y, z)
532
533 <span class="external"></span>return ((x, complicated_transform(x))
534 <span class="external"></span> for x in long_generator_function(parameter)
535 <span class="external"></span> if x is not None)
536
537 <span class="external"></span>squares = [x * x for x in range(10)]
538
539 <span class="external"></span>eat(jelly_bean for jelly_bean in jelly_beans
mmentovai9ec7bd62009-12-03 22:25:38 +0000540 <span class="external"></span> if jelly_bean.color == 'black')</PRE></DIV>
541 </DIV></DIV>
542 </DIV>
543 <DIV class="">
544<H3><A name="Default_Iterators_and_Operators" id="Default_Iterators_and_Operators">Default Iterators and Operators</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000545<SPAN class="link_button" id="link-Default_Iterators_and_Operators__button" name="link-Default_Iterators_and_Operators__button"><A href="?showone=Default_Iterators_and_Operators#Default_Iterators_and_Operators">
546 link
547 </A></SPAN><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>
mmentovai9ec7bd62009-12-03 22:25:38 +0000548 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000549 Use default iterators and operators for types that support them,
550 like lists, dictionaries, and files.
mmentovai9ec7bd62009-12-03 22:25:38 +0000551 </DIV>
552 <DIV class=""><DIV class="stylepoint_body" name="Default_Iterators_and_Operators__body" id="Default_Iterators_and_Operators__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000553 <P class="">
554<SPAN class="stylepoint_section">Definition: </SPAN>
555 Container types, like dictionaries and lists, define default
556 iterators and membership test operators ("in" and "not in").
557 </P>
558 <P class="">
559<SPAN class="stylepoint_section">Pros: </SPAN>
560 The default iterators and operators are simple and efficient.
561 They express the operation directly, without extra method calls.
562 A function that uses default operators is generic. It can be
563 used with any type that supports the operation.
564 </P>
565 <P class="">
566<SPAN class="stylepoint_section">Cons: </SPAN>
567 You can't tell the type of objects by reading the method names
568 (e.g. has_key() means a dictionary). This is also an advantage.
569 </P>
570 <P class="">
571<SPAN class="stylepoint_section">Decision: </SPAN> Use default iterators and operators for types
572 that support them, like lists, dictionaries, and files. The
573 built-in types define iterator methods, too. Prefer these
574 methods to methods that return lists, except that you should not
575 mutate a container while iterating over it.
576
mmentovai9ec7bd62009-12-03 22:25:38 +0000577<DIV class=""><PRE>Yes: <span class="external"></span>for key in adict: ...
apicard@google.comf900c2c2009-07-23 20:09:56 +0000578 <span class="external"></span>if key not in adict: ...
579 <span class="external"></span>if obj in alist: ...
580 <span class="external"></span>for line in afile: ...
mmentovai9ec7bd62009-12-03 22:25:38 +0000581 <span class="external"></span>for k, v in dict.iteritems(): ...</PRE></DIV>
582<DIV class=""><PRE class="badcode">No: <span class="external"></span>for key in adict.keys(): ...
apicard@google.comf900c2c2009-07-23 20:09:56 +0000583 <span class="external"></span>if not adict.has_key(key): ...
mmentovai9ec7bd62009-12-03 22:25:38 +0000584 <span class="external"></span>for line in afile.readlines(): ...</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000585 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000586 </DIV></DIV>
587 </DIV>
588 <DIV class="">
589<H3><A name="Generators" id="Generators">Generators</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000590<SPAN class="link_button" id="link-Generators__button" name="link-Generators__button"><A href="?showone=Generators#Generators">
591 link
592 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Generators__body','Generators__button')" name="Generators__button" id="Generators__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000593 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000594 Use generators as needed.
mmentovai9ec7bd62009-12-03 22:25:38 +0000595 </DIV>
596 <DIV class=""><DIV class="stylepoint_body" name="Generators__body" id="Generators__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000597 <P class="">
598<SPAN class="stylepoint_section">Definition: </SPAN>
599 A generator function returns an iterator that yields a value each
600 time it executes a yield statement. After it yields a value, the
601 runtime state of the generator function is suspended until the
602 next value is needed.
603 </P>
604 <P class="">
605<SPAN class="stylepoint_section">Pros: </SPAN>
606 Simpler code, because the state of local variables and control flow
607 are preserved for each call. A generator uses less memory than a
608 function that creates an entire list of values at once.
609 </P>
610 <P class="">
611<SPAN class="stylepoint_section">Cons: </SPAN>
612 None.
613 </P>
614 <P class="">
615<SPAN class="stylepoint_section">Decision: </SPAN>
616 Fine. Use "Yields:" rather than "Returns:" in the
617 doc string for generator functions.
618 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000619 </DIV></DIV>
620 </DIV>
621 <DIV class="">
622<H3><A name="Lambda_Functions" id="Lambda_Functions">Lambda Functions</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000623<SPAN class="link_button" id="link-Lambda_Functions__button" name="link-Lambda_Functions__button"><A href="?showone=Lambda_Functions#Lambda_Functions">
624 link
625 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Lambda_Functions__body','Lambda_Functions__button')" name="Lambda_Functions__button" id="Lambda_Functions__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000626 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000627 Okay for one-liners.
mmentovai9ec7bd62009-12-03 22:25:38 +0000628 </DIV>
629 <DIV class=""><DIV class="stylepoint_body" name="Lambda_Functions__body" id="Lambda_Functions__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000630 <P class="">
631<SPAN class="stylepoint_section">Definition: </SPAN>
632 Lambdas define anonymous functions in an expression, as
633 opposed to a statement. They are often used to define callbacks or
634 operators for higher-order functions like <code>map()</code> and
635 <code>filter()</code>.
636 </P>
637 <P class="">
638<SPAN class="stylepoint_section">Pros: </SPAN>
639 Convenient.
640 </P>
641 <P class="">
642<SPAN class="stylepoint_section">Cons: </SPAN> Harder to read and debug than local functions. The
643 lack of names means stack traces are more difficult to
644 understand. Expressiveness is limited because the function may
645 only contain an expression.
646 </P>
647 <P class="">
648<SPAN class="stylepoint_section">Decision: </SPAN>
649 Okay to use them for one-liners. If the code inside the lambda
650 function is any longer than 60–80 chars, it's probably better to
651 define it as a regular (nested) function.
652 <p>
653 For common operations like multiplication, use the functions from the
654 <code>operator</code> module instead of lambda functions. For
655 example, prefer <code>operator.mul</code> to <code>lambda
656 x, y: x * y</code>.
657 </p>
658 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000659 </DIV></DIV>
660 </DIV>
661 <DIV class="">
662<H3><A name="Default_Argument_Values" id="Default_Argument_Values">Default Argument Values</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000663<SPAN class="link_button" id="link-Default_Argument_Values__button" name="link-Default_Argument_Values__button"><A href="?showone=Default_Argument_Values#Default_Argument_Values">
664 link
665 </A></SPAN><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>
mmentovai9ec7bd62009-12-03 22:25:38 +0000666 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000667 Okay in most cases.
mmentovai9ec7bd62009-12-03 22:25:38 +0000668 </DIV>
669 <DIV class=""><DIV class="stylepoint_body" name="Default_Argument_Values__body" id="Default_Argument_Values__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000670 <P class="">
671<SPAN class="stylepoint_section">Definition: </SPAN>
672 You can specify values for variables at the end of a function's
673 parameter list, e.g., <code>def foo(a, b=0):</code>. If
674 <code>foo</code> is called with only one argument,
675 <code>b</code> is set to 0. If it is called with two arguments,
676 <code>b</code> has the value of the second argument.
677 </P>
678 <P class="">
679<SPAN class="stylepoint_section">Pros: </SPAN>
680 Often you have a function that uses lots of default values,
681 but—rarely—you want to override the
682 defaults. Default argument values provide an easy way to do this,
683 without having to define lots of functions for the rare
684 exceptions. Also, Python does not support overloaded
685 methods/functions and default arguments are an easy way of
686 "faking" the overloading behavior.
687 </P>
688 <P class="">
689<SPAN class="stylepoint_section">Cons: </SPAN>
690 Default arguments are evaluated once at module load
691 time. This may cause problems if the argument is a mutable
692 object such as a list or a dictionary. If the function modifies
693 the object (e.g., by appending an item to a list), the default
694 value is modified.
695 </P>
696 <P class="">
697<SPAN class="stylepoint_section">Decision: </SPAN>
698 Okay to use with the following caveats:
699 <p>
700 Do not use mutable objects as default values in the function or method
701 definition.
702 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000703<DIV class=""><PRE>Yes: <span class="external"></span>def foo(a, b=None):
apicard@google.comf900c2c2009-07-23 20:09:56 +0000704 <span class="external"> </span>if b is None:
mmentovai9ec7bd62009-12-03 22:25:38 +0000705 <span class="external"> </span>b = []</PRE></DIV>
706<DIV class=""><PRE class="badcode">No: <span class="external"></span>def foo(a, b=[]):
707 <span class="external"> </span>...</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000708 <p>
mmentovaif7facf92009-10-23 21:01:49 +0000709 Calling code must use named values for arguments with a default value.
710 This helps document the code somewhat and helps prevent and detect
apicard@google.comf900c2c2009-07-23 20:09:56 +0000711 interface breakage when more arguments are added.
712 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000713<DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000714<span class="external"></span>def foo(a, b=1):
mmentovai9ec7bd62009-12-03 22:25:38 +0000715 <span class="external"> </span>...</PRE></DIV>
716<DIV class=""><PRE>Yes: <span class="external"></span>foo(1)
717 <span class="external"></span>foo(1, b=2)</PRE></DIV>
718<DIV class=""><PRE class="badcode">No: <span class="external"></span>foo(1, 2)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000719 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000720 </DIV></DIV>
721 </DIV>
722 <DIV class="">
723<H3><A name="Properties" id="Properties">Properties</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000724<SPAN class="link_button" id="link-Properties__button" name="link-Properties__button"><A href="?showone=Properties#Properties">
725 link
726 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Properties__body','Properties__button')" name="Properties__button" id="Properties__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000727 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000728 Use properties for accessing or setting data where you would
729 normally have used simple, lightweight accessor or setter methods.
mmentovai9ec7bd62009-12-03 22:25:38 +0000730 </DIV>
731 <DIV class=""><DIV class="stylepoint_body" name="Properties__body" id="Properties__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000732 <P class="">
733<SPAN class="stylepoint_section">Definition: </SPAN> A way to wrap method calls for getting and
734 setting an attribute as a standard attribute access when the
735 computation is lightweight.
736 </P>
737 <P class="">
738<SPAN class="stylepoint_section">Pros: </SPAN> Readability is increased by eliminating explicit
739 get and set method calls for simple attribute access. Allows
740 calculations to be lazy. Considered the Pythonic way to
741 maintain the interface of a class. In terms of performance,
742 allowing properties bypasses needing trivial accessor methods
743 when a direct variable access is reasonable. This also allows
744 accessor methods to be added in the future without breaking the
745 interface.
746 </P>
747 <P class="">
748<SPAN class="stylepoint_section">Cons: </SPAN> Properties are specified after the getter and
749 setter methods are declared, requiring one to notice they are
750 used for properties farther down in the code (except for readonly
751 properties created with the <code>@property</code> decorator - see
752 below). Must inherit from
753 <code>object</code>. Can hide side-effects much like operator
754 overloading. Can be confusing for subclasses.
755 </P>
756 <P class="">
757<SPAN class="stylepoint_section">Decision: </SPAN> Use properties in new code to access or
758 set data where you would normally have used simple, lightweight
759 accessor or setter methods. Read-only properties should be created
760 with the <code>@property</code>
761 <a HREF="#Function_and_Method_Decorators">decorator</a>.
762
763 <p><a id="properties-template-dp">
764 Inheritance with properties can be non-obvious if the property itself is
765 not overridden. Thus one must make sure that accessor methods are
766 called indirectly to ensure methods overridden in subclasses are called
767 by the property (using the Template Method DP).
768 </a></p>
769
mmentovai9ec7bd62009-12-03 22:25:38 +0000770 <DIV class=""><PRE>Yes: <span class="external"></span>import math
apicard@google.comf900c2c2009-07-23 20:09:56 +0000771
772 <span class="external"></span>class Square(object):
773 <span class="external"> </span>"""A square with two properties: a writable area and a read-only perimeter.
774
775 <span class="external"> </span>To use:
776 <span class="external"> </span>&gt;&gt;&gt; sq = Square(3)
777 <span class="external"> </span>&gt;&gt;&gt; sq.area
778 <span class="external"> </span>9
779 <span class="external"> </span>&gt;&gt;&gt; sq.perimeter
780 <span class="external"> </span>12
781 <span class="external"> </span>&gt;&gt;&gt; sq.area = 16
782 <span class="external"> </span>&gt;&gt;&gt; sq.side
783 <span class="external"> </span>4
784 <span class="external"> </span>&gt;&gt;&gt; sq.perimeter
785 <span class="external"> </span>16
786 <span class="external"> </span>"""
787
788 <span class="external"> </span>def __init__(self, side):
789 <span class="external"> </span>self.side = side
790
791 <span class="external"> </span>def __get_area(self):
792 <span class="external"> </span>"""Calculates the 'area' property."""
793 <span class="external"> </span>return self.side ** 2
794
795 <span class="external"> </span>def ___get_area(self):
796 <span class="external"> </span>"""Indirect accessor for 'area' property."""
797 <span class="external"> </span>return self.__get_area()
798
799 <span class="external"> </span>def __set_area(self, area):
800 <span class="external"> </span>"""Sets the 'area' property."""
801 <span class="external"> </span>self.side = math.sqrt(area)
802
803 <span class="external"> </span>def ___set_area(self, area):
804 <span class="external"> </span>"""Indirect setter for 'area' property."""
805 <span class="external"> </span>self._SetArea(area)
806
807 <span class="external"> </span>area = property(___get_area, ___set_area,
808 <span class="external"> </span> doc="""Gets or sets the area of the square.""")
809
810 <span class="external"> </span>@property
811 <span class="external"> </span>def perimeter(self):
812 <span class="external"> </span>return self.side * 4
813<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000814</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000815 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000816 </DIV></DIV>
817 </DIV>
818 <DIV class="">
819<H3><A name="True/False_evaluations" id="True/False_evaluations">True/False evaluations</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000820<SPAN class="link_button" id="link-True/False_evaluations__button" name="link-True/False_evaluations__button"><A href="?showone=True/False_evaluations#True/False_evaluations">
821 link
822 </A></SPAN><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>
mmentovai9ec7bd62009-12-03 22:25:38 +0000823 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000824 Use the "implicit" false if at all possible.
mmentovai9ec7bd62009-12-03 22:25:38 +0000825 </DIV>
826 <DIV class=""><DIV class="stylepoint_body" name="True/False_evaluations__body" id="True/False_evaluations__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000827 <P class="">
828<SPAN class="stylepoint_section">Definition: </SPAN> Python evaluates certain values as <code>false</code>
829 when in a boolean context. A quick "rule of thumb" is that all
830 "empty" values are considered <code>false</code> so <code>0, None, [], {},
831 ""</code> all evaluate as <code>false</code> in a boolean context.
832 </P>
833 <P class="">
834<SPAN class="stylepoint_section">Pros: </SPAN> Conditions using Python booleans are easier to read
835 and less error-prone. In most cases, they're also faster.
836 </P>
837 <P class="">
838<SPAN class="stylepoint_section">Cons: </SPAN>
839 May look strange to C/C++ developers.
840 </P>
841 <P class="">
842<SPAN class="stylepoint_section">Decision: </SPAN>
843 Use the "implicit" false if at all possible, e.g., <code>if
844 foo:</code> rather than <code>if foo != []:</code>. There are a
845 few caveats that you should keep in mind though:
846 <ul>
847 <li>
848 Never use <code>==</code> or <code>!=</code> to compare
849 singletons like <code>None</code>. Use <code>is</code>
850 or <code>is not</code>.</li>
851
852 <li>Beware of writing <code>if x:</code> when you really mean
853 <code>if x is not None:</code>—e.g., when testing whether
854 a variable or argument that defaults to <code>None</code> was
855 set to some other value. The other value might be a value
856 that's false in a boolean context!</li>
857
858 <li>
859 Never compare a boolean variable to <code>False</code> using
860 <code>==</code>. Use <code>if not x:</code> instead. If
861 you need to distinguish <code>False</code> from
862 <code>None</code> then chain the expressions,
863 such as <code>if not x and x is not None:</code>.
864 </li>
865
866 <li>
867 For sequences (strings, lists, tuples), use the fact that
868 empty sequences are false, so <code>if not seq:</code> or
869 <code>if seq:</code> is preferable to <code>if
870 len(seq):</code> or <code>if not
871 len(seq):</code>.</li>
872
873 <li>
874 When handling integers, implicit false may involve more risk than
875 benefit (i.e., accidentally handling <code>None</code> as 0). You may
876 compare a value which is known to be an integer (and is not the
877 result of <code>len()</code>) against the integer 0.
mmentovai9ec7bd62009-12-03 22:25:38 +0000878<DIV class=""><PRE>Yes: <span class="external"></span>if not users:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000879 <span class="external"> </span>print 'no users'
880
881 <span class="external"></span>if foo == 0:
882 <span class="external"> </span>self.handle_zero()
883
884 <span class="external"></span>if i % 10 == 0:
mmentovai9ec7bd62009-12-03 22:25:38 +0000885 <span class="external"> </span>self.handle_multiple_of_ten()</PRE></DIV>
886<DIV class=""><PRE class="badcode">No: <span class="external"></span>if len(users) == 0:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000887 <span class="external"> </span>print 'no users'
888
889 <span class="external"></span>if foo is not None and not foo:
890 <span class="external"> </span>self.handle_zero()
891
892 <span class="external"></span>if not i % 10:
mmentovai9ec7bd62009-12-03 22:25:38 +0000893 <span class="external"> </span>self.handle_multiple_of_ten()</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000894</li>
895
896 <li>
897 Note that <code>'0'</code> (i.e., <code>0</code> as string)
898 evaluates to true.</li>
899 </ul>
900 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000901 </DIV></DIV>
902 </DIV>
903 <DIV class="">
904<H3><A name="Deprecated_Language_Features" id="Deprecated_Language_Features">Deprecated Language Features</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000905<SPAN class="link_button" id="link-Deprecated_Language_Features__button" name="link-Deprecated_Language_Features__button"><A href="?showone=Deprecated_Language_Features#Deprecated_Language_Features">
906 link
907 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Deprecated_Language_Features__body','Deprecated_Language_Features__button')" name="Deprecated_Language_Features__button" id="Deprecated_Language_Features__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000908 <DIV style="display:inline;" class="">
mmentovaif7facf92009-10-23 21:01:49 +0000909 Use string methods instead of the <code>string</code> module
910 where possible. Use function call syntax instead
911 of <code>apply</code>. Use list comprehensions
912 and <code>for</code> loops instead of <code>filter</code>,
913 <code>map</code>, and <code>reduce</code>.
mmentovai9ec7bd62009-12-03 22:25:38 +0000914 </DIV>
915 <DIV class=""><DIV class="stylepoint_body" name="Deprecated_Language_Features__body" id="Deprecated_Language_Features__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000916 <P class="">
mmentovaif7facf92009-10-23 21:01:49 +0000917<SPAN class="stylepoint_section">Definition: </SPAN>
918 Current versions of Python provide alternative constructs
919 that people find generally preferable.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000920 </P>
921 <P class="">
mmentovaif7facf92009-10-23 21:01:49 +0000922<SPAN class="stylepoint_section">Decision: </SPAN>
923 We do not use any Python version which does not support
924 these features, so there is no reason not to use the new
925 styles.
mmentovai9ec7bd62009-12-03 22:25:38 +0000926<DIV class=""><PRE class="badcode">No: <span class="external"></span>words = string.split(foo, ':')
mmentovaif7facf92009-10-23 21:01:49 +0000927
928 <span class="external"></span>map(lambda x: x[1], filter(lambda x: x[2] == 5, my_list))
929
mmentovai9ec7bd62009-12-03 22:25:38 +0000930 <span class="external"></span>apply(fn, args, kwargs)</PRE></DIV>
931<DIV class=""><PRE>Yes: <span class="external"></span>words = foo.split(':')
mmentovaif7facf92009-10-23 21:01:49 +0000932
933 <span class="external"></span>[x[1] for x in my_list if x[2] == 5]
934
mmentovai9ec7bd62009-12-03 22:25:38 +0000935 <span class="external"></span>fn(*args, **kwargs)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000936 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000937 </DIV></DIV>
938 </DIV>
939 <DIV class="">
940<H3><A name="Lexical_Scoping" id="Lexical_Scoping">Lexical Scoping</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000941<SPAN class="link_button" id="link-Lexical_Scoping__button" name="link-Lexical_Scoping__button"><A href="?showone=Lexical_Scoping#Lexical_Scoping">
942 link
943 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Lexical_Scoping__body','Lexical_Scoping__button')" name="Lexical_Scoping__button" id="Lexical_Scoping__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000944 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000945 Okay to use.
mmentovai9ec7bd62009-12-03 22:25:38 +0000946 </DIV>
947 <DIV class=""><DIV class="stylepoint_body" name="Lexical_Scoping__body" id="Lexical_Scoping__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000948 <P class="">
949<SPAN class="stylepoint_section">Definition: </SPAN>
950 A nested Python function can refer to variables defined in
951 enclosing functions, but can not assign to them. Variable
952 bindings are resolved using lexical scoping, that is, based on
953 the static program text. Any assignment to a name in a block
954 will cause Python to treat all references to that name as a
955 local variable, even if the use precedes the assignment. If a
956 global declaration occurs, the name is treated as a global
957 variable.
958
959 <p>
960 An example of the use of this feature is:
961 </p>
962
mmentovai9ec7bd62009-12-03 22:25:38 +0000963 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000964<span class="external"></span>def get_adder(summand1):
965 <span class="external"> </span>"""Returns a function that adds numbers to a given number."""
966 <span class="external"> </span>def adder(summand2):
967 <span class="external"> </span>return summand1 + summand2
968
969 <span class="external"> </span>return adder
970<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000971</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000972 </P>
973 <P class="">
974<SPAN class="stylepoint_section">Pros: </SPAN>
975 Often results in clearer, more elegant code. Especially comforting
976 to experienced Lisp and Scheme (and Haskell and ML and …)
977 programmers.
978 </P>
979 <P class="">
980<SPAN class="stylepoint_section">Cons: </SPAN>
981 Can lead to confusing bugs. Such as this example based on
982 <a HREF="http://www.python.org/dev/peps/pep-0227/">PEP-0227</a>:
mmentovai9ec7bd62009-12-03 22:25:38 +0000983<DIV class=""><PRE class="badcode">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000984<span class="external"></span>i = 4
985<span class="external"></span>def foo(x):
986 <span class="external"> </span>def bar():
987 <span class="external"> </span>print i,
988 <span class="external"> </span># ...
989 <span class="external"> </span># A bunch of code here
990 <span class="external"> </span># ...
991 <span class="external"> </span>for i in x: # Ah, i *is* local to Foo, so this is what Bar sees
992 <span class="external"> </span>print i,
mmentovai9ec7bd62009-12-03 22:25:38 +0000993 <span class="external"> </span>bar()</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000994 <p>
995 So <code>foo([1, 2, 3])</code> will print <code>1 2 3 3</code>, not
996 <code>1 2 3 4</code>.
997 </p>
998 </P>
999 <P class="">
1000<SPAN class="stylepoint_section">Decision: </SPAN>
1001 Okay to use.
1002 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001003 </DIV></DIV>
1004 </DIV>
1005 <DIV class="">
1006<H3><A name="Function_and_Method_Decorators" id="Function_and_Method_Decorators">Function and Method Decorators</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001007<SPAN class="link_button" id="link-Function_and_Method_Decorators__button" name="link-Function_and_Method_Decorators__button"><A href="?showone=Function_and_Method_Decorators#Function_and_Method_Decorators">
1008 link
1009 </A></SPAN><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>
mmentovai9ec7bd62009-12-03 22:25:38 +00001010 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001011 Use decorators judiciously when there is a clear advantage.
mmentovai9ec7bd62009-12-03 22:25:38 +00001012 </DIV>
1013 <DIV class=""><DIV class="stylepoint_body" name="Function_and_Method_Decorators__body" id="Function_and_Method_Decorators__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001014 <P class="">
1015<SPAN class="stylepoint_section">Definition: </SPAN>
1016
1017 <a HREF="http://www.python.org/doc/2.4.3/whatsnew/node6.html">Decorators
1018 for Functions and Methods</a>
1019 (a.k.a "the <code>@</code> notation").
1020 The most common decorators are <code>@classmethod</code> and
1021 <code>@staticmethod</code>, for converting ordinary methods to class or
1022 static methods. However, the decorator syntax allows for
1023 user-defined decorators as well. Specifically, for some function
1024 <code>my_decorator</code>, this:
mmentovai9ec7bd62009-12-03 22:25:38 +00001025 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001026<span class="external"></span>class C(object):
1027 <span class="external"> </span>@my_decorator
1028 <span class="external"> </span>def method(self):
1029 <span class="external"> </span># method body ...
1030<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001031</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001032
1033 is equivalent to:
mmentovai9ec7bd62009-12-03 22:25:38 +00001034 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001035<span class="external"></span>class C(object):
1036 <span class="external"> </span>def method(self):
1037 <span class="external"> </span># method body ...
1038 <span class="external"> </span>method = my_decorator(method)
1039<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001040</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001041 </P>
1042 <P class="">
1043<SPAN class="stylepoint_section">Pros: </SPAN> Elegantly specifies some transformation on a method; the
1044 transformation might eliminate some repetitive code, enforce invariants,
1045 etc.
1046 </P>
1047 <P class="">
1048<SPAN class="stylepoint_section">Cons: </SPAN> Decorators can perform arbitrary operations on a
1049 function's arguments or return values, resulting in surprising
1050 implicit behavior.
1051 Additionally, decorators execute at import time. Failures in decorator
1052 code are pretty much impossible to recover from.
1053 </P>
1054 <P class="">
1055<SPAN class="stylepoint_section">Decision: </SPAN> Use decorators judiciously when there is a clear
1056 advantage. Decorators should follow the same import and naming
1057 guidelines as functions. Decorator pydoc should clearly state that the
1058 function is a decorator. Write unit tests for decorators.
1059
1060 <p>
1061 Avoid external dependencies in the decorator itself (e.g. don't rely on
1062 files, sockets, database connections, etc.), since they might not be
1063 available when the decorator runs (at import time, perhaps from
1064 <code>pychecker</code> or other tools). A decorator that is
1065 called with valid parameters should (as much as possible) be guaranteed
1066 to succeed in all cases.
1067 </p>
1068 <p>
1069 Decorators are a special case of "top level code" - see
1070 <a HREF="#Main">main</a> for more discussion.
1071 </p>
1072 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001073 </DIV></DIV>
1074 </DIV>
1075 <DIV class="">
1076<H3><A name="Threading" id="Threading">Threading</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001077<SPAN class="link_button" id="link-Threading__button" name="link-Threading__button"><A href="?showone=Threading#Threading">
1078 link
1079 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Threading__body','Threading__button')" name="Threading__button" id="Threading__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001080 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001081 Do not rely on the atomicity of built-in types.
mmentovai9ec7bd62009-12-03 22:25:38 +00001082 </DIV>
1083 <DIV class=""><DIV class="stylepoint_body" name="Threading__body" id="Threading__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001084 <p>
1085 While Python's built-in data types such as dictionaries appear
1086 to have atomic operations, there are corner cases where they
1087 aren't atomic (e.g. if <code>__hash__</code> or
1088 <code>__eq__</code> are implemented as Python methods) and their
1089 atomicity should not be relied upon. Neither should you rely on
1090 atomic variable assignment (since this in turn depends on
1091 dictionaries).
1092 </p>
1093
1094 <p>
1095 Use the Queue module's <code>Queue</code> data type as the preferred
1096 way to
1097 communicate data between threads. Otherwise, use the threading
1098 module and its locking primitives. Learn about the proper use
1099 of condition variables so you can use
1100 <code>threading.Condition</code> instead of using lower-level
1101 locks.
1102 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001103 </DIV></DIV>
1104 </DIV>
1105 <DIV class="">
1106<H3><A name="Power_Features" id="Power_Features">Power Features</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001107<SPAN class="link_button" id="link-Power_Features__button" name="link-Power_Features__button"><A href="?showone=Power_Features#Power_Features">
1108 link
1109 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Power_Features__body','Power_Features__button')" name="Power_Features__button" id="Power_Features__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001110 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001111 Avoid these features.
mmentovai9ec7bd62009-12-03 22:25:38 +00001112 </DIV>
1113 <DIV class=""><DIV class="stylepoint_body" name="Power_Features__body" id="Power_Features__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001114 <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>
mmentovai9ec7bd62009-12-03 22:25:38 +00001138 </DIV></DIV>
1139 </DIV>
1140 </DIV>
1141 <DIV class="">
1142<H2 name="Python_Style_Rules" id="Python_Style_Rules">Python Style Rules</H2>
1143 <DIV class="">
1144<H3><A name="Semicolons" id="Semicolons">Semicolons</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001145<SPAN class="link_button" id="link-Semicolons__button" name="link-Semicolons__button"><A href="?showone=Semicolons#Semicolons">
1146 link
1147 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Semicolons__body','Semicolons__button')" name="Semicolons__button" id="Semicolons__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001148 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001149 Do not terminate your lines with semi-colons and do not use
1150 semi-colons to put two commands on the same line.
mmentovai9ec7bd62009-12-03 22:25:38 +00001151 </DIV>
1152 <DIV class=""><DIV class="stylepoint_body" name="Semicolons__body" id="Semicolons__body" style="display: none">
mmentovai9ec7bd62009-12-03 22:25:38 +00001153 </DIV></DIV>
1154 </DIV>
1155 <DIV class="">
1156<H3><A name="Line_length" id="Line_length">Line length</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001157<SPAN class="link_button" id="link-Line_length__button" name="link-Line_length__button"><A href="?showone=Line_length#Line_length">
1158 link
1159 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Line_length__body','Line_length__button')" name="Line_length__button" id="Line_length__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001160 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001161 Maximum line length is <em>80 characters</em>.
mmentovai9ec7bd62009-12-03 22:25:38 +00001162 </DIV>
1163 <DIV class=""><DIV class="stylepoint_body" name="Line_length__body" id="Line_length__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001164 <p>
1165 Exception: lines importing modules may end up longer than 80
1166 characters only if using Python 2.4 or
1167 earlier.
1168 </p>
1169
1170 <p>
1171 Make use of Python's
1172
1173 <a HREF="http://www.python.org/doc/ref/implicit-joining.html">implicit
1174 line joining inside parentheses, brackets and braces</a>.
1175 If necessary, you can add an extra pair of parentheses around an
1176 expression.
1177 </p>
1178
1179
mmentovai9ec7bd62009-12-03 22:25:38 +00001180 <DIV class=""><PRE>Yes: foo_bar(self, width, height, color='black', design=None, x='foo',
apicard@google.comf900c2c2009-07-23 20:09:56 +00001181 emphasis=None, highlight=0)
1182
1183 if (width == 0 and height == 0 and
mmentovai9ec7bd62009-12-03 22:25:38 +00001184 color == 'red' and emphasis == 'strong'):</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001185
1186
1187 <p>
1188 When a literal string won't fit on a single line, use parentheses for
1189 implicit line joining.
1190 </p>
1191
mmentovai9ec7bd62009-12-03 22:25:38 +00001192 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001193<span class="external"></span>x = ('This will build a very long long '
mmentovai9ec7bd62009-12-03 22:25:38 +00001194<span class="external"></span> 'long long long long long long string')</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001195
1196 <p>
1197 Make note of the indentation of the elements in the line
1198 continuation examples above; see the
1199 <a HREF="#indentation">indentation</a>
1200 section for explanation.
1201 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001202 </DIV></DIV>
1203 </DIV>
1204 <DIV class="">
1205<H3><A name="Parentheses" id="Parentheses">Parentheses</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001206<SPAN class="link_button" id="link-Parentheses__button" name="link-Parentheses__button"><A href="?showone=Parentheses#Parentheses">
1207 link
1208 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Parentheses__body','Parentheses__button')" name="Parentheses__button" id="Parentheses__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001209 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001210 Use parentheses sparingly.
mmentovai9ec7bd62009-12-03 22:25:38 +00001211 </DIV>
1212 <DIV class=""><DIV class="stylepoint_body" name="Parentheses__body" id="Parentheses__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001213 <p>
1214 Do not use them in return statements or conditional statements unless
1215 using parentheses for implied line continuation. (See above.)
1216 It is however fine to use parentheses around tuples.
1217 </p>
1218
mmentovai9ec7bd62009-12-03 22:25:38 +00001219<DIV class=""><PRE>Yes: <span class="external"></span>if foo:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001220 <span class="external"> </span>bar()
1221 <span class="external"></span>while x:
1222 <span class="external"> </span>x = bar()
1223 <span class="external"></span>if x and y:
1224 <span class="external"> </span>bar()
1225 <span class="external"></span>if not x:
1226 <span class="external"> </span>bar()
1227 <span class="external"></span>return foo
mmentovai9ec7bd62009-12-03 22:25:38 +00001228 <span class="external"></span>for (x, y) in dict.items(): ...</PRE></DIV>
1229<DIV class=""><PRE class="badcode">No: <span class="external"></span>if (x):
apicard@google.comf900c2c2009-07-23 20:09:56 +00001230 <span class="external"> </span>bar()
1231 <span class="external"></span>if not(x):
1232 <span class="external"> </span>bar()
mmentovai9ec7bd62009-12-03 22:25:38 +00001233 <span class="external"></span>return (foo)</PRE></DIV>
1234 </DIV></DIV>
1235 </DIV>
1236 <DIV class="">
1237<H3><A name="Indentation" id="Indentation">Indentation</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001238<SPAN class="link_button" id="link-Indentation__button" name="link-Indentation__button"><A href="?showone=Indentation#Indentation">
1239 link
1240 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Indentation__body','Indentation__button')" name="Indentation__button" id="Indentation__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001241 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001242 Indent your code blocks with <em>4 spaces</em>.
mmentovai9ec7bd62009-12-03 22:25:38 +00001243 </DIV>
1244 <DIV class=""><DIV class="stylepoint_body" name="Indentation__body" id="Indentation__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001245 <p>
1246 Never use tabs or mix tabs and spaces.
1247 In cases of implied line continuation, you should align wrapped elements
1248 either vertically, as per the examples in the
1249 <a HREF="#Line_length">line length</a> section; or using a hanging
1250 indent of 4 spaces, in which case there should be no argument on
1251 the first line.
1252 </p>
1253
1254
mmentovai9ec7bd62009-12-03 22:25:38 +00001255<DIV class=""><PRE>Yes: # Aligned with opening delimiter
apicard@google.comf900c2c2009-07-23 20:09:56 +00001256 foo = long_function_name(var_one, var_two,
1257 var_three, var_four)
1258
1259 # 4-space hanging indent; nothing on first line
1260 foo = long_function_name(
1261 var_one, var_two, var_three,
mmentovai9ec7bd62009-12-03 22:25:38 +00001262 var_four)</PRE></DIV>
1263<DIV class=""><PRE class="badcode">No: <span class="external"></span># Stuff on first line forbidden
apicard@google.comf900c2c2009-07-23 20:09:56 +00001264 <span class="external"></span>foo = long_function_name(var_one, var_two,
1265 <span class="external"></span> var_three, var_four)
1266
1267 <span class="external"></span># 2-space hanging indent forbidden
1268 <span class="external"></span>foo = long_function_name(
1269 <span class="external"></span> var_one, var_two, var_three,
mmentovai9ec7bd62009-12-03 22:25:38 +00001270 <span class="external"></span> var_four)</PRE></DIV>
1271 </DIV></DIV>
1272 </DIV>
1273 <DIV class="">
1274<H3><A name="Blank_Lines" id="Blank_Lines">Blank Lines</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001275<SPAN class="link_button" id="link-Blank_Lines__button" name="link-Blank_Lines__button"><A href="?showone=Blank_Lines#Blank_Lines">
1276 link
1277 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Blank_Lines__body','Blank_Lines__button')" name="Blank_Lines__button" id="Blank_Lines__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001278 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001279 Two blank lines between top-level definitions, one blank line
1280 between method definitions.
mmentovai9ec7bd62009-12-03 22:25:38 +00001281 </DIV>
1282 <DIV class=""><DIV class="stylepoint_body" name="Blank_Lines__body" id="Blank_Lines__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001283 <p>
1284 Two blank lines between top-level definitions, be they function
1285 or class definitions. One blank line between method definitions
1286 and between the <code>class</code> line and the first method.
1287 Use single blank lines as you judge appropriate within functions or
1288 methods.
1289 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001290 </DIV></DIV>
1291 </DIV>
1292 <DIV class="">
1293<H3><A name="Whitespace" id="Whitespace">Whitespace</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001294<SPAN class="link_button" id="link-Whitespace__button" name="link-Whitespace__button"><A href="?showone=Whitespace#Whitespace">
1295 link
1296 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Whitespace__body','Whitespace__button')" name="Whitespace__button" id="Whitespace__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001297 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001298 Follow standard typographic rules for the use of spaces around
1299 punctuation.
mmentovai9ec7bd62009-12-03 22:25:38 +00001300 </DIV>
1301 <DIV class=""><DIV class="stylepoint_body" name="Whitespace__body" id="Whitespace__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001302 <p>
1303 No whitespace inside parentheses, brackets or braces.
1304 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001305<DIV class=""><PRE>Yes: <span class="external"></span>spam(ham[1], {eggs: 2}, [])</PRE></DIV>
1306<DIV class=""><PRE class="badcode">No: <span class="external"></span>spam( ham[ 1 ], { eggs: 2 }, [ ] )</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001307 <p>
1308 No whitespace before a comma, semicolon, or colon. Do use
1309 whitespace after a comma, semicolon, or colon except at the end
1310 of the line.
1311 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001312<DIV class=""><PRE>Yes: <span class="external"></span>if x == 4:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001313 <span class="external"> </span>print x, y
mmentovai9ec7bd62009-12-03 22:25:38 +00001314 <span class="external"></span>x, y = y, x</PRE></DIV>
1315<DIV class=""><PRE class="badcode">No: <span class="external"></span>if x == 4 :
apicard@google.comf900c2c2009-07-23 20:09:56 +00001316 <span class="external"> </span>print x , y
mmentovai9ec7bd62009-12-03 22:25:38 +00001317 <span class="external"></span>x , y = y , x</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001318 <p>
1319 No whitespace before the open paren/bracket that starts an argument list,
1320 indexing or slicing.
1321 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001322 <DIV class=""><PRE>Yes: <span class="external"></span>spam(1)</PRE></DIV>
1323<DIV class=""><PRE class="badcode">No: <span class="external"></span>spam (1)</PRE></DIV>
1324<DIV class=""><PRE>Yes: <span class="external"></span>dict['key'] = list[index]</PRE></DIV>
1325<DIV class=""><PRE class="badcode">No: <span class="external"></span>dict ['key'] = list [index]</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001326
1327 <p>
1328 Surround binary operators with a single space on either side for
1329 assignment (<code>=</code>), comparisons (<code>==, &lt;, &gt;, !=,
1330 &lt;&gt;, &lt;=, &gt;=, in, not in, is, is not</code>), and Booleans
1331 (<code>and, or, not</code>). Use your better judgment for the
1332 insertion of spaces around arithmetic operators but always be
1333 consistent about whitespace on either side of a binary operator.
1334 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001335<DIV class=""><PRE>Yes: <span class="external"></span>x == 1</PRE></DIV>
1336<DIV class=""><PRE class="badcode">No: <span class="external"></span>x&lt;1</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001337 <p>
1338 Don't use spaces around the '=' sign when used to indicate a
1339 keyword argument or a default parameter value.
1340 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001341<DIV class=""><PRE>Yes: <span class="external"></span>def complex(real, imag=0.0): return magic(r=real, i=imag)</PRE></DIV>
1342<DIV class=""><PRE class="badcode">No: <span class="external"></span>def complex(real, imag = 0.0): return magic(r = real, i = imag)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001343
1344 <p>
1345 Don't use spaces to vertically align tokens on consecutive lines, since it
1346 becomes a maintenance burden (applies to <code>:</code>, <code>#</code>,
1347 <code>=</code>, etc.):
1348 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001349<DIV class=""><PRE>Yes:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001350 foo = 1000 # comment
1351 long_name = 2 # comment that should not be aligned
1352
1353 dictionary = {
1354 "foo": 1,
1355 "long_name": 2,
mmentovai9ec7bd62009-12-03 22:25:38 +00001356 }</PRE></DIV>
1357<DIV class=""><PRE class="badcode">No:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001358 foo = 1000 # comment
1359 long_name = 2 # comment that should not be aligned
1360
1361 dictionary = {
1362 "foo" : 1,
1363 "long_name": 2,
mmentovai9ec7bd62009-12-03 22:25:38 +00001364 }</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001365
1366
mmentovai9ec7bd62009-12-03 22:25:38 +00001367 </DIV></DIV>
1368 </DIV>
1369 <DIV class="">
1370<H3><A name="Python_Interpreter" id="Python_Interpreter">Python Interpreter</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001371<SPAN class="link_button" id="link-Python_Interpreter__button" name="link-Python_Interpreter__button"><A href="?showone=Python_Interpreter#Python_Interpreter">
1372 link
1373 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Python_Interpreter__body','Python_Interpreter__button')" name="Python_Interpreter__button" id="Python_Interpreter__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001374 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001375 Modules should begin with
1376
1377 <code>#!/usr/bin/env python&lt;version&gt;</code>
mmentovai9ec7bd62009-12-03 22:25:38 +00001378 </DIV>
1379 <DIV class=""><DIV class="stylepoint_body" name="Python_Interpreter__body" id="Python_Interpreter__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001380 <p>
1381 Modules should begin with a "shebang" line specifying the Python
1382 interpreter used to execute the program:
1383 </p>
1384
mmentovai9ec7bd62009-12-03 22:25:38 +00001385<DIV class=""><PRE>
1386<span class="external"></span>#!/usr/bin/env python2.4</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001387
1388 <p>
1389 Always use the most specific version you can use, e.g.,
1390 <code>/usr/bin/python2.4</code>, not
1391 <code>/usr/bin/python2</code>. This makes it easier to find
1392 dependencies when
1393
1394 upgrading to a different Python version
1395 and also avoids confusion and breakage during use. E.g., Does
1396 <code>/usr/bin/python2</code> mean Python 2.0.1 or Python
1397 2.3.0?
1398 </p>
1399
mmentovai9ec7bd62009-12-03 22:25:38 +00001400 </DIV></DIV>
1401 </DIV>
1402 <DIV class="">
1403<H3><A name="Comments" id="Comments">Comments</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001404<SPAN class="link_button" id="link-Comments__button" name="link-Comments__button"><A href="?showone=Comments#Comments">
1405 link
1406 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Comments__body','Comments__button')" name="Comments__button" id="Comments__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001407 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001408 Be sure to use the right style for module, function, method and in-line
1409 comments.
mmentovai9ec7bd62009-12-03 22:25:38 +00001410 </DIV>
1411 <DIV class=""><DIV class="stylepoint_body" name="Comments__body" id="Comments__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001412
1413 <P class="">
1414<SPAN class="stylepoint_subsection">Doc Strings</SPAN>
1415
1416 <p>
1417 Python has a unique commenting style using doc strings. A doc
1418 string is a string that is the first statement in a package,
1419 module, class or function. These strings can be extracted
1420 automatically through the <code>__doc__</code> member of the
1421 object and are used by <code>pydoc</code>. (Try running
1422 <code>pydoc</code> on your module to see how it looks.) Our
1423 convention for doc strings is to use the three double-quote
1424 format for strings. A doc string should be organized as a
1425 summary line (one physical line) terminated by a period,
1426 question mark, or exclamation point, followed by a blank line,
1427 followed by the rest of the doc string starting at the same
1428 cursor position as the first quote of the first line. There are
1429 more formatting guidelines for doc strings below.
1430 </p>
1431
1432 </P>
1433 <P class="">
1434<SPAN class="stylepoint_subsection">Modules</SPAN>
1435
1436
1437
1438 <p>
1439 Every file should contain the following items, in order:
1440 <ul>
1441 <li>a copyright statement (for example,
1442 <code>Copyright 2008 Google Inc.</code>)</li>
1443 <li>a license boilerplate. Choose the appropriate boilerplate
1444 for the license used by the project (for example, Apache 2.0, BSD,
1445 LGPL, GPL)</li>
1446 <li>an author line to identify the original author of the file</li>
1447 </ul>
1448 </p>
1449 </P>
1450 <P class="">
1451<SPAN class="stylepoint_subsection">Functions and Methods</SPAN>
1452
1453 <p>
1454 Any function or method which is not both obvious and very short
1455 needs a doc string. Additionally, any externally accessible
1456 function or method regardless of length or simplicity needs a
1457 doc string. The doc string should include what the function does
1458 and have detailed descriptions of the input and output. It
1459 should not, generally, describe how it does it unless it's some
1460 complicated algorithm. For tricky code block/inline comments
1461 within the code are more appropriate. The doc string should give
1462 enough information to write a call to the function without
1463 looking at a single line of the function's code. Args should be
1464 individually documented, an explanation following after a colon,
1465 and should use a uniform hanging indent of 2 or 4 spaces. The
1466 doc string should specify the expected types where specific types
1467 are required. A "Raises:" section should list all exceptions
1468 that can be raised by the function. The doc string for generator
1469 functions should use "Yields:" rather than "Returns:".
1470 </p>
1471
mmentovai9ec7bd62009-12-03 22:25:38 +00001472 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001473<span class="external"></span>def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
1474 <span class="external"> </span>"""Fetches rows from a Bigtable.
1475
1476 <span class="external"> </span>Retrieves rows pertaining to the given keys from the Table instance
1477 <span class="external"> </span>represented by big_table. Silly things may happen if
1478 <span class="external"> </span>other_silly_variable is not None.
1479
1480 <span class="external"> </span>Args:
1481 <span class="external"> </span>big_table: An open Bigtable Table instance.
1482 <span class="external"> </span>keys: A sequence of strings representing the key of each table row
1483 <span class="external"> </span> to fetch.
1484 <span class="external"> </span>other_silly_variable: Another optional variable, that has a much
1485 <span class="external"> </span> longer name than the other args, and which does nothing.
1486
1487 <span class="external"> </span>Returns:
1488 <span class="external"> </span>A dict mapping keys to the corresponding table row data
1489 <span class="external"> </span>fetched. Each row is represented as a tuple of strings. For
1490 <span class="external"> </span>example:
1491
1492 <span class="external"> </span>{'Serak': ('Rigel VII', 'Preparer'),
1493 <span class="external"> </span> 'Zim': ('Irk', 'Invader'),
1494 <span class="external"> </span> 'Lrrr': ('Omicron Persei 8', 'Emperor')}
1495
1496 <span class="external"> </span>If a key from the keys argument is missing from the dictionary,
1497 <span class="external"> </span>then that row was not found in the table.
1498
1499 <span class="external"> </span>Raises:
1500 <span class="external"> </span>IOError: An error occurred accessing the bigtable.Table object.
1501 <span class="external"> </span>"""
1502 <span class="external"> </span>pass
1503<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001504</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001505 </P>
1506 <P class="">
1507<SPAN class="stylepoint_subsection">Classes</SPAN>
1508
1509 <p>
1510 Classes should have a doc string below the class definition describing
1511 the class. If your class has public attributes, they should be documented
1512 here in an Attributes section and follow the same formatting as a
1513 function's Args section.
1514 </p>
1515
mmentovai9ec7bd62009-12-03 22:25:38 +00001516 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001517<span class="external"></span>class SampleClass(object):
1518 <span class="external"> </span>"""Summary of class here.
1519
1520 <span class="external"> </span>Longer class information....
1521 <span class="external"> </span>Longer class information....
1522
1523 <span class="external"> </span>Attributes:
1524 <span class="external"> </span>likes_spam: A boolean indicating if we like SPAM or not.
1525 <span class="external"> </span>eggs: An integer count of the eggs we have laid.
1526 <span class="external"> </span>"""
1527
1528 <span class="external"> </span>def __init__(self, likes_spam=False):
1529 <span class="external"> </span>"""Inits SampleClass with blah."""
1530 <span class="external"> </span>self.likes_spam = likes_spam
1531 <span class="external"> </span>self.eggs = 0
1532
1533 <span class="external"> </span>def public_method(self):
1534 <span class="external"> </span>"""Performs operation blah."""
1535<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001536</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001537
1538 </P>
1539 <P class="">
1540<SPAN class="stylepoint_subsection">Block and Inline Comments</SPAN>
1541
1542 <p>
1543 The final place to have comments is in tricky parts of the
1544 code. If you're going to have to explain it at the next
1545 <a HREF="http://en.wikipedia.org/wiki/Code_review">code review</a>,
1546 you should comment it now. Complicated operations get a few lines of
1547 comments before the operations
1548 commence. Non-obvious ones get comments at the end of the line.
1549 </p>
1550
mmentovai9ec7bd62009-12-03 22:25:38 +00001551 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001552<span class="external"></span># We use a weighted dictionary search to find out where i is in
1553<span class="external"></span># the array. We extrapolate position based on the largest num
1554<span class="external"></span># in the array and the array size and then do binary search to
1555<span class="external"></span># get the exact number.
1556
1557<span class="external"></span>if i &amp; (i-1) == 0: # true iff i is a power of 2
1558<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001559</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001560
1561 <p>
1562 To improve legibility, these comments should be at least 2 spaces away
1563 from the code.
1564 </p>
1565
1566 <p>
1567 On the other hand, never describe the code. Assume the person
1568 reading the code knows Python (though not what you're trying to
1569 do) better than you do.
1570 </p>
1571
mmentovai9ec7bd62009-12-03 22:25:38 +00001572 <DIV class=""><PRE class="badcode">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001573<span class="external"></span># BAD COMMENT: Now go through the b array and make sure whenever i occurs
1574<span class="external"></span># the next element is i+1
1575<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001576</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001577
1578 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001579 </DIV></DIV>
1580 </DIV>
1581 <DIV class="">
1582<H3><A name="Classes" id="Classes">Classes</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001583<SPAN class="link_button" id="link-Classes__button" name="link-Classes__button"><A href="?showone=Classes#Classes">
1584 link
1585 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Classes__body','Classes__button')" name="Classes__button" id="Classes__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001586 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001587 If a class inherits from no other base classes, explicitly inherit
1588 from <code>object</code>. This also applies to nested classes.
mmentovai9ec7bd62009-12-03 22:25:38 +00001589 </DIV>
1590 <DIV class=""><DIV class="stylepoint_body" name="Classes__body" id="Classes__body" style="display: none">
mmentovai9ec7bd62009-12-03 22:25:38 +00001591 <DIV class=""><PRE class="badcode">No: <span class="external"></span>class SampleClass:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001592 <span class="external"> </span>pass
1593
1594
1595 <span class="external"></span>class OuterClass:
1596
1597 <span class="external"> </span>class InnerClass:
1598 <span class="external"> </span>pass
1599<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001600</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001601
mmentovai9ec7bd62009-12-03 22:25:38 +00001602 <DIV class=""><PRE>Yes: <span class="external"></span>class SampleClass(object):
apicard@google.comf900c2c2009-07-23 20:09:56 +00001603 <span class="external"> </span>pass
1604
1605
1606 <span class="external"></span>class OuterClass(object):
1607
1608 <span class="external"> </span>class InnerClass(object):
1609 <span class="external"> </span>pass
1610
1611
1612 <span class="external"></span>class ChildClass(ParentClass):
1613 <span class="external"> </span>"""Explicitly inherits from another class already."""
1614<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001615</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001616
1617 <p>Inheriting from <code>object</code> is needed to make properties work
1618 properly, and it will protect your code from one particular potential
1619 incompatibility with Python 3000. It also defines
1620 special methods that implement the default semantics of objects including
1621 <code>__new__</code>, <code>__init__</code>, <code>__delattr__</code>,
1622 <code>__getattribute__</code>, <code>__setattr__</code>,
1623 <code>__hash__</code>, <code>__repr__</code>, and <code>__str__</code>.
1624 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001625 </DIV></DIV>
1626 </DIV>
1627 <DIV class="">
1628<H3><A name="Strings" id="Strings">Strings</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001629<SPAN class="link_button" id="link-Strings__button" name="link-Strings__button"><A href="?showone=Strings#Strings">
1630 link
1631 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Strings__body','Strings__button')" name="Strings__button" id="Strings__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001632 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001633 Use the <code>%</code> operator for formatting strings,
1634 even when the parameters are all strings. Use your best judgement
1635 to decide between <code>+</code> and <code>%</code> though.
mmentovai9ec7bd62009-12-03 22:25:38 +00001636 </DIV>
1637 <DIV class=""><DIV class="stylepoint_body" name="Strings__body" id="Strings__body" style="display: none">
mmentovai9ec7bd62009-12-03 22:25:38 +00001638<DIV class=""><PRE class="badcode">No: <span class="external"></span>x = '%s%s' % (a, b) # use + in this case
apicard@google.comf900c2c2009-07-23 20:09:56 +00001639 <span class="external"></span>x = imperative + ', ' + expletive + '!'
mmentovai9ec7bd62009-12-03 22:25:38 +00001640 <span class="external"></span>x = 'name: ' + name + '; score: ' + str(n)</PRE></DIV>
1641<DIV class=""><PRE>Yes: <span class="external"></span>x = a + b
apicard@google.comf900c2c2009-07-23 20:09:56 +00001642 <span class="external"></span>x = '%s, %s!' % (imperative, expletive)
mmentovai9ec7bd62009-12-03 22:25:38 +00001643 <span class="external"></span>x = 'name: %s; score: %d' % (name, n)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001644
1645 <p>
1646 Avoid using the <code>+</code> and <code>+=</code> operators to
1647 accumulate a string within a loop. Since strings are immutable, this
1648 creates unnecessary temporary objects and results in quadratic rather
1649 than linear running time. Instead, add each substring to a list and
1650 <code>''.join</code> the list after the loop terminates (or, write each
1651 substring to a <code>cStringIO.StringIO</code> buffer).
1652 </p>
1653
mmentovai9ec7bd62009-12-03 22:25:38 +00001654<DIV class=""><PRE class="badcode">No: <span class="external"></span>employee_table = '&lt;table&gt;'
apicard@google.comf900c2c2009-07-23 20:09:56 +00001655 <span class="external"></span>for last_name, first_name in employee_list:
1656 <span class="external"> </span>employee_table += '&lt;tr&gt;&lt;td&gt;%s, %s&lt;/td&gt;&lt;/tr&gt;' % (last_name, first_name)
mmentovai9ec7bd62009-12-03 22:25:38 +00001657 <span class="external"></span>employee_table += '&lt;/table&gt;'</PRE></DIV>
1658<DIV class=""><PRE>Yes: <span class="external"></span>items = ['&lt;table&gt;']
apicard@google.comf900c2c2009-07-23 20:09:56 +00001659 <span class="external"></span>for last_name, first_name in employee_list:
1660 <span class="external"> </span>items.append('&lt;tr&gt;&lt;td&gt;%s, %s&lt;/td&gt;&lt;/tr&gt;' % (last_name, first_name))
1661 <span class="external"></span>items.append('&lt;/table&gt;')
mmentovai9ec7bd62009-12-03 22:25:38 +00001662 <span class="external"></span>employee_table = ''.join(items)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001663
1664 <p>
1665 Use <code>"""</code> for multi-line strings rather than
1666 <code>'''</code>. Note, however, that it is often cleaner to
1667 use implicit line joining since multi-line strings do
1668 not flow with the indentation of the rest of the program:
1669 </p>
1670
mmentovai9ec7bd62009-12-03 22:25:38 +00001671 <DIV class=""><PRE class="badcode"> No<span class="external"></span>:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001672 <span class="external"></span>print """This is pretty ugly.
1673Don'<span class="external"></span>t do this.
1674"""<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001675</PRE></DIV>
1676<DIV class=""><PRE>Ye<span class="external"></span>s:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001677 <span class="external"></span>print ("This is much nicer.\n"
mmentovai9ec7bd62009-12-03 22:25:38 +00001678 <span class="external"></span> "Do it this way.\n")</PRE></DIV>
1679 </DIV></DIV>
1680 </DIV>
1681 <DIV class="">
1682<H3><A name="TODO_Comments" id="TODO_Comments">TODO Comments</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001683<SPAN class="link_button" id="link-TODO_Comments__button" name="link-TODO_Comments__button"><A href="?showone=TODO_Comments#TODO_Comments">
1684 link
1685 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('TODO_Comments__body','TODO_Comments__button')" name="TODO_Comments__button" id="TODO_Comments__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001686 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001687 Use <code>TODO</code> comments for code that is temporary, a
1688 short-term solution, or good-enough but not perfect.
mmentovai9ec7bd62009-12-03 22:25:38 +00001689 </DIV>
1690 <DIV class=""><DIV class="stylepoint_body" name="TODO_Comments__body" id="TODO_Comments__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001691 <p>
1692 <code>TODO</code>s should include the string <code>TODO</code> in
1693 all caps, followed by your
1694
1695 name, e-mail address, or other
1696 identifier
1697 in parentheses. A colon is optional. A comment explaining what there
1698 is to do is required. The main purpose is to have
1699 a consistent <code>TODO</code> format searchable by the person
1700 adding the comment (who can provide more details upon request). A
1701 <code>TODO</code> is not a commitment to provide the fix yourself.
1702 </p>
1703
mmentovai9ec7bd62009-12-03 22:25:38 +00001704 <DIV class=""><PRE># TODO(kl@gmail.com): Drop the use of "has_key".
1705# TODO(Zeke) change this to use relations.</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001706 <p>
1707 If your <code>TODO</code> is of the form "At a future date do
1708 something" make sure that you either include a very specific
1709 date ("Fix by November 2009") or a very specific event
1710 ("Remove this code when all clients can handle XML responses.").
1711 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001712 </DIV></DIV>
1713 </DIV>
1714 <DIV class="">
1715<H3><A name="Imports_formatting" id="Imports_formatting">Imports formatting</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001716<SPAN class="link_button" id="link-Imports_formatting__button" name="link-Imports_formatting__button"><A href="?showone=Imports_formatting#Imports_formatting">
1717 link
1718 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Imports_formatting__body','Imports_formatting__button')" name="Imports_formatting__button" id="Imports_formatting__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001719 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001720 Imports should be on separate lines.
mmentovai9ec7bd62009-12-03 22:25:38 +00001721 </DIV>
1722 <DIV class=""><DIV class="stylepoint_body" name="Imports_formatting__body" id="Imports_formatting__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001723 <p>
1724 E.g.:
1725 </p>
1726
mmentovai9ec7bd62009-12-03 22:25:38 +00001727<DIV class=""><PRE>Yes: <span class="external"></span>import os
1728 <span class="external"></span>import sys</PRE></DIV>
1729<DIV class=""><PRE class="badcode">No: <span class="external"></span>import os, sys</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001730 <p>
1731 Imports are always put at the top of the file, just after any
1732 module comments and doc strings and before module globals and
1733 constants. Imports should be grouped with the order being most generic
1734 to least generic:
1735 </p>
1736 <ul>
1737 <li>standard library imports</li>
1738 <li>third-party imports</li>
1739
1740 <li>application-specific imports</li>
1741 </ul>
1742 <p>
1743 Within each grouping, imports should be sorted lexicographically,
1744 ignoring case, according to each module's full package path.
1745 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001746 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001747<span class="external"></span>import foo
1748<span class="external"></span>from foo import bar
1749<span class="external"></span>from foo.bar import baz
1750<span class="external"></span>from foo.bar import Quux
mmentovai9ec7bd62009-12-03 22:25:38 +00001751<span class="external"></span>from Foob import ar</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001752
1753
mmentovai9ec7bd62009-12-03 22:25:38 +00001754
1755 </DIV></DIV>
1756 </DIV>
1757 <DIV class="">
1758<H3><A name="Statements" id="Statements">Statements</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001759<SPAN class="link_button" id="link-Statements__button" name="link-Statements__button"><A href="?showone=Statements#Statements">
1760 link
1761 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Statements__body','Statements__button')" name="Statements__button" id="Statements__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001762 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001763 Generally only one statement per line.
mmentovai9ec7bd62009-12-03 22:25:38 +00001764 </DIV>
1765 <DIV class=""><DIV class="stylepoint_body" name="Statements__body" id="Statements__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001766 <p>
1767 However, you may put the
1768 result of a test on the same line as the test only if the entire
1769 statement fits on one line. In particular, you can never do so
1770 with <code>try</code>/<code>except</code> since the
1771 <code>try</code> and <code>except</code> can't both fit on the
1772 same line, and you can only do so with an <code>if</code> if
1773 there is no <code>else</code>.
1774 </p>
1775
mmentovai9ec7bd62009-12-03 22:25:38 +00001776 <DIV class=""><PRE>Ye<span class="external"></span>s:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001777
mmentovai9ec7bd62009-12-03 22:25:38 +00001778 <span class="external"></span>if foo: bar(foo)</PRE></DIV>
1779<DIV class=""><PRE class="badcode">No<span class="external"></span>:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001780
1781 <span class="external"></span>if foo: bar(foo)
1782 <span class="external"></span>else: baz(foo)
1783
1784 <span class="external"></span>try: bar(foo)
1785 <span class="external"></span>except ValueError: baz(foo)
1786
1787 <span class="external"></span>try:
1788 <span class="external"> </span>bar(foo)
1789 <span class="external"></span>except ValueError: baz(foo)
1790<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001791</PRE></DIV>
1792 </DIV></DIV>
1793 </DIV>
1794 <DIV class="">
1795<H3><A name="Access_Control" id="Access_Control">Access Control</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001796<SPAN class="link_button" id="link-Access_Control__button" name="link-Access_Control__button"><A href="?showone=Access_Control#Access_Control">
1797 link
1798 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Access_Control__body','Access_Control__button')" name="Access_Control__button" id="Access_Control__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001799 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001800 If an accessor function would be trivial you should use public variables
1801 instead of accessor functions to avoid the extra cost of function
1802 calls in Python. When more functionality is added you can use
1803 <code>property</code> to keep the syntax consistent.
mmentovai9ec7bd62009-12-03 22:25:38 +00001804 </DIV>
1805 <DIV class=""><DIV class="stylepoint_body" name="Access_Control__body" id="Access_Control__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001806 <p>
1807 On the other hand, if access is more complex, or the cost of accessing
1808 the variable is significant, you should use function calls (following the
1809 <a HREF="#naming">Naming</a> guidelines) such as <code>get_foo()</code>
1810 and <code>set_foo()</code>. If the past behavior allowed access through a
1811 property, do not bind the new accessor functions to the property. Any
1812 code still attempting to access the variable by the old method should
1813 break visibly so they are made aware of the change in complexity.
1814 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001815 </DIV></DIV>
1816 </DIV>
1817 <DIV class="">
1818<H3><A name="Naming" id="Naming">Naming</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001819<SPAN class="link_button" id="link-Naming__button" name="link-Naming__button"><A href="?showone=Naming#Naming">
1820 link
1821 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Naming__body','Naming__button')" name="Naming__button" id="Naming__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001822 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001823 <code>module_name, package_name, ClassName, method_name, ExceptionName,
1824 function_name, GLOBAL_VAR_NAME, instance_var_name,
1825 function_parameter_name, local_var_name.</code>
mmentovai9ec7bd62009-12-03 22:25:38 +00001826 </DIV>
1827 <DIV class=""><DIV class="stylepoint_body" name="Naming__body" id="Naming__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001828 <P class="">
1829<SPAN class="stylepoint_subsection">Names to Avoid</SPAN>
1830
1831 <ul>
1832 <li>single character names except for counters or iterators</li>
1833 <li>dashes (<code>-</code>) in any package/module name</li>
1834 <li>
1835<code>__double_leading_and_trailing_underscore__</code> names
1836 (reserved by Python)</li>
1837 </ul>
1838
1839 </P>
1840 <P class="">
1841<SPAN class="stylepoint_subsection">Naming Convention</SPAN>
1842
1843 <ul>
1844 <li>
1845 "Internal" means internal to a module or protected
1846 or private within a class.</li>
1847 <li>
1848 Prepending a single underscore (<code>_</code>) has some
1849 support for protecting module variables and functions (not included
1850 with <code>import * from</code>). Prepending a double underscore
1851 (<code>__</code>) to an instance variable or method
1852 effectively serves to make the variable or method private to its class
1853 (using name mangling).</li>
1854 <li>
1855 Place related classes and top-level functions together in a
1856 module. Unlike Java,
1857 there is no need to limit yourself to one class per module.</li>
1858 <li>
1859 Use CapWords for class names, but lower_with_under.py for module names.
1860 Although there are many existing modules named CapWords.py, this is now
1861 discouraged because it's confusing when the module happens to be
1862 named after a class. ("wait -- did I write
1863 <code>import StringIO</code> or <code>from StringIO import
1864 StringIO</code>?")</li>
1865 </ul>
1866
1867 </P>
1868 <P class="">
1869<SPAN class="stylepoint_subsection">Guidelines derived from Guido's Recommendations</SPAN>
1870
1871 <table rules="all" border="1" cellspacing="2" cellpadding="2">
1872
1873 <tr>
1874 <th>Type</th>
1875 <th>Public</th>
1876 <th>Internal</th>
1877 </tr>
1878
1879
1880
1881 <tr>
1882 <td>Packages</td>
1883 <td><code>lower_with_under</code></td>
1884 <td></td>
1885 </tr>
1886
1887 <tr>
1888 <td>Modules</td>
1889 <td><code>lower_with_under</code></td>
1890 <td><code>_lower_with_under</code></td>
1891 </tr>
1892
1893 <tr>
1894 <td>Classes</td>
1895 <td><code>CapWords</code></td>
1896 <td><code>_CapWords</code></td>
1897 </tr>
1898
1899 <tr>
1900 <td>Exceptions</td>
1901 <td><code>CapWords</code></td>
1902 <td></td>
1903 </tr>
1904
1905
1906
1907 <tr>
1908 <td>Functions</td>
1909 <td><code>lower_with_under()</code></td>
1910 <td><code>_lower_with_under()</code></td>
1911 </tr>
1912
1913 <tr>
1914 <td>Global/Class Constants</td>
1915 <td><code>CAPS_WITH_UNDER</code></td>
1916 <td><code>_CAPS_WITH_UNDER</code></td>
1917 </tr>
1918
1919 <tr>
1920 <td>Global/Class Variables</td>
1921 <td><code>lower_with_under</code></td>
1922 <td><code>_lower_with_under</code></td>
1923 </tr>
1924
1925 <tr>
1926 <td>Instance Variables</td>
1927 <td><code>lower_with_under</code></td>
1928 <td><code>_lower_with_under (protected) or __lower_with_under (private)</code></td>
1929 </tr>
1930
1931
1932
1933 <tr>
1934 <td>Method Names</td>
1935 <td><code>lower_with_under()</code></td>
1936 <td><code>_lower_with_under() (protected) or __lower_with_under() (private)</code></td>
1937 </tr>
1938
1939 <tr>
1940 <td>Function/Method Parameters</td>
1941 <td><code>lower_with_under</code></td>
1942 <td></td>
1943 </tr>
1944
1945 <tr>
1946 <td>Local Variables</td>
1947 <td><code>lower_with_under</code></td>
1948 <td></td>
1949 </tr>
1950
1951
1952 </table>
1953
1954
1955 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001956 </DIV></DIV>
1957 </DIV>
1958 <DIV class="">
1959<H3><A name="Main" id="Main">Main</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001960<SPAN class="link_button" id="link-Main__button" name="link-Main__button"><A href="?showone=Main#Main">
1961 link
1962 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Main__body','Main__button')" name="Main__button" id="Main__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001963 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001964 Even a file meant to be used as a script should be importable and a
1965 mere import should not have the side effect of executing the script's
1966 main functionality. The main functionality should be in a main()
1967 function.
mmentovai9ec7bd62009-12-03 22:25:38 +00001968 </DIV>
1969 <DIV class=""><DIV class="stylepoint_body" name="Main__body" id="Main__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001970 <p>
1971 In Python,
1972 <code>pychecker</code>, <code>pydoc</code>, and unit tests
1973 require modules to be importable. Your code should always check
1974 <code>if __name__ == '__main__'</code> before executing your
1975 main program so that the main program is not executed when the
1976 module is imported.
1977
1978 </p>
1979
1980
1981
1982
1983
1984
1985
mmentovai9ec7bd62009-12-03 22:25:38 +00001986 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001987<span class="external"></span>def main():
1988 <span class="external"> </span>...
1989
1990<span class="external"></span>if __name__ == '__main__':
1991 <span class="external"> </span>main()
1992<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001993</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001994
1995 <p>
1996 All code at the top level will be executed when the module is
1997 imported. Be careful not to call functions, create objects, or
1998 perform other operations that should not be executed when the
1999 file is being <code>pycheck</code>ed or <code>pydoc</code>ed.
2000 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00002001 </DIV></DIV>
2002 </DIV>
2003 </DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002004
2005<H2>Parting Words</H2>
2006 <p>
2007 <em>BE CONSISTENT</em>.
2008 </p>
2009
2010 <p>
2011 If you're editing code, take a few minutes to look at the code
2012 around you and determine its style. If they use spaces around
2013 all their arithmetic operators, you should too. If their
2014 comments have little boxes of hash marks around them, make your
2015 comments have little boxes of hash marks around them too.
2016 </p>
2017
2018 <p>
2019 The point of having style guidelines is to have a common vocabulary
2020 of coding so people can concentrate on what you're saying rather
2021 than on how you're saying it. We present global style rules here so
2022 people know the vocabulary, but local style is also important. If
2023 code you add to a file looks drastically different from the existing
2024 code around it, it throws readers out of their rhythm when they go to
2025 read it. Avoid this.
2026 </p>
2027
2028
2029
2030<p align="right">
mmentovai9ec7bd62009-12-03 22:25:38 +00002031Revision 2.15
apicard@google.comf900c2c2009-07-23 20:09:56 +00002032</p>
2033
2034
2035<address>
2036 Amit Patel<br>
2037 Antoine Picard<br>
2038 Eugene Jhong<br>
2039 Jeremy Hylton<br>
2040 Matt Smart<br>
2041 Mike Shields<br>
2042</address>
2043</BODY>
2044</HTML>