blob: 46769a36486c47a36e389fd0201dcc9b2e7d1c0b [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>
3<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
4<TITLE>Google Python Style Guide</TITLE>
5<LINK HREF="http://www.google.com/favicon.ico" type="image/x-icon" rel="shortcut icon">
6<LINK HREF="styleguide.css" type="text/css" rel="stylesheet">
7<SCRIPT language="javascript" type="text/javascript">
8
9 function ShowHideByName(bodyName, buttonName) {
10 var bodyElements;
11 if (document.getElementsByName) {
12 bodyElements = document.getElementsByName(bodyName);
13 } else {
14 bodyElements = [document.getElementById(bodyName)];
15 }
16 if (bodyElements.length != 1) {
17 alert("ShowHideByName() got the wrong number of bodyElements: " + bodyElements.length);
18 } else {
19 var bodyElement = bodyElements[0];
20 var buttonElement;
21 if (document.getElementsByName) {
22 var buttonElements = document.getElementsByName(buttonName);
23 buttonElement = buttonElements[0];
24 } else {
25 buttonElement = document.getElementById(buttonName);
26 }
27 if (bodyElement.style.display == "none" || bodyElement.style.display == "") {
28 bodyElement.style.display = "inline";
29 buttonElement.innerHTML = '▽';
30 } else {
31 bodyElement.style.display = "none";
32 buttonElement.innerHTML = '▶';
33 }
34 }
35 }
36
37 function ShowHideAll() {
38 var allButton;
39 if (document.getElementsByName) {
40 var allButtons = document.getElementsByName("show_hide_all_button");
41 allButton = allButtons[0];
42 } else {
43 allButton = document.getElementById("show_hide_all_button");
44 }
45 if (allButton.innerHTML == '▽') {
46 allButton.innerHTML = '▶';
47 SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "none", '▶');
48 } else {
49 allButton.innerHTML = '▽';
50 SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "inline", '▽');
51 }
52 }
53
54 // Recursively sets state of all children
55 // of a particular node.
56 function SetHiddenState(root, newState, newButton) {
57 for (var i = 0; i != root.length; i++) {
58 SetHiddenState(root[i].childNodes, newState, newButton);
59 if (root[i].className == 'showhide_button') {
60 root[i].innerHTML = newButton;
61 }
62 if (root[i].className == 'stylepoint_body') {
63 root[i].style.display = newState;
64 }
65 }
66 }
67
68
69 window.onload = function() {
70 // if the URL contains "?showall=y", expand the details of all children
71 {
72 var showHideAllRegex = new RegExp("[\\?&](showall)=([^&#]*)");
73 var showHideAllValue = showHideAllRegex.exec(window.location.href);
74 if (showHideAllValue != null) {
75 if (showHideAllValue[2] == "y") {
76 SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "inline", '▽');
77 } else {
78 SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "none", '▶');
79 }
80 }
81 var showOneRegex = new RegExp("[\\?&](showone)=([^&#]*)");
82 var showOneValue = showOneRegex.exec(window.location.href);
83 if (showOneValue != null) {
84 var body_name = showOneValue[2] + '__body';
85 var button_name = showOneValue[2] + '__button';
86 ShowHideByName(body_name, button_name);
87 }
88
89 }
90 }
91 </SCRIPT>
92</HEAD>
93<BODY>
94<H1>Google Python Style Guide</H1>
95 <p align="right">
96
mmentovai9ec7bd62009-12-03 22:25:38 +000097 Revision 2.15
apicard@google.comf900c2c2009-07-23 20:09:56 +000098 </p>
99
100 <address>
101 Amit Patel<br>
102 Antoine Picard<br>
103 Eugene Jhong<br>
104 Jeremy Hylton<br>
105 Matt Smart<br>
106 Mike Shields<br>
107 </address>
108 <DIV style="margin-left: 50%; font-size: 75%;">
109<P>
110 Each style point has a summary for which additional information is available
111 by toggling the accompanying arrow button that looks this way:
112 <SPAN class="showhide_button" style="margin-left: 0;"></SPAN>.
113 You may toggle all summaries with the big arrow button:
114 </P>
115<DIV style=" font-size: larger; margin-left: +2em;">
116<SPAN class="showhide_button" style="font-size: 180%;" onclick="javascript:ShowHideAll()" name="show_hide_all_button" id="show_hide_all_button"></SPAN>
117 Toggle all summaries
118 </DIV>
119</DIV>
120<DIV class="toc">
121<DIV class="toc_title">Table of Contents</DIV>
122<TABLE>
123<TR valign="top" class="">
124<TD><DIV class="toc_category"><A href="#Python_Language_Rules">Python Language Rules</A></DIV></TD>
125<TD><DIV class="toc_stylepoint">
mmentovaif7facf92009-10-23 21:01:49 +0000126<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 +0000127</TR>
128<TR valign="top" class="">
129<TD><DIV class="toc_category"><A href="#Python_Style_Rules">Python Style Rules</A></DIV></TD>
130<TD><DIV class="toc_stylepoint">
131<SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Semicolons">Semicolons</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Line_length">Line length</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Parentheses">Parentheses</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Indentation">Indentation</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Blank_Lines">Blank Lines</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Whitespace">Whitespace</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Python_Interpreter">Python Interpreter</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Comments">Comments</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Classes">Classes</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Strings">Strings</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#TODO_Comments">TODO Comments</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Imports_formatting">Imports formatting</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Statements">Statements</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Access_Control">Access Control</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Naming">Naming</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Main">Main</A></SPAN> </DIV></TD>
132</TR>
133</TABLE>
134</DIV>
135<H2>Overview</H2>
mmentovai9ec7bd62009-12-03 22:25:38 +0000136 <DIV class="">
137<H2 name="Important_Note" id="Important_Note">Important Note</H2>
138 <DIV class="">
139<H3><A name="Displaying_Hidden_Details_in_this_Guide" id="Displaying_Hidden_Details_in_this_Guide">Displaying Hidden Details in this Guide</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000140<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 +0000141 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000142 This style guide contains many details that are initially
143 hidden from view. They are marked by the triangle icon, which you
144 see here on your left. Click it now.
145 You should see "Hooray" appear below.
mmentovai9ec7bd62009-12-03 22:25:38 +0000146 </DIV>
147 <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">
148<SPAN class="link_button"><A href="?showone=Displaying_Hidden_Details_in_this_Guide#Displaying_Hidden_Details_in_this_Guide">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000149 link
150 </A></SPAN>
151 <p>
152 Hooray! Now you know you can expand points to get more
153 details. Alternatively, there's a "toggle all" at the
154 top of this document.
155 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000156 </DIV></DIV>
157 </DIV>
158 </DIV>
159 <DIV class="">
160<H2 name="Background" id="Background">Background</H2>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000161 <p>
162 Python is the main scripting language used at Google. This
163 style guide is a list of <em>do</em>s and <em>don't</em>s for Python
164 programs.
165 </p>
166
167
168
mmentovai9ec7bd62009-12-03 22:25:38 +0000169 </DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000170
mmentovai9ec7bd62009-12-03 22:25:38 +0000171 <DIV class="">
172<H2 name="Python_Language_Rules" id="Python_Language_Rules">Python Language Rules</H2>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000173
mmentovai9ec7bd62009-12-03 22:25:38 +0000174 <DIV class="">
175<H3><A name="pychecker" id="pychecker">pychecker</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000176<SPAN class="showhide_button" onclick="javascript:ShowHideByName('pychecker__body','pychecker__button')" name="pychecker__button" id="pychecker__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000177 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000178 Run <code>pychecker</code> over your code.
mmentovai9ec7bd62009-12-03 22:25:38 +0000179 </DIV>
180 <DIV class=""><DIV class="stylepoint_body" name="pychecker__body" id="pychecker__body" style="display: none">
181<SPAN class="link_button"><A href="?showone=pychecker#pychecker">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000182 link
183 </A></SPAN>
184 <P class="">
185<SPAN class="stylepoint_section">Definition: </SPAN>
186 PyChecker is a tool for finding bugs in Python source code. It finds
187 problems that are typically caught by a compiler for less dynamic
188 languages like C and C++. It is similar to lint. Because of the
189 dynamic nature of Python, some warnings may be incorrect; however,
190 spurious warnings should be fairly infrequent.
191 </P>
192 <P class="">
193<SPAN class="stylepoint_section">Pros: </SPAN>
194 Catches easy-to-miss errors like typos, use-vars-before-assignment, etc.
195 </P>
196 <P class="">
197<SPAN class="stylepoint_section">Cons: </SPAN>
198 <code>pychecker</code> isn't perfect. To take
199 advantage of it, we'll need to sometimes: a) Write around it b)
200 Suppress its warnings c) Improve it or d) Ignore it.
201 </P>
202 <P class="">
203<SPAN class="stylepoint_section">Decision: </SPAN>
204 Make sure you run <code>pychecker</code> on your code.
205 </P>
206
207 <p>
208 For information on how to run <code>pychecker</code>, see the
209 <a HREF="http://pychecker.sourceforge.net">pychecker
210 homepage</a>
211 </p>
212 <p>
213 To suppress warnings, you can set a module-level variable named
214 <code>__pychecker__</code> to suppress appropriate warnings.
215 For example:
216 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000217 <DIV class=""><PRE>
218<span class="external"></span>__pychecker__ = 'no-callinit no-classattr'</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000219 <p>
220 Suppressing in this way has the advantage that we can easily search
221 for suppressions and revisit them.
222 </p>
223 <p>
224 You can get a list of pychecker warnings by doing
225 <code>pychecker --help</code>.
226 </p>
227 <p>
228 Unused argument warnings can be suppressed by using `_' as the
229 identifier for the unused argument or prefixing the argument name with
230 `unused_'. In situations where changing the argument names is
231 infeasible, you can mention them at the beginning of the function.
232 For example:
233 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000234 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000235<span class="external"></span>def foo(a, unused_b, unused_c, d=None, e=None):
236 <span class="external"> </span>(d, e) = (d, e) # Silence pychecker
237 <span class="external"> </span>return a
238<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000239</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000240 <p>
241 Ideally, pychecker would be extended to ensure that such `unused
242 declarations' were true.
243 </p>
244
mmentovai9ec7bd62009-12-03 22:25:38 +0000245 </DIV></DIV>
246 </DIV>
247 <DIV class="">
248<H3><A name="Imports" id="Imports">Imports</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000249<SPAN class="showhide_button" onclick="javascript:ShowHideByName('Imports__body','Imports__button')" name="Imports__button" id="Imports__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000250 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000251 Use <code>import</code>s for packages and modules only.
mmentovai9ec7bd62009-12-03 22:25:38 +0000252 </DIV>
253 <DIV class=""><DIV class="stylepoint_body" name="Imports__body" id="Imports__body" style="display: none">
254<SPAN class="link_button"><A href="?showone=Imports#Imports">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000255 link
256 </A></SPAN>
257 <P class="">
258<SPAN class="stylepoint_section">Definition: </SPAN>
259 Reusability mechanism for sharing code from one module to another.
260 </P>
261 <P class="">
262<SPAN class="stylepoint_section">Pros: </SPAN>
263 Simplest and most commonly used way of sharing things.
264 </P>
265 <P class="">
266<SPAN class="stylepoint_section">Cons: </SPAN> <code>from foo import *</code> or
267 <code>from foo import Bar</code> is
268 very nasty and can lead to serious maintenance issues because
269 it makes it hard to find module dependencies.
270 </P>
271 <P class="">
272<SPAN class="stylepoint_section">Decision: </SPAN>
273 Use <code>import x</code> for importing packages and modules.
274 Use <code>from x import y</code> only when <code>x</code> is a
275 package and <code>y</code> is a module. This allows the
276 importer to refer to the module without specifying the full
277 package prefix. For example the module
278 <code>sound.effects.echo</code> may be imported as follows:
279 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000280 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000281<span class="external"></span>from sound.effects import echo
282<span class="external"></span>...
283<span class="external"></span>echo.echofilter(input, output, delay=0.7, atten=4)
284<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000285</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000286 <p>
287 Even if the module is in the same package, do not directly import
288 the module without the full package name. This might cause the
289 package to be imported twice (with unintended side effects) when the
290 "main" module that is used to start an application lives inside a
291 package (and uses modules from that same package).
292 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000293 </DIV></DIV>
294 </DIV>
295 <DIV class="">
296<H3><A name="Packages" id="Packages">Packages</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000297<SPAN class="showhide_button" onclick="javascript:ShowHideByName('Packages__body','Packages__button')" name="Packages__button" id="Packages__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000298 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000299 Import and refer to each module using the full pathname location of
300 that module.
mmentovai9ec7bd62009-12-03 22:25:38 +0000301 </DIV>
302 <DIV class=""><DIV class="stylepoint_body" name="Packages__body" id="Packages__body" style="display: none">
303<SPAN class="link_button"><A href="?showone=Packages#Packages">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000304 link
305 </A></SPAN>
306 <P class="">
307<SPAN class="stylepoint_section">Pros: </SPAN>
308 Avoids conflicts in module names. Makes it easier to find modules.
309 </P>
310 <P class="">
311<SPAN class="stylepoint_section">Cons: </SPAN>
312 Makes it harder to deploy code because you have to replicate the
313 package hierarchy.
314 </P>
315 <P class="">
316<SPAN class="stylepoint_section">Decision: </SPAN>
317 All new code should refer to modules based on their package
318 name.
319 </P>
320 <p>
321 Imports should be as follows:
322 </p>
323
324
mmentovai9ec7bd62009-12-03 22:25:38 +0000325 <DIV class=""><PRE># Reference in code with complete name.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000326import sound.effects.echo
327
328# Reference in code with just module name.
329from sound.effects import echo
mmentovai9ec7bd62009-12-03 22:25:38 +0000330</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000331
mmentovai9ec7bd62009-12-03 22:25:38 +0000332 </DIV></DIV>
333 </DIV>
334 <DIV class="">
335<H3><A name="Exceptions" id="Exceptions">Exceptions</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000336<SPAN class="showhide_button" onclick="javascript:ShowHideByName('Exceptions__body','Exceptions__button')" name="Exceptions__button" id="Exceptions__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000337 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000338 Exceptions are allowed but must be used carefully.
mmentovai9ec7bd62009-12-03 22:25:38 +0000339 </DIV>
340 <DIV class=""><DIV class="stylepoint_body" name="Exceptions__body" id="Exceptions__body" style="display: none">
341<SPAN class="link_button"><A href="?showone=Exceptions#Exceptions">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000342 link
343 </A></SPAN>
344 <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>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000405<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 +0000406 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000407 Avoid global variables.
mmentovai9ec7bd62009-12-03 22:25:38 +0000408 </DIV>
409 <DIV class=""><DIV class="stylepoint_body" name="Global_variables__body" id="Global_variables__body" style="display: none">
410<SPAN class="link_button"><A href="?showone=Global_variables#Global_variables">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000411 link
412 </A></SPAN>
413 <P class="">
414<SPAN class="stylepoint_section">Definition: </SPAN>
415 Variables that are declared at the module level.
416 </P>
417 <P class="">
418<SPAN class="stylepoint_section">Pros: </SPAN>
419 Occasionally useful.
420 </P>
421 <P class="">
422<SPAN class="stylepoint_section">Cons: </SPAN>
423 Has the potential to change module behavior during the import,
424 because assignments to module-level variables are done when the
425 module is imported.
426 </P>
427 <P class="">
428<SPAN class="stylepoint_section">Decision: </SPAN>
429 Avoid global variables in favor of class variables. Some
430 exceptions are:
431 <ul>
432 <li>Default options for scripts.</li>
433 <li>Module-level constants. For example: <code>PI = 3.14159</code>.
434 Constants should be named using all caps with underscores;
435 see <a HREF="#Naming">Naming</a> below.</li>
436 <li>It is sometimes useful for globals to cache values needed
437 or returned by functions.</li>
438 <li>If needed, globals should be made internal to the module
439 and accessed through public module level functions;
440 see <a HREF="#Naming">Naming</a> below.</li>
441 </ul>
442 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000443 </DIV></DIV>
444 </DIV>
445 <DIV class="">
446<H3><A name="Nested/Local/Inner_Classes_and_Functions" id="Nested/Local/Inner_Classes_and_Functions">Nested/Local/Inner Classes and Functions</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000447<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 +0000448 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000449 Nested/local/inner classes and functions are fine.
mmentovai9ec7bd62009-12-03 22:25:38 +0000450 </DIV>
451 <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">
452<SPAN class="link_button"><A href="?showone=Nested/Local/Inner_Classes_and_Functions#Nested/Local/Inner_Classes_and_Functions">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000453 link
454 </A></SPAN>
455 <P class="">
456<SPAN class="stylepoint_section">Definition: </SPAN>
mmentovaif7facf92009-10-23 21:01:49 +0000457 A class can be defined inside of a method, function, or class. A
458 function can be defined inside a method or function. Nested functions
459 have read-only access to variables defined in enclosing scopes.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000460 </P>
461 <P class="">
462<SPAN class="stylepoint_section">Pros: </SPAN>
463 Allows definition of utility classes and functions that are only
464 used inside of a very limited scope. Very <a HREF="http://en.wikipedia.org/wiki/Abstract_data_type">ADT</a>-y.
465 </P>
466 <P class="">
467<SPAN class="stylepoint_section">Cons: </SPAN>
468 Instances of nested or local classes cannot be pickled.
469 </P>
470 <P class="">
471<SPAN class="stylepoint_section">Decision: </SPAN>
472 They are fine.
473 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000474 </DIV></DIV>
475 </DIV>
476 <DIV class="">
477<H3><A name="List_Comprehensions" id="List_Comprehensions">List Comprehensions</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000478<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">
483<SPAN class="link_button"><A href="?showone=List_Comprehensions#List_Comprehensions">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000484 link
485 </A></SPAN>
486 <P class="">
487<SPAN class="stylepoint_section">Definition: </SPAN>
488 List comprehensions and generator expressions provide a concise
489 and efficient way to create lists and iterators without
490 resorting to the use of <code>map()</code>,
491 <code>filter()</code>, or <code>lambda</code>.
492 </P>
493 <P class="">
494<SPAN class="stylepoint_section">Pros: </SPAN>
495 Simple list comprehensions can be clearer and simpler than
496 other list creation techniques. Generator expressions can be
497 very efficient, since they avoid the creation of a list
498 entirely.
499 </P>
500 <P class="">
501<SPAN class="stylepoint_section">Cons: </SPAN>
502 Complicated list comprehensions or generator expressions can be
503 hard to read.
504 </P>
505 <P class="">
506<SPAN class="stylepoint_section">Decision: </SPAN>
507 Okay to use for simple cases. Each portion must fit on one line:
508 mapping expression, <code>for</code> clause, filter expression.
509 Multiple <code>for</code> clauses or filter expressions are not
510 permitted. Use loops instead when things get more complicated.
511 </P>
512
mmentovai9ec7bd62009-12-03 22:25:38 +0000513<DIV class=""><PRE class="badcode">No<span class="external"></span>:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000514 <span class="external"></span>result = [(x, y) for x in range(10) for y in range(5) if x * y &gt; 10]
515
516 <span class="external"></span>return ((x, y, z)
517 <span class="external"></span> for x in xrange(5)
518 <span class="external"></span> for y in xrange(5)
519 <span class="external"></span> if x != y
520 <span class="external"></span> for z in xrange(5)
mmentovai9ec7bd62009-12-03 22:25:38 +0000521 <span class="external"></span> if y != z)</PRE></DIV>
522<DIV class=""><PRE>Ye<span class="external"></span>s:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000523 <span class="external"></span>result = []
524 <span class="external"></span>for x in range(10):
525 <span class="external"> </span>for y in range(5):
526 <span class="external"> </span>if x * y &gt; 10:
527 <span class="external"> </span>result.append((x, y))
528
529 <span class="external"></span>for x in xrange(5):
530 <span class="external"> </span>for y in xrange(5):
531 <span class="external"> </span>if x != y:
532 <span class="external"> </span>for z in xrange(5):
533 <span class="external"> </span>if y != z:
534 <span class="external"> </span>yield (x, y, z)
535
536 <span class="external"></span>return ((x, complicated_transform(x))
537 <span class="external"></span> for x in long_generator_function(parameter)
538 <span class="external"></span> if x is not None)
539
540 <span class="external"></span>squares = [x * x for x in range(10)]
541
542 <span class="external"></span>eat(jelly_bean for jelly_bean in jelly_beans
mmentovai9ec7bd62009-12-03 22:25:38 +0000543 <span class="external"></span> if jelly_bean.color == 'black')</PRE></DIV>
544 </DIV></DIV>
545 </DIV>
546 <DIV class="">
547<H3><A name="Default_Iterators_and_Operators" id="Default_Iterators_and_Operators">Default Iterators and Operators</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000548<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 +0000549 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000550 Use default iterators and operators for types that support them,
551 like lists, dictionaries, and files.
mmentovai9ec7bd62009-12-03 22:25:38 +0000552 </DIV>
553 <DIV class=""><DIV class="stylepoint_body" name="Default_Iterators_and_Operators__body" id="Default_Iterators_and_Operators__body" style="display: none">
554<SPAN class="link_button"><A href="?showone=Default_Iterators_and_Operators#Default_Iterators_and_Operators">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000555 link
556 </A></SPAN>
557 <P class="">
558<SPAN class="stylepoint_section">Definition: </SPAN>
559 Container types, like dictionaries and lists, define default
560 iterators and membership test operators ("in" and "not in").
561 </P>
562 <P class="">
563<SPAN class="stylepoint_section">Pros: </SPAN>
564 The default iterators and operators are simple and efficient.
565 They express the operation directly, without extra method calls.
566 A function that uses default operators is generic. It can be
567 used with any type that supports the operation.
568 </P>
569 <P class="">
570<SPAN class="stylepoint_section">Cons: </SPAN>
571 You can't tell the type of objects by reading the method names
572 (e.g. has_key() means a dictionary). This is also an advantage.
573 </P>
574 <P class="">
575<SPAN class="stylepoint_section">Decision: </SPAN> Use default iterators and operators for types
576 that support them, like lists, dictionaries, and files. The
577 built-in types define iterator methods, too. Prefer these
578 methods to methods that return lists, except that you should not
579 mutate a container while iterating over it.
580
mmentovai9ec7bd62009-12-03 22:25:38 +0000581<DIV class=""><PRE>Yes: <span class="external"></span>for key in adict: ...
apicard@google.comf900c2c2009-07-23 20:09:56 +0000582 <span class="external"></span>if key not in adict: ...
583 <span class="external"></span>if obj in alist: ...
584 <span class="external"></span>for line in afile: ...
mmentovai9ec7bd62009-12-03 22:25:38 +0000585 <span class="external"></span>for k, v in dict.iteritems(): ...</PRE></DIV>
586<DIV class=""><PRE class="badcode">No: <span class="external"></span>for key in adict.keys(): ...
apicard@google.comf900c2c2009-07-23 20:09:56 +0000587 <span class="external"></span>if not adict.has_key(key): ...
mmentovai9ec7bd62009-12-03 22:25:38 +0000588 <span class="external"></span>for line in afile.readlines(): ...</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000589 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000590 </DIV></DIV>
591 </DIV>
592 <DIV class="">
593<H3><A name="Generators" id="Generators">Generators</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000594<SPAN class="showhide_button" onclick="javascript:ShowHideByName('Generators__body','Generators__button')" name="Generators__button" id="Generators__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000595 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000596 Use generators as needed.
mmentovai9ec7bd62009-12-03 22:25:38 +0000597 </DIV>
598 <DIV class=""><DIV class="stylepoint_body" name="Generators__body" id="Generators__body" style="display: none">
599<SPAN class="link_button"><A href="?showone=Generators#Generators">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000600 link
601 </A></SPAN>
602 <P class="">
603<SPAN class="stylepoint_section">Definition: </SPAN>
604 A generator function returns an iterator that yields a value each
605 time it executes a yield statement. After it yields a value, the
606 runtime state of the generator function is suspended until the
607 next value is needed.
608 </P>
609 <P class="">
610<SPAN class="stylepoint_section">Pros: </SPAN>
611 Simpler code, because the state of local variables and control flow
612 are preserved for each call. A generator uses less memory than a
613 function that creates an entire list of values at once.
614 </P>
615 <P class="">
616<SPAN class="stylepoint_section">Cons: </SPAN>
617 None.
618 </P>
619 <P class="">
620<SPAN class="stylepoint_section">Decision: </SPAN>
621 Fine. Use "Yields:" rather than "Returns:" in the
622 doc string for generator functions.
623 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000624 </DIV></DIV>
625 </DIV>
626 <DIV class="">
627<H3><A name="Lambda_Functions" id="Lambda_Functions">Lambda Functions</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000628<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 +0000629 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000630 Okay for one-liners.
mmentovai9ec7bd62009-12-03 22:25:38 +0000631 </DIV>
632 <DIV class=""><DIV class="stylepoint_body" name="Lambda_Functions__body" id="Lambda_Functions__body" style="display: none">
633<SPAN class="link_button"><A href="?showone=Lambda_Functions#Lambda_Functions">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000634 link
635 </A></SPAN>
636 <P class="">
637<SPAN class="stylepoint_section">Definition: </SPAN>
638 Lambdas define anonymous functions in an expression, as
639 opposed to a statement. They are often used to define callbacks or
640 operators for higher-order functions like <code>map()</code> and
641 <code>filter()</code>.
642 </P>
643 <P class="">
644<SPAN class="stylepoint_section">Pros: </SPAN>
645 Convenient.
646 </P>
647 <P class="">
648<SPAN class="stylepoint_section">Cons: </SPAN> Harder to read and debug than local functions. The
649 lack of names means stack traces are more difficult to
650 understand. Expressiveness is limited because the function may
651 only contain an expression.
652 </P>
653 <P class="">
654<SPAN class="stylepoint_section">Decision: </SPAN>
655 Okay to use them for one-liners. If the code inside the lambda
656 function is any longer than 60–80 chars, it's probably better to
657 define it as a regular (nested) function.
658 <p>
659 For common operations like multiplication, use the functions from the
660 <code>operator</code> module instead of lambda functions. For
661 example, prefer <code>operator.mul</code> to <code>lambda
662 x, y: x * y</code>.
663 </p>
664 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000665 </DIV></DIV>
666 </DIV>
667 <DIV class="">
668<H3><A name="Default_Argument_Values" id="Default_Argument_Values">Default Argument Values</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000669<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 +0000670 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000671 Okay in most cases.
mmentovai9ec7bd62009-12-03 22:25:38 +0000672 </DIV>
673 <DIV class=""><DIV class="stylepoint_body" name="Default_Argument_Values__body" id="Default_Argument_Values__body" style="display: none">
674<SPAN class="link_button"><A href="?showone=Default_Argument_Values#Default_Argument_Values">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000675 link
676 </A></SPAN>
677 <P class="">
678<SPAN class="stylepoint_section">Definition: </SPAN>
679 You can specify values for variables at the end of a function's
680 parameter list, e.g., <code>def foo(a, b=0):</code>. If
681 <code>foo</code> is called with only one argument,
682 <code>b</code> is set to 0. If it is called with two arguments,
683 <code>b</code> has the value of the second argument.
684 </P>
685 <P class="">
686<SPAN class="stylepoint_section">Pros: </SPAN>
687 Often you have a function that uses lots of default values,
688 but—rarely—you want to override the
689 defaults. Default argument values provide an easy way to do this,
690 without having to define lots of functions for the rare
691 exceptions. Also, Python does not support overloaded
692 methods/functions and default arguments are an easy way of
693 "faking" the overloading behavior.
694 </P>
695 <P class="">
696<SPAN class="stylepoint_section">Cons: </SPAN>
697 Default arguments are evaluated once at module load
698 time. This may cause problems if the argument is a mutable
699 object such as a list or a dictionary. If the function modifies
700 the object (e.g., by appending an item to a list), the default
701 value is modified.
702 </P>
703 <P class="">
704<SPAN class="stylepoint_section">Decision: </SPAN>
705 Okay to use with the following caveats:
706 <p>
707 Do not use mutable objects as default values in the function or method
708 definition.
709 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000710<DIV class=""><PRE>Yes: <span class="external"></span>def foo(a, b=None):
apicard@google.comf900c2c2009-07-23 20:09:56 +0000711 <span class="external"> </span>if b is None:
mmentovai9ec7bd62009-12-03 22:25:38 +0000712 <span class="external"> </span>b = []</PRE></DIV>
713<DIV class=""><PRE class="badcode">No: <span class="external"></span>def foo(a, b=[]):
714 <span class="external"> </span>...</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000715 <p>
mmentovaif7facf92009-10-23 21:01:49 +0000716 Calling code must use named values for arguments with a default value.
717 This helps document the code somewhat and helps prevent and detect
apicard@google.comf900c2c2009-07-23 20:09:56 +0000718 interface breakage when more arguments are added.
719 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000720<DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000721<span class="external"></span>def foo(a, b=1):
mmentovai9ec7bd62009-12-03 22:25:38 +0000722 <span class="external"> </span>...</PRE></DIV>
723<DIV class=""><PRE>Yes: <span class="external"></span>foo(1)
724 <span class="external"></span>foo(1, b=2)</PRE></DIV>
725<DIV class=""><PRE class="badcode">No: <span class="external"></span>foo(1, 2)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000726 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000727 </DIV></DIV>
728 </DIV>
729 <DIV class="">
730<H3><A name="Properties" id="Properties">Properties</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000731<SPAN class="showhide_button" onclick="javascript:ShowHideByName('Properties__body','Properties__button')" name="Properties__button" id="Properties__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000732 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000733 Use properties for accessing or setting data where you would
734 normally have used simple, lightweight accessor or setter methods.
mmentovai9ec7bd62009-12-03 22:25:38 +0000735 </DIV>
736 <DIV class=""><DIV class="stylepoint_body" name="Properties__body" id="Properties__body" style="display: none">
737<SPAN class="link_button"><A href="?showone=Properties#Properties">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000738 link
739 </A></SPAN>
740 <P class="">
741<SPAN class="stylepoint_section">Definition: </SPAN> A way to wrap method calls for getting and
742 setting an attribute as a standard attribute access when the
743 computation is lightweight.
744 </P>
745 <P class="">
746<SPAN class="stylepoint_section">Pros: </SPAN> Readability is increased by eliminating explicit
747 get and set method calls for simple attribute access. Allows
748 calculations to be lazy. Considered the Pythonic way to
749 maintain the interface of a class. In terms of performance,
750 allowing properties bypasses needing trivial accessor methods
751 when a direct variable access is reasonable. This also allows
752 accessor methods to be added in the future without breaking the
753 interface.
754 </P>
755 <P class="">
756<SPAN class="stylepoint_section">Cons: </SPAN> Properties are specified after the getter and
757 setter methods are declared, requiring one to notice they are
758 used for properties farther down in the code (except for readonly
759 properties created with the <code>@property</code> decorator - see
760 below). Must inherit from
761 <code>object</code>. Can hide side-effects much like operator
762 overloading. Can be confusing for subclasses.
763 </P>
764 <P class="">
765<SPAN class="stylepoint_section">Decision: </SPAN> Use properties in new code to access or
766 set data where you would normally have used simple, lightweight
767 accessor or setter methods. Read-only properties should be created
768 with the <code>@property</code>
769 <a HREF="#Function_and_Method_Decorators">decorator</a>.
770
771 <p><a id="properties-template-dp">
772 Inheritance with properties can be non-obvious if the property itself is
773 not overridden. Thus one must make sure that accessor methods are
774 called indirectly to ensure methods overridden in subclasses are called
775 by the property (using the Template Method DP).
776 </a></p>
777
mmentovai9ec7bd62009-12-03 22:25:38 +0000778 <DIV class=""><PRE>Yes: <span class="external"></span>import math
apicard@google.comf900c2c2009-07-23 20:09:56 +0000779
780 <span class="external"></span>class Square(object):
781 <span class="external"> </span>"""A square with two properties: a writable area and a read-only perimeter.
782
783 <span class="external"> </span>To use:
784 <span class="external"> </span>&gt;&gt;&gt; sq = Square(3)
785 <span class="external"> </span>&gt;&gt;&gt; sq.area
786 <span class="external"> </span>9
787 <span class="external"> </span>&gt;&gt;&gt; sq.perimeter
788 <span class="external"> </span>12
789 <span class="external"> </span>&gt;&gt;&gt; sq.area = 16
790 <span class="external"> </span>&gt;&gt;&gt; sq.side
791 <span class="external"> </span>4
792 <span class="external"> </span>&gt;&gt;&gt; sq.perimeter
793 <span class="external"> </span>16
794 <span class="external"> </span>"""
795
796 <span class="external"> </span>def __init__(self, side):
797 <span class="external"> </span>self.side = side
798
799 <span class="external"> </span>def __get_area(self):
800 <span class="external"> </span>"""Calculates the 'area' property."""
801 <span class="external"> </span>return self.side ** 2
802
803 <span class="external"> </span>def ___get_area(self):
804 <span class="external"> </span>"""Indirect accessor for 'area' property."""
805 <span class="external"> </span>return self.__get_area()
806
807 <span class="external"> </span>def __set_area(self, area):
808 <span class="external"> </span>"""Sets the 'area' property."""
809 <span class="external"> </span>self.side = math.sqrt(area)
810
811 <span class="external"> </span>def ___set_area(self, area):
812 <span class="external"> </span>"""Indirect setter for 'area' property."""
813 <span class="external"> </span>self._SetArea(area)
814
815 <span class="external"> </span>area = property(___get_area, ___set_area,
816 <span class="external"> </span> doc="""Gets or sets the area of the square.""")
817
818 <span class="external"> </span>@property
819 <span class="external"> </span>def perimeter(self):
820 <span class="external"> </span>return self.side * 4
821<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000822</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000823 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000824 </DIV></DIV>
825 </DIV>
826 <DIV class="">
827<H3><A name="True/False_evaluations" id="True/False_evaluations">True/False evaluations</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000828<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 +0000829 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000830 Use the "implicit" false if at all possible.
mmentovai9ec7bd62009-12-03 22:25:38 +0000831 </DIV>
832 <DIV class=""><DIV class="stylepoint_body" name="True/False_evaluations__body" id="True/False_evaluations__body" style="display: none">
833<SPAN class="link_button"><A href="?showone=True/False_evaluations#True/False_evaluations">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000834 link
835 </A></SPAN>
836 <P class="">
837<SPAN class="stylepoint_section">Definition: </SPAN> Python evaluates certain values as <code>false</code>
838 when in a boolean context. A quick "rule of thumb" is that all
839 "empty" values are considered <code>false</code> so <code>0, None, [], {},
840 ""</code> all evaluate as <code>false</code> in a boolean context.
841 </P>
842 <P class="">
843<SPAN class="stylepoint_section">Pros: </SPAN> Conditions using Python booleans are easier to read
844 and less error-prone. In most cases, they're also faster.
845 </P>
846 <P class="">
847<SPAN class="stylepoint_section">Cons: </SPAN>
848 May look strange to C/C++ developers.
849 </P>
850 <P class="">
851<SPAN class="stylepoint_section">Decision: </SPAN>
852 Use the "implicit" false if at all possible, e.g., <code>if
853 foo:</code> rather than <code>if foo != []:</code>. There are a
854 few caveats that you should keep in mind though:
855 <ul>
856 <li>
857 Never use <code>==</code> or <code>!=</code> to compare
858 singletons like <code>None</code>. Use <code>is</code>
859 or <code>is not</code>.</li>
860
861 <li>Beware of writing <code>if x:</code> when you really mean
862 <code>if x is not None:</code>—e.g., when testing whether
863 a variable or argument that defaults to <code>None</code> was
864 set to some other value. The other value might be a value
865 that's false in a boolean context!</li>
866
867 <li>
868 Never compare a boolean variable to <code>False</code> using
869 <code>==</code>. Use <code>if not x:</code> instead. If
870 you need to distinguish <code>False</code> from
871 <code>None</code> then chain the expressions,
872 such as <code>if not x and x is not None:</code>.
873 </li>
874
875 <li>
876 For sequences (strings, lists, tuples), use the fact that
877 empty sequences are false, so <code>if not seq:</code> or
878 <code>if seq:</code> is preferable to <code>if
879 len(seq):</code> or <code>if not
880 len(seq):</code>.</li>
881
882 <li>
883 When handling integers, implicit false may involve more risk than
884 benefit (i.e., accidentally handling <code>None</code> as 0). You may
885 compare a value which is known to be an integer (and is not the
886 result of <code>len()</code>) against the integer 0.
mmentovai9ec7bd62009-12-03 22:25:38 +0000887<DIV class=""><PRE>Yes: <span class="external"></span>if not users:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000888 <span class="external"> </span>print 'no users'
889
890 <span class="external"></span>if foo == 0:
891 <span class="external"> </span>self.handle_zero()
892
893 <span class="external"></span>if i % 10 == 0:
mmentovai9ec7bd62009-12-03 22:25:38 +0000894 <span class="external"> </span>self.handle_multiple_of_ten()</PRE></DIV>
895<DIV class=""><PRE class="badcode">No: <span class="external"></span>if len(users) == 0:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000896 <span class="external"> </span>print 'no users'
897
898 <span class="external"></span>if foo is not None and not foo:
899 <span class="external"> </span>self.handle_zero()
900
901 <span class="external"></span>if not i % 10:
mmentovai9ec7bd62009-12-03 22:25:38 +0000902 <span class="external"> </span>self.handle_multiple_of_ten()</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000903</li>
904
905 <li>
906 Note that <code>'0'</code> (i.e., <code>0</code> as string)
907 evaluates to true.</li>
908 </ul>
909 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000910 </DIV></DIV>
911 </DIV>
912 <DIV class="">
913<H3><A name="Deprecated_Language_Features" id="Deprecated_Language_Features">Deprecated Language Features</A></H3>
mmentovaif7facf92009-10-23 21:01:49 +0000914<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 +0000915 <DIV style="display:inline;" class="">
mmentovaif7facf92009-10-23 21:01:49 +0000916 Use string methods instead of the <code>string</code> module
917 where possible. Use function call syntax instead
918 of <code>apply</code>. Use list comprehensions
919 and <code>for</code> loops instead of <code>filter</code>,
920 <code>map</code>, and <code>reduce</code>.
mmentovai9ec7bd62009-12-03 22:25:38 +0000921 </DIV>
922 <DIV class=""><DIV class="stylepoint_body" name="Deprecated_Language_Features__body" id="Deprecated_Language_Features__body" style="display: none">
923<SPAN class="link_button"><A href="?showone=Deprecated_Language_Features#Deprecated_Language_Features">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000924 link
925 </A></SPAN>
926 <P class="">
mmentovaif7facf92009-10-23 21:01:49 +0000927<SPAN class="stylepoint_section">Definition: </SPAN>
928 Current versions of Python provide alternative constructs
929 that people find generally preferable.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000930 </P>
931 <P class="">
mmentovaif7facf92009-10-23 21:01:49 +0000932<SPAN class="stylepoint_section">Decision: </SPAN>
933 We do not use any Python version which does not support
934 these features, so there is no reason not to use the new
935 styles.
mmentovai9ec7bd62009-12-03 22:25:38 +0000936<DIV class=""><PRE class="badcode">No: <span class="external"></span>words = string.split(foo, ':')
mmentovaif7facf92009-10-23 21:01:49 +0000937
938 <span class="external"></span>map(lambda x: x[1], filter(lambda x: x[2] == 5, my_list))
939
mmentovai9ec7bd62009-12-03 22:25:38 +0000940 <span class="external"></span>apply(fn, args, kwargs)</PRE></DIV>
941<DIV class=""><PRE>Yes: <span class="external"></span>words = foo.split(':')
mmentovaif7facf92009-10-23 21:01:49 +0000942
943 <span class="external"></span>[x[1] for x in my_list if x[2] == 5]
944
mmentovai9ec7bd62009-12-03 22:25:38 +0000945 <span class="external"></span>fn(*args, **kwargs)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000946 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000947 </DIV></DIV>
948 </DIV>
949 <DIV class="">
950<H3><A name="Lexical_Scoping" id="Lexical_Scoping">Lexical Scoping</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000951<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 +0000952 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000953 Okay to use.
mmentovai9ec7bd62009-12-03 22:25:38 +0000954 </DIV>
955 <DIV class=""><DIV class="stylepoint_body" name="Lexical_Scoping__body" id="Lexical_Scoping__body" style="display: none">
956<SPAN class="link_button"><A href="?showone=Lexical_Scoping#Lexical_Scoping">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000957 link
958 </A></SPAN>
959 <P class="">
960<SPAN class="stylepoint_section">Definition: </SPAN>
961 A nested Python function can refer to variables defined in
962 enclosing functions, but can not assign to them. Variable
963 bindings are resolved using lexical scoping, that is, based on
964 the static program text. Any assignment to a name in a block
965 will cause Python to treat all references to that name as a
966 local variable, even if the use precedes the assignment. If a
967 global declaration occurs, the name is treated as a global
968 variable.
969
970 <p>
971 An example of the use of this feature is:
972 </p>
973
mmentovai9ec7bd62009-12-03 22:25:38 +0000974 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000975<span class="external"></span>def get_adder(summand1):
976 <span class="external"> </span>"""Returns a function that adds numbers to a given number."""
977 <span class="external"> </span>def adder(summand2):
978 <span class="external"> </span>return summand1 + summand2
979
980 <span class="external"> </span>return adder
981<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000982</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000983 </P>
984 <P class="">
985<SPAN class="stylepoint_section">Pros: </SPAN>
986 Often results in clearer, more elegant code. Especially comforting
987 to experienced Lisp and Scheme (and Haskell and ML and …)
988 programmers.
989 </P>
990 <P class="">
991<SPAN class="stylepoint_section">Cons: </SPAN>
992 Can lead to confusing bugs. Such as this example based on
993 <a HREF="http://www.python.org/dev/peps/pep-0227/">PEP-0227</a>:
mmentovai9ec7bd62009-12-03 22:25:38 +0000994<DIV class=""><PRE class="badcode">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000995<span class="external"></span>i = 4
996<span class="external"></span>def foo(x):
997 <span class="external"> </span>def bar():
998 <span class="external"> </span>print i,
999 <span class="external"> </span># ...
1000 <span class="external"> </span># A bunch of code here
1001 <span class="external"> </span># ...
1002 <span class="external"> </span>for i in x: # Ah, i *is* local to Foo, so this is what Bar sees
1003 <span class="external"> </span>print i,
mmentovai9ec7bd62009-12-03 22:25:38 +00001004 <span class="external"> </span>bar()</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001005 <p>
1006 So <code>foo([1, 2, 3])</code> will print <code>1 2 3 3</code>, not
1007 <code>1 2 3 4</code>.
1008 </p>
1009 </P>
1010 <P class="">
1011<SPAN class="stylepoint_section">Decision: </SPAN>
1012 Okay to use.
1013 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001014 </DIV></DIV>
1015 </DIV>
1016 <DIV class="">
1017<H3><A name="Function_and_Method_Decorators" id="Function_and_Method_Decorators">Function and Method Decorators</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001018<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 +00001019 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001020 Use decorators judiciously when there is a clear advantage.
mmentovai9ec7bd62009-12-03 22:25:38 +00001021 </DIV>
1022 <DIV class=""><DIV class="stylepoint_body" name="Function_and_Method_Decorators__body" id="Function_and_Method_Decorators__body" style="display: none">
1023<SPAN class="link_button"><A href="?showone=Function_and_Method_Decorators#Function_and_Method_Decorators">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001024 link
1025 </A></SPAN>
1026 <P class="">
1027<SPAN class="stylepoint_section">Definition: </SPAN>
1028
1029 <a HREF="http://www.python.org/doc/2.4.3/whatsnew/node6.html">Decorators
1030 for Functions and Methods</a>
1031 (a.k.a "the <code>@</code> notation").
1032 The most common decorators are <code>@classmethod</code> and
1033 <code>@staticmethod</code>, for converting ordinary methods to class or
1034 static methods. However, the decorator syntax allows for
1035 user-defined decorators as well. Specifically, for some function
1036 <code>my_decorator</code>, this:
mmentovai9ec7bd62009-12-03 22:25:38 +00001037 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001038<span class="external"></span>class C(object):
1039 <span class="external"> </span>@my_decorator
1040 <span class="external"> </span>def method(self):
1041 <span class="external"> </span># method body ...
1042<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001043</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001044
1045 is equivalent to:
mmentovai9ec7bd62009-12-03 22:25:38 +00001046 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001047<span class="external"></span>class C(object):
1048 <span class="external"> </span>def method(self):
1049 <span class="external"> </span># method body ...
1050 <span class="external"> </span>method = my_decorator(method)
1051<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001052</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001053 </P>
1054 <P class="">
1055<SPAN class="stylepoint_section">Pros: </SPAN> Elegantly specifies some transformation on a method; the
1056 transformation might eliminate some repetitive code, enforce invariants,
1057 etc.
1058 </P>
1059 <P class="">
1060<SPAN class="stylepoint_section">Cons: </SPAN> Decorators can perform arbitrary operations on a
1061 function's arguments or return values, resulting in surprising
1062 implicit behavior.
1063 Additionally, decorators execute at import time. Failures in decorator
1064 code are pretty much impossible to recover from.
1065 </P>
1066 <P class="">
1067<SPAN class="stylepoint_section">Decision: </SPAN> Use decorators judiciously when there is a clear
1068 advantage. Decorators should follow the same import and naming
1069 guidelines as functions. Decorator pydoc should clearly state that the
1070 function is a decorator. Write unit tests for decorators.
1071
1072 <p>
1073 Avoid external dependencies in the decorator itself (e.g. don't rely on
1074 files, sockets, database connections, etc.), since they might not be
1075 available when the decorator runs (at import time, perhaps from
1076 <code>pychecker</code> or other tools). A decorator that is
1077 called with valid parameters should (as much as possible) be guaranteed
1078 to succeed in all cases.
1079 </p>
1080 <p>
1081 Decorators are a special case of "top level code" - see
1082 <a HREF="#Main">main</a> for more discussion.
1083 </p>
1084 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001085 </DIV></DIV>
1086 </DIV>
1087 <DIV class="">
1088<H3><A name="Threading" id="Threading">Threading</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001089<SPAN class="showhide_button" onclick="javascript:ShowHideByName('Threading__body','Threading__button')" name="Threading__button" id="Threading__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001090 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001091 Do not rely on the atomicity of built-in types.
mmentovai9ec7bd62009-12-03 22:25:38 +00001092 </DIV>
1093 <DIV class=""><DIV class="stylepoint_body" name="Threading__body" id="Threading__body" style="display: none">
1094<SPAN class="link_button"><A href="?showone=Threading#Threading">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001095 link
1096 </A></SPAN>
1097 <p>
1098 While Python's built-in data types such as dictionaries appear
1099 to have atomic operations, there are corner cases where they
1100 aren't atomic (e.g. if <code>__hash__</code> or
1101 <code>__eq__</code> are implemented as Python methods) and their
1102 atomicity should not be relied upon. Neither should you rely on
1103 atomic variable assignment (since this in turn depends on
1104 dictionaries).
1105 </p>
1106
1107 <p>
1108 Use the Queue module's <code>Queue</code> data type as the preferred
1109 way to
1110 communicate data between threads. Otherwise, use the threading
1111 module and its locking primitives. Learn about the proper use
1112 of condition variables so you can use
1113 <code>threading.Condition</code> instead of using lower-level
1114 locks.
1115 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001116 </DIV></DIV>
1117 </DIV>
1118 <DIV class="">
1119<H3><A name="Power_Features" id="Power_Features">Power Features</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001120<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 +00001121 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001122 Avoid these features.
mmentovai9ec7bd62009-12-03 22:25:38 +00001123 </DIV>
1124 <DIV class=""><DIV class="stylepoint_body" name="Power_Features__body" id="Power_Features__body" style="display: none">
1125<SPAN class="link_button"><A href="?showone=Power_Features#Power_Features">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001126 link
1127 </A></SPAN>
1128 <P class="">
1129<SPAN class="stylepoint_section">Definition: </SPAN> Python is an extremely flexible language and
1130 gives you many fancy features such as metaclasses, access to bytecode,
1131 on-the-fly compilation, dynamic inheritance, object reparenting,
1132 import hacks, reflection, modification of system internals,
1133 etc.
1134 </P>
1135 <P class="">
1136<SPAN class="stylepoint_section">Pros: </SPAN> These are powerful language features. They can
1137 make your code more compact.
1138 </P>
1139 <P class="">
1140<SPAN class="stylepoint_section">Cons: </SPAN> It's very tempting to use these "cool" features
1141 when they're not absolutely necessary. It's harder to read,
1142 understand, and debug code that's using unusual features
1143 underneath. It doesn't seem that way at first (to the original
1144 author), but when revisiting the code, it tends to be more
1145 difficult than code that is longer but is straightforward.
1146 </P>
1147 <P class="">
1148<SPAN class="stylepoint_section">Decision: </SPAN>
1149 Avoid these features in
1150 your code.
1151 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001152 </DIV></DIV>
1153 </DIV>
1154 </DIV>
1155 <DIV class="">
1156<H2 name="Python_Style_Rules" id="Python_Style_Rules">Python Style Rules</H2>
1157 <DIV class="">
1158<H3><A name="Semicolons" id="Semicolons">Semicolons</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001159<SPAN class="showhide_button" onclick="javascript:ShowHideByName('Semicolons__body','Semicolons__button')" name="Semicolons__button" id="Semicolons__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001160 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001161 Do not terminate your lines with semi-colons and do not use
1162 semi-colons to put two commands on the same line.
mmentovai9ec7bd62009-12-03 22:25:38 +00001163 </DIV>
1164 <DIV class=""><DIV class="stylepoint_body" name="Semicolons__body" id="Semicolons__body" style="display: none">
1165<SPAN class="link_button"><A href="?showone=Semicolons#Semicolons">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001166 link
1167 </A></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001168 </DIV></DIV>
1169 </DIV>
1170 <DIV class="">
1171<H3><A name="Line_length" id="Line_length">Line length</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001172<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 +00001173 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001174 Maximum line length is <em>80 characters</em>.
mmentovai9ec7bd62009-12-03 22:25:38 +00001175 </DIV>
1176 <DIV class=""><DIV class="stylepoint_body" name="Line_length__body" id="Line_length__body" style="display: none">
1177<SPAN class="link_button"><A href="?showone=Line_length#Line_length">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001178 link
1179 </A></SPAN>
1180 <p>
1181 Exception: lines importing modules may end up longer than 80
1182 characters only if using Python 2.4 or
1183 earlier.
1184 </p>
1185
1186 <p>
1187 Make use of Python's
1188
1189 <a HREF="http://www.python.org/doc/ref/implicit-joining.html">implicit
1190 line joining inside parentheses, brackets and braces</a>.
1191 If necessary, you can add an extra pair of parentheses around an
1192 expression.
1193 </p>
1194
1195
mmentovai9ec7bd62009-12-03 22:25:38 +00001196 <DIV class=""><PRE>Yes: foo_bar(self, width, height, color='black', design=None, x='foo',
apicard@google.comf900c2c2009-07-23 20:09:56 +00001197 emphasis=None, highlight=0)
1198
1199 if (width == 0 and height == 0 and
mmentovai9ec7bd62009-12-03 22:25:38 +00001200 color == 'red' and emphasis == 'strong'):</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001201
1202
1203 <p>
1204 When a literal string won't fit on a single line, use parentheses for
1205 implicit line joining.
1206 </p>
1207
mmentovai9ec7bd62009-12-03 22:25:38 +00001208 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001209<span class="external"></span>x = ('This will build a very long long '
mmentovai9ec7bd62009-12-03 22:25:38 +00001210<span class="external"></span> 'long long long long long long string')</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001211
1212 <p>
1213 Make note of the indentation of the elements in the line
1214 continuation examples above; see the
1215 <a HREF="#indentation">indentation</a>
1216 section for explanation.
1217 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001218 </DIV></DIV>
1219 </DIV>
1220 <DIV class="">
1221<H3><A name="Parentheses" id="Parentheses">Parentheses</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001222<SPAN class="showhide_button" onclick="javascript:ShowHideByName('Parentheses__body','Parentheses__button')" name="Parentheses__button" id="Parentheses__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001223 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001224 Use parentheses sparingly.
mmentovai9ec7bd62009-12-03 22:25:38 +00001225 </DIV>
1226 <DIV class=""><DIV class="stylepoint_body" name="Parentheses__body" id="Parentheses__body" style="display: none">
1227<SPAN class="link_button"><A href="?showone=Parentheses#Parentheses">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001228 link
1229 </A></SPAN>
1230 <p>
1231 Do not use them in return statements or conditional statements unless
1232 using parentheses for implied line continuation. (See above.)
1233 It is however fine to use parentheses around tuples.
1234 </p>
1235
mmentovai9ec7bd62009-12-03 22:25:38 +00001236<DIV class=""><PRE>Yes: <span class="external"></span>if foo:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001237 <span class="external"> </span>bar()
1238 <span class="external"></span>while x:
1239 <span class="external"> </span>x = bar()
1240 <span class="external"></span>if x and y:
1241 <span class="external"> </span>bar()
1242 <span class="external"></span>if not x:
1243 <span class="external"> </span>bar()
1244 <span class="external"></span>return foo
mmentovai9ec7bd62009-12-03 22:25:38 +00001245 <span class="external"></span>for (x, y) in dict.items(): ...</PRE></DIV>
1246<DIV class=""><PRE class="badcode">No: <span class="external"></span>if (x):
apicard@google.comf900c2c2009-07-23 20:09:56 +00001247 <span class="external"> </span>bar()
1248 <span class="external"></span>if not(x):
1249 <span class="external"> </span>bar()
mmentovai9ec7bd62009-12-03 22:25:38 +00001250 <span class="external"></span>return (foo)</PRE></DIV>
1251 </DIV></DIV>
1252 </DIV>
1253 <DIV class="">
1254<H3><A name="Indentation" id="Indentation">Indentation</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001255<SPAN class="showhide_button" onclick="javascript:ShowHideByName('Indentation__body','Indentation__button')" name="Indentation__button" id="Indentation__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001256 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001257 Indent your code blocks with <em>4 spaces</em>.
mmentovai9ec7bd62009-12-03 22:25:38 +00001258 </DIV>
1259 <DIV class=""><DIV class="stylepoint_body" name="Indentation__body" id="Indentation__body" style="display: none">
1260<SPAN class="link_button"><A href="?showone=Indentation#Indentation">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001261 link
1262 </A></SPAN>
1263 <p>
1264 Never use tabs or mix tabs and spaces.
1265 In cases of implied line continuation, you should align wrapped elements
1266 either vertically, as per the examples in the
1267 <a HREF="#Line_length">line length</a> section; or using a hanging
1268 indent of 4 spaces, in which case there should be no argument on
1269 the first line.
1270 </p>
1271
1272
mmentovai9ec7bd62009-12-03 22:25:38 +00001273<DIV class=""><PRE>Yes: # Aligned with opening delimiter
apicard@google.comf900c2c2009-07-23 20:09:56 +00001274 foo = long_function_name(var_one, var_two,
1275 var_three, var_four)
1276
1277 # 4-space hanging indent; nothing on first line
1278 foo = long_function_name(
1279 var_one, var_two, var_three,
mmentovai9ec7bd62009-12-03 22:25:38 +00001280 var_four)</PRE></DIV>
1281<DIV class=""><PRE class="badcode">No: <span class="external"></span># Stuff on first line forbidden
apicard@google.comf900c2c2009-07-23 20:09:56 +00001282 <span class="external"></span>foo = long_function_name(var_one, var_two,
1283 <span class="external"></span> var_three, var_four)
1284
1285 <span class="external"></span># 2-space hanging indent forbidden
1286 <span class="external"></span>foo = long_function_name(
1287 <span class="external"></span> var_one, var_two, var_three,
mmentovai9ec7bd62009-12-03 22:25:38 +00001288 <span class="external"></span> var_four)</PRE></DIV>
1289 </DIV></DIV>
1290 </DIV>
1291 <DIV class="">
1292<H3><A name="Blank_Lines" id="Blank_Lines">Blank Lines</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001293<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 +00001294 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001295 Two blank lines between top-level definitions, one blank line
1296 between method definitions.
mmentovai9ec7bd62009-12-03 22:25:38 +00001297 </DIV>
1298 <DIV class=""><DIV class="stylepoint_body" name="Blank_Lines__body" id="Blank_Lines__body" style="display: none">
1299<SPAN class="link_button"><A href="?showone=Blank_Lines#Blank_Lines">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001300 link
1301 </A></SPAN>
1302 <p>
1303 Two blank lines between top-level definitions, be they function
1304 or class definitions. One blank line between method definitions
1305 and between the <code>class</code> line and the first method.
1306 Use single blank lines as you judge appropriate within functions or
1307 methods.
1308 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001309 </DIV></DIV>
1310 </DIV>
1311 <DIV class="">
1312<H3><A name="Whitespace" id="Whitespace">Whitespace</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001313<SPAN class="showhide_button" onclick="javascript:ShowHideByName('Whitespace__body','Whitespace__button')" name="Whitespace__button" id="Whitespace__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001314 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001315 Follow standard typographic rules for the use of spaces around
1316 punctuation.
mmentovai9ec7bd62009-12-03 22:25:38 +00001317 </DIV>
1318 <DIV class=""><DIV class="stylepoint_body" name="Whitespace__body" id="Whitespace__body" style="display: none">
1319<SPAN class="link_button"><A href="?showone=Whitespace#Whitespace">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001320 link
1321 </A></SPAN>
1322 <p>
1323 No whitespace inside parentheses, brackets or braces.
1324 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001325<DIV class=""><PRE>Yes: <span class="external"></span>spam(ham[1], {eggs: 2}, [])</PRE></DIV>
1326<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 +00001327 <p>
1328 No whitespace before a comma, semicolon, or colon. Do use
1329 whitespace after a comma, semicolon, or colon except at the end
1330 of the line.
1331 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001332<DIV class=""><PRE>Yes: <span class="external"></span>if x == 4:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001333 <span class="external"> </span>print x, y
mmentovai9ec7bd62009-12-03 22:25:38 +00001334 <span class="external"></span>x, y = y, x</PRE></DIV>
1335<DIV class=""><PRE class="badcode">No: <span class="external"></span>if x == 4 :
apicard@google.comf900c2c2009-07-23 20:09:56 +00001336 <span class="external"> </span>print x , y
mmentovai9ec7bd62009-12-03 22:25:38 +00001337 <span class="external"></span>x , y = y , x</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001338 <p>
1339 No whitespace before the open paren/bracket that starts an argument list,
1340 indexing or slicing.
1341 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001342 <DIV class=""><PRE>Yes: <span class="external"></span>spam(1)</PRE></DIV>
1343<DIV class=""><PRE class="badcode">No: <span class="external"></span>spam (1)</PRE></DIV>
1344<DIV class=""><PRE>Yes: <span class="external"></span>dict['key'] = list[index]</PRE></DIV>
1345<DIV class=""><PRE class="badcode">No: <span class="external"></span>dict ['key'] = list [index]</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001346
1347 <p>
1348 Surround binary operators with a single space on either side for
1349 assignment (<code>=</code>), comparisons (<code>==, &lt;, &gt;, !=,
1350 &lt;&gt;, &lt;=, &gt;=, in, not in, is, is not</code>), and Booleans
1351 (<code>and, or, not</code>). Use your better judgment for the
1352 insertion of spaces around arithmetic operators but always be
1353 consistent about whitespace on either side of a binary operator.
1354 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001355<DIV class=""><PRE>Yes: <span class="external"></span>x == 1</PRE></DIV>
1356<DIV class=""><PRE class="badcode">No: <span class="external"></span>x&lt;1</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001357 <p>
1358 Don't use spaces around the '=' sign when used to indicate a
1359 keyword argument or a default parameter value.
1360 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001361<DIV class=""><PRE>Yes: <span class="external"></span>def complex(real, imag=0.0): return magic(r=real, i=imag)</PRE></DIV>
1362<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 +00001363
1364 <p>
1365 Don't use spaces to vertically align tokens on consecutive lines, since it
1366 becomes a maintenance burden (applies to <code>:</code>, <code>#</code>,
1367 <code>=</code>, etc.):
1368 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001369<DIV class=""><PRE>Yes:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001370 foo = 1000 # comment
1371 long_name = 2 # comment that should not be aligned
1372
1373 dictionary = {
1374 "foo": 1,
1375 "long_name": 2,
mmentovai9ec7bd62009-12-03 22:25:38 +00001376 }</PRE></DIV>
1377<DIV class=""><PRE class="badcode">No:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001378 foo = 1000 # comment
1379 long_name = 2 # comment that should not be aligned
1380
1381 dictionary = {
1382 "foo" : 1,
1383 "long_name": 2,
mmentovai9ec7bd62009-12-03 22:25:38 +00001384 }</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001385
1386
mmentovai9ec7bd62009-12-03 22:25:38 +00001387 </DIV></DIV>
1388 </DIV>
1389 <DIV class="">
1390<H3><A name="Python_Interpreter" id="Python_Interpreter">Python Interpreter</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001391<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 +00001392 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001393 Modules should begin with
1394
1395 <code>#!/usr/bin/env python&lt;version&gt;</code>
mmentovai9ec7bd62009-12-03 22:25:38 +00001396 </DIV>
1397 <DIV class=""><DIV class="stylepoint_body" name="Python_Interpreter__body" id="Python_Interpreter__body" style="display: none">
1398<SPAN class="link_button"><A href="?showone=Python_Interpreter#Python_Interpreter">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001399 link
1400 </A></SPAN>
1401 <p>
1402 Modules should begin with a "shebang" line specifying the Python
1403 interpreter used to execute the program:
1404 </p>
1405
mmentovai9ec7bd62009-12-03 22:25:38 +00001406<DIV class=""><PRE>
1407<span class="external"></span>#!/usr/bin/env python2.4</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001408
1409 <p>
1410 Always use the most specific version you can use, e.g.,
1411 <code>/usr/bin/python2.4</code>, not
1412 <code>/usr/bin/python2</code>. This makes it easier to find
1413 dependencies when
1414
1415 upgrading to a different Python version
1416 and also avoids confusion and breakage during use. E.g., Does
1417 <code>/usr/bin/python2</code> mean Python 2.0.1 or Python
1418 2.3.0?
1419 </p>
1420
mmentovai9ec7bd62009-12-03 22:25:38 +00001421 </DIV></DIV>
1422 </DIV>
1423 <DIV class="">
1424<H3><A name="Comments" id="Comments">Comments</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001425<SPAN class="showhide_button" onclick="javascript:ShowHideByName('Comments__body','Comments__button')" name="Comments__button" id="Comments__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001426 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001427 Be sure to use the right style for module, function, method and in-line
1428 comments.
mmentovai9ec7bd62009-12-03 22:25:38 +00001429 </DIV>
1430 <DIV class=""><DIV class="stylepoint_body" name="Comments__body" id="Comments__body" style="display: none">
1431<SPAN class="link_button"><A href="?showone=Comments#Comments">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001432 link
1433 </A></SPAN>
1434
1435 <P class="">
1436<SPAN class="stylepoint_subsection">Doc Strings</SPAN>
1437
1438 <p>
1439 Python has a unique commenting style using doc strings. A doc
1440 string is a string that is the first statement in a package,
1441 module, class or function. These strings can be extracted
1442 automatically through the <code>__doc__</code> member of the
1443 object and are used by <code>pydoc</code>. (Try running
1444 <code>pydoc</code> on your module to see how it looks.) Our
1445 convention for doc strings is to use the three double-quote
1446 format for strings. A doc string should be organized as a
1447 summary line (one physical line) terminated by a period,
1448 question mark, or exclamation point, followed by a blank line,
1449 followed by the rest of the doc string starting at the same
1450 cursor position as the first quote of the first line. There are
1451 more formatting guidelines for doc strings below.
1452 </p>
1453
1454 </P>
1455 <P class="">
1456<SPAN class="stylepoint_subsection">Modules</SPAN>
1457
1458
1459
1460 <p>
1461 Every file should contain the following items, in order:
1462 <ul>
1463 <li>a copyright statement (for example,
1464 <code>Copyright 2008 Google Inc.</code>)</li>
1465 <li>a license boilerplate. Choose the appropriate boilerplate
1466 for the license used by the project (for example, Apache 2.0, BSD,
1467 LGPL, GPL)</li>
1468 <li>an author line to identify the original author of the file</li>
1469 </ul>
1470 </p>
1471 </P>
1472 <P class="">
1473<SPAN class="stylepoint_subsection">Functions and Methods</SPAN>
1474
1475 <p>
1476 Any function or method which is not both obvious and very short
1477 needs a doc string. Additionally, any externally accessible
1478 function or method regardless of length or simplicity needs a
1479 doc string. The doc string should include what the function does
1480 and have detailed descriptions of the input and output. It
1481 should not, generally, describe how it does it unless it's some
1482 complicated algorithm. For tricky code block/inline comments
1483 within the code are more appropriate. The doc string should give
1484 enough information to write a call to the function without
1485 looking at a single line of the function's code. Args should be
1486 individually documented, an explanation following after a colon,
1487 and should use a uniform hanging indent of 2 or 4 spaces. The
1488 doc string should specify the expected types where specific types
1489 are required. A "Raises:" section should list all exceptions
1490 that can be raised by the function. The doc string for generator
1491 functions should use "Yields:" rather than "Returns:".
1492 </p>
1493
mmentovai9ec7bd62009-12-03 22:25:38 +00001494 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001495<span class="external"></span>def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
1496 <span class="external"> </span>"""Fetches rows from a Bigtable.
1497
1498 <span class="external"> </span>Retrieves rows pertaining to the given keys from the Table instance
1499 <span class="external"> </span>represented by big_table. Silly things may happen if
1500 <span class="external"> </span>other_silly_variable is not None.
1501
1502 <span class="external"> </span>Args:
1503 <span class="external"> </span>big_table: An open Bigtable Table instance.
1504 <span class="external"> </span>keys: A sequence of strings representing the key of each table row
1505 <span class="external"> </span> to fetch.
1506 <span class="external"> </span>other_silly_variable: Another optional variable, that has a much
1507 <span class="external"> </span> longer name than the other args, and which does nothing.
1508
1509 <span class="external"> </span>Returns:
1510 <span class="external"> </span>A dict mapping keys to the corresponding table row data
1511 <span class="external"> </span>fetched. Each row is represented as a tuple of strings. For
1512 <span class="external"> </span>example:
1513
1514 <span class="external"> </span>{'Serak': ('Rigel VII', 'Preparer'),
1515 <span class="external"> </span> 'Zim': ('Irk', 'Invader'),
1516 <span class="external"> </span> 'Lrrr': ('Omicron Persei 8', 'Emperor')}
1517
1518 <span class="external"> </span>If a key from the keys argument is missing from the dictionary,
1519 <span class="external"> </span>then that row was not found in the table.
1520
1521 <span class="external"> </span>Raises:
1522 <span class="external"> </span>IOError: An error occurred accessing the bigtable.Table object.
1523 <span class="external"> </span>"""
1524 <span class="external"> </span>pass
1525<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001526</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001527 </P>
1528 <P class="">
1529<SPAN class="stylepoint_subsection">Classes</SPAN>
1530
1531 <p>
1532 Classes should have a doc string below the class definition describing
1533 the class. If your class has public attributes, they should be documented
1534 here in an Attributes section and follow the same formatting as a
1535 function's Args section.
1536 </p>
1537
mmentovai9ec7bd62009-12-03 22:25:38 +00001538 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001539<span class="external"></span>class SampleClass(object):
1540 <span class="external"> </span>"""Summary of class here.
1541
1542 <span class="external"> </span>Longer class information....
1543 <span class="external"> </span>Longer class information....
1544
1545 <span class="external"> </span>Attributes:
1546 <span class="external"> </span>likes_spam: A boolean indicating if we like SPAM or not.
1547 <span class="external"> </span>eggs: An integer count of the eggs we have laid.
1548 <span class="external"> </span>"""
1549
1550 <span class="external"> </span>def __init__(self, likes_spam=False):
1551 <span class="external"> </span>"""Inits SampleClass with blah."""
1552 <span class="external"> </span>self.likes_spam = likes_spam
1553 <span class="external"> </span>self.eggs = 0
1554
1555 <span class="external"> </span>def public_method(self):
1556 <span class="external"> </span>"""Performs operation blah."""
1557<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001558</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001559
1560 </P>
1561 <P class="">
1562<SPAN class="stylepoint_subsection">Block and Inline Comments</SPAN>
1563
1564 <p>
1565 The final place to have comments is in tricky parts of the
1566 code. If you're going to have to explain it at the next
1567 <a HREF="http://en.wikipedia.org/wiki/Code_review">code review</a>,
1568 you should comment it now. Complicated operations get a few lines of
1569 comments before the operations
1570 commence. Non-obvious ones get comments at the end of the line.
1571 </p>
1572
mmentovai9ec7bd62009-12-03 22:25:38 +00001573 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001574<span class="external"></span># We use a weighted dictionary search to find out where i is in
1575<span class="external"></span># the array. We extrapolate position based on the largest num
1576<span class="external"></span># in the array and the array size and then do binary search to
1577<span class="external"></span># get the exact number.
1578
1579<span class="external"></span>if i &amp; (i-1) == 0: # true iff i is a power of 2
1580<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001581</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001582
1583 <p>
1584 To improve legibility, these comments should be at least 2 spaces away
1585 from the code.
1586 </p>
1587
1588 <p>
1589 On the other hand, never describe the code. Assume the person
1590 reading the code knows Python (though not what you're trying to
1591 do) better than you do.
1592 </p>
1593
mmentovai9ec7bd62009-12-03 22:25:38 +00001594 <DIV class=""><PRE class="badcode">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001595<span class="external"></span># BAD COMMENT: Now go through the b array and make sure whenever i occurs
1596<span class="external"></span># the next element is i+1
1597<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001598</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001599
1600 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001601 </DIV></DIV>
1602 </DIV>
1603 <DIV class="">
1604<H3><A name="Classes" id="Classes">Classes</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001605<SPAN class="showhide_button" onclick="javascript:ShowHideByName('Classes__body','Classes__button')" name="Classes__button" id="Classes__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001606 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001607 If a class inherits from no other base classes, explicitly inherit
1608 from <code>object</code>. This also applies to nested classes.
mmentovai9ec7bd62009-12-03 22:25:38 +00001609 </DIV>
1610 <DIV class=""><DIV class="stylepoint_body" name="Classes__body" id="Classes__body" style="display: none">
1611<SPAN class="link_button"><A href="?showone=Classes#Classes">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001612 link
1613 </A></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001614 <DIV class=""><PRE class="badcode">No: <span class="external"></span>class SampleClass:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001615 <span class="external"> </span>pass
1616
1617
1618 <span class="external"></span>class OuterClass:
1619
1620 <span class="external"> </span>class InnerClass:
1621 <span class="external"> </span>pass
1622<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001623</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001624
mmentovai9ec7bd62009-12-03 22:25:38 +00001625 <DIV class=""><PRE>Yes: <span class="external"></span>class SampleClass(object):
apicard@google.comf900c2c2009-07-23 20:09:56 +00001626 <span class="external"> </span>pass
1627
1628
1629 <span class="external"></span>class OuterClass(object):
1630
1631 <span class="external"> </span>class InnerClass(object):
1632 <span class="external"> </span>pass
1633
1634
1635 <span class="external"></span>class ChildClass(ParentClass):
1636 <span class="external"> </span>"""Explicitly inherits from another class already."""
1637<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001638</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001639
1640 <p>Inheriting from <code>object</code> is needed to make properties work
1641 properly, and it will protect your code from one particular potential
1642 incompatibility with Python 3000. It also defines
1643 special methods that implement the default semantics of objects including
1644 <code>__new__</code>, <code>__init__</code>, <code>__delattr__</code>,
1645 <code>__getattribute__</code>, <code>__setattr__</code>,
1646 <code>__hash__</code>, <code>__repr__</code>, and <code>__str__</code>.
1647 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001648 </DIV></DIV>
1649 </DIV>
1650 <DIV class="">
1651<H3><A name="Strings" id="Strings">Strings</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001652<SPAN class="showhide_button" onclick="javascript:ShowHideByName('Strings__body','Strings__button')" name="Strings__button" id="Strings__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001653 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001654 Use the <code>%</code> operator for formatting strings,
1655 even when the parameters are all strings. Use your best judgement
1656 to decide between <code>+</code> and <code>%</code> though.
mmentovai9ec7bd62009-12-03 22:25:38 +00001657 </DIV>
1658 <DIV class=""><DIV class="stylepoint_body" name="Strings__body" id="Strings__body" style="display: none">
1659<SPAN class="link_button"><A href="?showone=Strings#Strings">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001660 link
1661 </A></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001662<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 +00001663 <span class="external"></span>x = imperative + ', ' + expletive + '!'
mmentovai9ec7bd62009-12-03 22:25:38 +00001664 <span class="external"></span>x = 'name: ' + name + '; score: ' + str(n)</PRE></DIV>
1665<DIV class=""><PRE>Yes: <span class="external"></span>x = a + b
apicard@google.comf900c2c2009-07-23 20:09:56 +00001666 <span class="external"></span>x = '%s, %s!' % (imperative, expletive)
mmentovai9ec7bd62009-12-03 22:25:38 +00001667 <span class="external"></span>x = 'name: %s; score: %d' % (name, n)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001668
1669 <p>
1670 Avoid using the <code>+</code> and <code>+=</code> operators to
1671 accumulate a string within a loop. Since strings are immutable, this
1672 creates unnecessary temporary objects and results in quadratic rather
1673 than linear running time. Instead, add each substring to a list and
1674 <code>''.join</code> the list after the loop terminates (or, write each
1675 substring to a <code>cStringIO.StringIO</code> buffer).
1676 </p>
1677
mmentovai9ec7bd62009-12-03 22:25:38 +00001678<DIV class=""><PRE class="badcode">No: <span class="external"></span>employee_table = '&lt;table&gt;'
apicard@google.comf900c2c2009-07-23 20:09:56 +00001679 <span class="external"></span>for last_name, first_name in employee_list:
1680 <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 +00001681 <span class="external"></span>employee_table += '&lt;/table&gt;'</PRE></DIV>
1682<DIV class=""><PRE>Yes: <span class="external"></span>items = ['&lt;table&gt;']
apicard@google.comf900c2c2009-07-23 20:09:56 +00001683 <span class="external"></span>for last_name, first_name in employee_list:
1684 <span class="external"> </span>items.append('&lt;tr&gt;&lt;td&gt;%s, %s&lt;/td&gt;&lt;/tr&gt;' % (last_name, first_name))
1685 <span class="external"></span>items.append('&lt;/table&gt;')
mmentovai9ec7bd62009-12-03 22:25:38 +00001686 <span class="external"></span>employee_table = ''.join(items)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001687
1688 <p>
1689 Use <code>"""</code> for multi-line strings rather than
1690 <code>'''</code>. Note, however, that it is often cleaner to
1691 use implicit line joining since multi-line strings do
1692 not flow with the indentation of the rest of the program:
1693 </p>
1694
mmentovai9ec7bd62009-12-03 22:25:38 +00001695 <DIV class=""><PRE class="badcode"> No<span class="external"></span>:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001696 <span class="external"></span>print """This is pretty ugly.
1697Don'<span class="external"></span>t do this.
1698"""<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001699</PRE></DIV>
1700<DIV class=""><PRE>Ye<span class="external"></span>s:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001701 <span class="external"></span>print ("This is much nicer.\n"
mmentovai9ec7bd62009-12-03 22:25:38 +00001702 <span class="external"></span> "Do it this way.\n")</PRE></DIV>
1703 </DIV></DIV>
1704 </DIV>
1705 <DIV class="">
1706<H3><A name="TODO_Comments" id="TODO_Comments">TODO Comments</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001707<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 +00001708 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001709 Use <code>TODO</code> comments for code that is temporary, a
1710 short-term solution, or good-enough but not perfect.
mmentovai9ec7bd62009-12-03 22:25:38 +00001711 </DIV>
1712 <DIV class=""><DIV class="stylepoint_body" name="TODO_Comments__body" id="TODO_Comments__body" style="display: none">
1713<SPAN class="link_button"><A href="?showone=TODO_Comments#TODO_Comments">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001714 link
1715 </A></SPAN>
1716 <p>
1717 <code>TODO</code>s should include the string <code>TODO</code> in
1718 all caps, followed by your
1719
1720 name, e-mail address, or other
1721 identifier
1722 in parentheses. A colon is optional. A comment explaining what there
1723 is to do is required. The main purpose is to have
1724 a consistent <code>TODO</code> format searchable by the person
1725 adding the comment (who can provide more details upon request). A
1726 <code>TODO</code> is not a commitment to provide the fix yourself.
1727 </p>
1728
mmentovai9ec7bd62009-12-03 22:25:38 +00001729 <DIV class=""><PRE># TODO(kl@gmail.com): Drop the use of "has_key".
1730# TODO(Zeke) change this to use relations.</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001731 <p>
1732 If your <code>TODO</code> is of the form "At a future date do
1733 something" make sure that you either include a very specific
1734 date ("Fix by November 2009") or a very specific event
1735 ("Remove this code when all clients can handle XML responses.").
1736 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001737 </DIV></DIV>
1738 </DIV>
1739 <DIV class="">
1740<H3><A name="Imports_formatting" id="Imports_formatting">Imports formatting</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001741<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 +00001742 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001743 Imports should be on separate lines.
mmentovai9ec7bd62009-12-03 22:25:38 +00001744 </DIV>
1745 <DIV class=""><DIV class="stylepoint_body" name="Imports_formatting__body" id="Imports_formatting__body" style="display: none">
1746<SPAN class="link_button"><A href="?showone=Imports_formatting#Imports_formatting">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001747 link
1748 </A></SPAN>
1749 <p>
1750 E.g.:
1751 </p>
1752
mmentovai9ec7bd62009-12-03 22:25:38 +00001753<DIV class=""><PRE>Yes: <span class="external"></span>import os
1754 <span class="external"></span>import sys</PRE></DIV>
1755<DIV class=""><PRE class="badcode">No: <span class="external"></span>import os, sys</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001756 <p>
1757 Imports are always put at the top of the file, just after any
1758 module comments and doc strings and before module globals and
1759 constants. Imports should be grouped with the order being most generic
1760 to least generic:
1761 </p>
1762 <ul>
1763 <li>standard library imports</li>
1764 <li>third-party imports</li>
1765
1766 <li>application-specific imports</li>
1767 </ul>
1768 <p>
1769 Within each grouping, imports should be sorted lexicographically,
1770 ignoring case, according to each module's full package path.
1771 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001772 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001773<span class="external"></span>import foo
1774<span class="external"></span>from foo import bar
1775<span class="external"></span>from foo.bar import baz
1776<span class="external"></span>from foo.bar import Quux
mmentovai9ec7bd62009-12-03 22:25:38 +00001777<span class="external"></span>from Foob import ar</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001778
1779
mmentovai9ec7bd62009-12-03 22:25:38 +00001780
1781 </DIV></DIV>
1782 </DIV>
1783 <DIV class="">
1784<H3><A name="Statements" id="Statements">Statements</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001785<SPAN class="showhide_button" onclick="javascript:ShowHideByName('Statements__body','Statements__button')" name="Statements__button" id="Statements__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001786 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001787 Generally only one statement per line.
mmentovai9ec7bd62009-12-03 22:25:38 +00001788 </DIV>
1789 <DIV class=""><DIV class="stylepoint_body" name="Statements__body" id="Statements__body" style="display: none">
1790<SPAN class="link_button"><A href="?showone=Statements#Statements">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001791 link
1792 </A></SPAN>
1793 <p>
1794 However, you may put the
1795 result of a test on the same line as the test only if the entire
1796 statement fits on one line. In particular, you can never do so
1797 with <code>try</code>/<code>except</code> since the
1798 <code>try</code> and <code>except</code> can't both fit on the
1799 same line, and you can only do so with an <code>if</code> if
1800 there is no <code>else</code>.
1801 </p>
1802
mmentovai9ec7bd62009-12-03 22:25:38 +00001803 <DIV class=""><PRE>Ye<span class="external"></span>s:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001804
mmentovai9ec7bd62009-12-03 22:25:38 +00001805 <span class="external"></span>if foo: bar(foo)</PRE></DIV>
1806<DIV class=""><PRE class="badcode">No<span class="external"></span>:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001807
1808 <span class="external"></span>if foo: bar(foo)
1809 <span class="external"></span>else: baz(foo)
1810
1811 <span class="external"></span>try: bar(foo)
1812 <span class="external"></span>except ValueError: baz(foo)
1813
1814 <span class="external"></span>try:
1815 <span class="external"> </span>bar(foo)
1816 <span class="external"></span>except ValueError: baz(foo)
1817<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001818</PRE></DIV>
1819 </DIV></DIV>
1820 </DIV>
1821 <DIV class="">
1822<H3><A name="Access_Control" id="Access_Control">Access Control</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001823<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 +00001824 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001825 If an accessor function would be trivial you should use public variables
1826 instead of accessor functions to avoid the extra cost of function
1827 calls in Python. When more functionality is added you can use
1828 <code>property</code> to keep the syntax consistent.
mmentovai9ec7bd62009-12-03 22:25:38 +00001829 </DIV>
1830 <DIV class=""><DIV class="stylepoint_body" name="Access_Control__body" id="Access_Control__body" style="display: none">
1831<SPAN class="link_button"><A href="?showone=Access_Control#Access_Control">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001832 link
1833 </A></SPAN>
1834 <p>
1835 On the other hand, if access is more complex, or the cost of accessing
1836 the variable is significant, you should use function calls (following the
1837 <a HREF="#naming">Naming</a> guidelines) such as <code>get_foo()</code>
1838 and <code>set_foo()</code>. If the past behavior allowed access through a
1839 property, do not bind the new accessor functions to the property. Any
1840 code still attempting to access the variable by the old method should
1841 break visibly so they are made aware of the change in complexity.
1842 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001843 </DIV></DIV>
1844 </DIV>
1845 <DIV class="">
1846<H3><A name="Naming" id="Naming">Naming</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001847<SPAN class="showhide_button" onclick="javascript:ShowHideByName('Naming__body','Naming__button')" name="Naming__button" id="Naming__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001848 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001849 <code>module_name, package_name, ClassName, method_name, ExceptionName,
1850 function_name, GLOBAL_VAR_NAME, instance_var_name,
1851 function_parameter_name, local_var_name.</code>
mmentovai9ec7bd62009-12-03 22:25:38 +00001852 </DIV>
1853 <DIV class=""><DIV class="stylepoint_body" name="Naming__body" id="Naming__body" style="display: none">
1854<SPAN class="link_button"><A href="?showone=Naming#Naming">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001855 link
1856 </A></SPAN>
1857 <P class="">
1858<SPAN class="stylepoint_subsection">Names to Avoid</SPAN>
1859
1860 <ul>
1861 <li>single character names except for counters or iterators</li>
1862 <li>dashes (<code>-</code>) in any package/module name</li>
1863 <li>
1864<code>__double_leading_and_trailing_underscore__</code> names
1865 (reserved by Python)</li>
1866 </ul>
1867
1868 </P>
1869 <P class="">
1870<SPAN class="stylepoint_subsection">Naming Convention</SPAN>
1871
1872 <ul>
1873 <li>
1874 "Internal" means internal to a module or protected
1875 or private within a class.</li>
1876 <li>
1877 Prepending a single underscore (<code>_</code>) has some
1878 support for protecting module variables and functions (not included
1879 with <code>import * from</code>). Prepending a double underscore
1880 (<code>__</code>) to an instance variable or method
1881 effectively serves to make the variable or method private to its class
1882 (using name mangling).</li>
1883 <li>
1884 Place related classes and top-level functions together in a
1885 module. Unlike Java,
1886 there is no need to limit yourself to one class per module.</li>
1887 <li>
1888 Use CapWords for class names, but lower_with_under.py for module names.
1889 Although there are many existing modules named CapWords.py, this is now
1890 discouraged because it's confusing when the module happens to be
1891 named after a class. ("wait -- did I write
1892 <code>import StringIO</code> or <code>from StringIO import
1893 StringIO</code>?")</li>
1894 </ul>
1895
1896 </P>
1897 <P class="">
1898<SPAN class="stylepoint_subsection">Guidelines derived from Guido's Recommendations</SPAN>
1899
1900 <table rules="all" border="1" cellspacing="2" cellpadding="2">
1901
1902 <tr>
1903 <th>Type</th>
1904 <th>Public</th>
1905 <th>Internal</th>
1906 </tr>
1907
1908
1909
1910 <tr>
1911 <td>Packages</td>
1912 <td><code>lower_with_under</code></td>
1913 <td></td>
1914 </tr>
1915
1916 <tr>
1917 <td>Modules</td>
1918 <td><code>lower_with_under</code></td>
1919 <td><code>_lower_with_under</code></td>
1920 </tr>
1921
1922 <tr>
1923 <td>Classes</td>
1924 <td><code>CapWords</code></td>
1925 <td><code>_CapWords</code></td>
1926 </tr>
1927
1928 <tr>
1929 <td>Exceptions</td>
1930 <td><code>CapWords</code></td>
1931 <td></td>
1932 </tr>
1933
1934
1935
1936 <tr>
1937 <td>Functions</td>
1938 <td><code>lower_with_under()</code></td>
1939 <td><code>_lower_with_under()</code></td>
1940 </tr>
1941
1942 <tr>
1943 <td>Global/Class Constants</td>
1944 <td><code>CAPS_WITH_UNDER</code></td>
1945 <td><code>_CAPS_WITH_UNDER</code></td>
1946 </tr>
1947
1948 <tr>
1949 <td>Global/Class Variables</td>
1950 <td><code>lower_with_under</code></td>
1951 <td><code>_lower_with_under</code></td>
1952 </tr>
1953
1954 <tr>
1955 <td>Instance Variables</td>
1956 <td><code>lower_with_under</code></td>
1957 <td><code>_lower_with_under (protected) or __lower_with_under (private)</code></td>
1958 </tr>
1959
1960
1961
1962 <tr>
1963 <td>Method Names</td>
1964 <td><code>lower_with_under()</code></td>
1965 <td><code>_lower_with_under() (protected) or __lower_with_under() (private)</code></td>
1966 </tr>
1967
1968 <tr>
1969 <td>Function/Method Parameters</td>
1970 <td><code>lower_with_under</code></td>
1971 <td></td>
1972 </tr>
1973
1974 <tr>
1975 <td>Local Variables</td>
1976 <td><code>lower_with_under</code></td>
1977 <td></td>
1978 </tr>
1979
1980
1981 </table>
1982
1983
1984 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001985 </DIV></DIV>
1986 </DIV>
1987 <DIV class="">
1988<H3><A name="Main" id="Main">Main</A></H3>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001989<SPAN class="showhide_button" onclick="javascript:ShowHideByName('Main__body','Main__button')" name="Main__button" id="Main__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001990 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001991 Even a file meant to be used as a script should be importable and a
1992 mere import should not have the side effect of executing the script's
1993 main functionality. The main functionality should be in a main()
1994 function.
mmentovai9ec7bd62009-12-03 22:25:38 +00001995 </DIV>
1996 <DIV class=""><DIV class="stylepoint_body" name="Main__body" id="Main__body" style="display: none">
1997<SPAN class="link_button"><A href="?showone=Main#Main">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001998 link
1999 </A></SPAN>
2000 <p>
2001 In Python,
2002 <code>pychecker</code>, <code>pydoc</code>, and unit tests
2003 require modules to be importable. Your code should always check
2004 <code>if __name__ == '__main__'</code> before executing your
2005 main program so that the main program is not executed when the
2006 module is imported.
2007
2008 </p>
2009
2010
2011
2012
2013
2014
2015
mmentovai9ec7bd62009-12-03 22:25:38 +00002016 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002017<span class="external"></span>def main():
2018 <span class="external"> </span>...
2019
2020<span class="external"></span>if __name__ == '__main__':
2021 <span class="external"> </span>main()
2022<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00002023</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002024
2025 <p>
2026 All code at the top level will be executed when the module is
2027 imported. Be careful not to call functions, create objects, or
2028 perform other operations that should not be executed when the
2029 file is being <code>pycheck</code>ed or <code>pydoc</code>ed.
2030 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00002031 </DIV></DIV>
2032 </DIV>
2033 </DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002034
2035<H2>Parting Words</H2>
2036 <p>
2037 <em>BE CONSISTENT</em>.
2038 </p>
2039
2040 <p>
2041 If you're editing code, take a few minutes to look at the code
2042 around you and determine its style. If they use spaces around
2043 all their arithmetic operators, you should too. If their
2044 comments have little boxes of hash marks around them, make your
2045 comments have little boxes of hash marks around them too.
2046 </p>
2047
2048 <p>
2049 The point of having style guidelines is to have a common vocabulary
2050 of coding so people can concentrate on what you're saying rather
2051 than on how you're saying it. We present global style rules here so
2052 people know the vocabulary, but local style is also important. If
2053 code you add to a file looks drastically different from the existing
2054 code around it, it throws readers out of their rhythm when they go to
2055 read it. Avoid this.
2056 </p>
2057
2058
2059
2060<p align="right">
mmentovai9ec7bd62009-12-03 22:25:38 +00002061Revision 2.15
apicard@google.comf900c2c2009-07-23 20:09:56 +00002062</p>
2063
2064
2065<address>
2066 Amit Patel<br>
2067 Antoine Picard<br>
2068 Eugene Jhong<br>
2069 Jeremy Hylton<br>
2070 Matt Smart<br>
2071 Mike Shields<br>
2072</address>
2073</BODY>
2074</HTML>