blob: 475cebffd116f4e8ba57d38376ae4a023c43608c [file] [log] [blame]
mmentovaif7facf92009-10-23 21:01:49 +00001<HTML xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcq="http://purl.org/dc/qualifiers/1.0/" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:fn="http://www.w3.org/2005/xpath-functions">
apicard@google.comf900c2c2009-07-23 20:09:56 +00002<HEAD>
apicard@google.comf900c2c2009-07-23 20:09:56 +00003<TITLE>Google Python Style Guide</TITLE>
mmentovaib729e3c2010-08-10 18:40:41 +00004<META http-equiv="Content-Type" content="text/html; charset=utf-8">
apicard@google.comf900c2c2009-07-23 20:09:56 +00005<LINK HREF="http://www.google.com/favicon.ico" type="image/x-icon" rel="shortcut icon">
6<LINK HREF="styleguide.css" type="text/css" rel="stylesheet">
7<SCRIPT language="javascript" type="text/javascript">
8
9 function ShowHideByName(bodyName, buttonName) {
10 var bodyElements;
mmentovai8411f0c2010-08-04 17:46:16 +000011 var linkElement;
apicard@google.comf900c2c2009-07-23 20:09:56 +000012 if (document.getElementsByName) {
13 bodyElements = document.getElementsByName(bodyName);
mmentovai8411f0c2010-08-04 17:46:16 +000014 linkElement = document.getElementsByName('link-' + buttonName)[0];
apicard@google.comf900c2c2009-07-23 20:09:56 +000015 } else {
16 bodyElements = [document.getElementById(bodyName)];
mmentovai8411f0c2010-08-04 17:46:16 +000017 linkElement = document.getElementById('link-' + buttonName);
apicard@google.comf900c2c2009-07-23 20:09:56 +000018 }
19 if (bodyElements.length != 1) {
20 alert("ShowHideByName() got the wrong number of bodyElements: " + bodyElements.length);
21 } else {
22 var bodyElement = bodyElements[0];
23 var buttonElement;
24 if (document.getElementsByName) {
25 var buttonElements = document.getElementsByName(buttonName);
26 buttonElement = buttonElements[0];
27 } else {
28 buttonElement = document.getElementById(buttonName);
29 }
30 if (bodyElement.style.display == "none" || bodyElement.style.display == "") {
31 bodyElement.style.display = "inline";
mmentovai8411f0c2010-08-04 17:46:16 +000032 linkElement.style.display = "block";
apicard@google.comf900c2c2009-07-23 20:09:56 +000033 buttonElement.innerHTML = '▽';
34 } else {
35 bodyElement.style.display = "none";
mmentovai8411f0c2010-08-04 17:46:16 +000036 linkElement.style.display = "none";
apicard@google.comf900c2c2009-07-23 20:09:56 +000037 buttonElement.innerHTML = '▶';
38 }
39 }
40 }
41
42 function ShowHideAll() {
43 var allButton;
44 if (document.getElementsByName) {
45 var allButtons = document.getElementsByName("show_hide_all_button");
46 allButton = allButtons[0];
47 } else {
48 allButton = document.getElementById("show_hide_all_button");
49 }
50 if (allButton.innerHTML == '▽') {
51 allButton.innerHTML = '▶';
52 SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "none", '▶');
53 } else {
54 allButton.innerHTML = '▽';
55 SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "inline", '▽');
56 }
57 }
58
59 // Recursively sets state of all children
60 // of a particular node.
61 function SetHiddenState(root, newState, newButton) {
62 for (var i = 0; i != root.length; i++) {
63 SetHiddenState(root[i].childNodes, newState, newButton);
64 if (root[i].className == 'showhide_button') {
65 root[i].innerHTML = newButton;
66 }
mmentovai8411f0c2010-08-04 17:46:16 +000067 if (root[i].className == 'stylepoint_body' ||
68 root[i].className == 'link_button') {
apicard@google.comf900c2c2009-07-23 20:09:56 +000069 root[i].style.display = newState;
70 }
71 }
72 }
73
74
75 window.onload = function() {
76 // if the URL contains "?showall=y", expand the details of all children
77 {
78 var showHideAllRegex = new RegExp("[\\?&](showall)=([^&#]*)");
79 var showHideAllValue = showHideAllRegex.exec(window.location.href);
80 if (showHideAllValue != null) {
81 if (showHideAllValue[2] == "y") {
82 SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "inline", '▽');
83 } else {
84 SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "none", '▶');
85 }
86 }
87 var showOneRegex = new RegExp("[\\?&](showone)=([^&#]*)");
88 var showOneValue = showOneRegex.exec(window.location.href);
89 if (showOneValue != null) {
90 var body_name = showOneValue[2] + '__body';
91 var button_name = showOneValue[2] + '__button';
92 ShowHideByName(body_name, button_name);
93 }
94
95 }
96 }
97 </SCRIPT>
98</HEAD>
99<BODY>
100<H1>Google Python Style Guide</H1>
101 <p align="right">
102
mmentovaicd4ce0f2011-03-29 20:30:47 +0000103 Revision 2.20
apicard@google.comf900c2c2009-07-23 20:09:56 +0000104 </p>
105
106 <address>
107 Amit Patel<br>
108 Antoine Picard<br>
109 Eugene Jhong<br>
110 Jeremy Hylton<br>
111 Matt Smart<br>
112 Mike Shields<br>
113 </address>
114 <DIV style="margin-left: 50%; font-size: 75%;">
115<P>
116 Each style point has a summary for which additional information is available
117 by toggling the accompanying arrow button that looks this way:
mmentovai8411f0c2010-08-04 17:46:16 +0000118 <SPAN class="showhide_button" style="margin-left: 0; float: none"></SPAN>.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000119 You may toggle all summaries with the big arrow button:
120 </P>
121<DIV style=" font-size: larger; margin-left: +2em;">
mmentovai8411f0c2010-08-04 17:46:16 +0000122<SPAN class="showhide_button" style="font-size: 180%; float: none" onclick="javascript:ShowHideAll()" name="show_hide_all_button" id="show_hide_all_button"></SPAN>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000123 Toggle all summaries
124 </DIV>
125</DIV>
126<DIV class="toc">
127<DIV class="toc_title">Table of Contents</DIV>
128<TABLE>
129<TR valign="top" class="">
130<TD><DIV class="toc_category"><A href="#Python_Language_Rules">Python Language Rules</A></DIV></TD>
131<TD><DIV class="toc_stylepoint">
mmentovaif7facf92009-10-23 21:01:49 +0000132<SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#pychecker">pychecker</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Imports">Imports</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Packages">Packages</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Exceptions">Exceptions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Global_variables">Global variables</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Nested/Local/Inner_Classes_and_Functions">Nested/Local/Inner Classes and Functions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#List_Comprehensions">List Comprehensions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Default_Iterators_and_Operators">Default Iterators and Operators</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Generators">Generators</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Lambda_Functions">Lambda Functions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Default_Argument_Values">Default Argument Values</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Properties">Properties</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#True/False_evaluations">True/False evaluations</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Deprecated_Language_Features">Deprecated Language Features</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Lexical_Scoping">Lexical Scoping</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Function_and_Method_Decorators">Function and Method Decorators</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Threading">Threading</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Power_Features">Power Features</A></SPAN> </DIV></TD>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000133</TR>
134<TR valign="top" class="">
135<TD><DIV class="toc_category"><A href="#Python_Style_Rules">Python Style Rules</A></DIV></TD>
136<TD><DIV class="toc_stylepoint">
mmentovaicd4ce0f2011-03-29 20:30:47 +0000137<SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Semicolons">Semicolons</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Line_length">Line length</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Parentheses">Parentheses</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Indentation">Indentation</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Blank_Lines">Blank Lines</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Whitespace">Whitespace</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Shebang_Line">Shebang Line</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Comments">Comments</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Classes">Classes</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Strings">Strings</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#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>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000138</TR>
139</TABLE>
140</DIV>
mmentovai9ec7bd62009-12-03 22:25:38 +0000141 <DIV class="">
142<H2 name="Important_Note" id="Important_Note">Important Note</H2>
143 <DIV class="">
144<H3><A name="Displaying_Hidden_Details_in_this_Guide" id="Displaying_Hidden_Details_in_this_Guide">Displaying Hidden Details in this Guide</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000145<SPAN class="link_button" id="link-Displaying_Hidden_Details_in_this_Guide__button" name="link-Displaying_Hidden_Details_in_this_Guide__button"><A href="?showone=Displaying_Hidden_Details_in_this_Guide#Displaying_Hidden_Details_in_this_Guide">
146 link
147 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Displaying_Hidden_Details_in_this_Guide__body','Displaying_Hidden_Details_in_this_Guide__button')" name="Displaying_Hidden_Details_in_this_Guide__button" id="Displaying_Hidden_Details_in_this_Guide__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000148 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000149 This style guide contains many details that are initially
150 hidden from view. They are marked by the triangle icon, which you
151 see here on your left. Click it now.
152 You should see "Hooray" appear below.
mmentovai9ec7bd62009-12-03 22:25:38 +0000153 </DIV>
154 <DIV class=""><DIV class="stylepoint_body" name="Displaying_Hidden_Details_in_this_Guide__body" id="Displaying_Hidden_Details_in_this_Guide__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000155 <p>
156 Hooray! Now you know you can expand points to get more
157 details. Alternatively, there's a "toggle all" at the
158 top of this document.
159 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000160 </DIV></DIV>
161 </DIV>
162 </DIV>
163 <DIV class="">
164<H2 name="Background" id="Background">Background</H2>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000165 <p>
166 Python is the main scripting language used at Google. This
167 style guide is a list of <em>do</em>s and <em>don't</em>s for Python
168 programs.
169 </p>
170
mshields@google.com222e6da2010-11-29 20:32:06 +0000171 <p>
172 To help you format code correctly, we've created a <a href="google_python_style.vim">settings
173 file for Vim</a>. For Emacs, the default settings should be fine.
174 </p>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000175
176
mmentovai9ec7bd62009-12-03 22:25:38 +0000177 </DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000178
mmentovai9ec7bd62009-12-03 22:25:38 +0000179 <DIV class="">
180<H2 name="Python_Language_Rules" id="Python_Language_Rules">Python Language Rules</H2>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000181
mmentovai9ec7bd62009-12-03 22:25:38 +0000182 <DIV class="">
183<H3><A name="pychecker" id="pychecker">pychecker</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000184<SPAN class="link_button" id="link-pychecker__button" name="link-pychecker__button"><A href="?showone=pychecker#pychecker">
185 link
186 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('pychecker__body','pychecker__button')" name="pychecker__button" id="pychecker__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000187 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000188 Run <code>pychecker</code> over your code.
mmentovai9ec7bd62009-12-03 22:25:38 +0000189 </DIV>
mmentovai8411f0c2010-08-04 17:46:16 +0000190 <DIV class=""><DIV class="stylepoint_body" name="pychecker__body" id="pychecker__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000191 <P class="">
192<SPAN class="stylepoint_section">Definition: </SPAN>
193 PyChecker is a tool for finding bugs in Python source code. It finds
194 problems that are typically caught by a compiler for less dynamic
195 languages like C and C++. It is similar to lint. Because of the
196 dynamic nature of Python, some warnings may be incorrect; however,
197 spurious warnings should be fairly infrequent.
198 </P>
199 <P class="">
200<SPAN class="stylepoint_section">Pros: </SPAN>
201 Catches easy-to-miss errors like typos, use-vars-before-assignment, etc.
202 </P>
203 <P class="">
204<SPAN class="stylepoint_section">Cons: </SPAN>
205 <code>pychecker</code> isn't perfect. To take
206 advantage of it, we'll need to sometimes: a) Write around it b)
207 Suppress its warnings c) Improve it or d) Ignore it.
208 </P>
209 <P class="">
210<SPAN class="stylepoint_section">Decision: </SPAN>
211 Make sure you run <code>pychecker</code> on your code.
212 </P>
213
214 <p>
215 For information on how to run <code>pychecker</code>, see the
216 <a HREF="http://pychecker.sourceforge.net">pychecker
217 homepage</a>
218 </p>
219 <p>
220 To suppress warnings, you can set a module-level variable named
221 <code>__pychecker__</code> to suppress appropriate warnings.
222 For example:
223 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000224 <DIV class=""><PRE>
225<span class="external"></span>__pychecker__ = 'no-callinit no-classattr'</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000226 <p>
227 Suppressing in this way has the advantage that we can easily search
228 for suppressions and revisit them.
229 </p>
230 <p>
231 You can get a list of pychecker warnings by doing
232 <code>pychecker --help</code>.
233 </p>
234 <p>
235 Unused argument warnings can be suppressed by using `_' as the
236 identifier for the unused argument or prefixing the argument name with
237 `unused_'. In situations where changing the argument names is
238 infeasible, you can mention them at the beginning of the function.
239 For example:
240 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000241 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000242<span class="external"></span>def foo(a, unused_b, unused_c, d=None, e=None):
243 <span class="external"> </span>(d, e) = (d, e) # Silence pychecker
244 <span class="external"> </span>return a
245<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000246</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000247 <p>
248 Ideally, pychecker would be extended to ensure that such `unused
249 declarations' were true.
250 </p>
251
mmentovai9ec7bd62009-12-03 22:25:38 +0000252 </DIV></DIV>
253 </DIV>
254 <DIV class="">
255<H3><A name="Imports" id="Imports">Imports</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000256<SPAN class="link_button" id="link-Imports__button" name="link-Imports__button"><A href="?showone=Imports#Imports">
257 link
258 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Imports__body','Imports__button')" name="Imports__button" id="Imports__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000259 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000260 Use <code>import</code>s for packages and modules only.
mmentovai9ec7bd62009-12-03 22:25:38 +0000261 </DIV>
262 <DIV class=""><DIV class="stylepoint_body" name="Imports__body" id="Imports__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000263 <P class="">
264<SPAN class="stylepoint_section">Definition: </SPAN>
265 Reusability mechanism for sharing code from one module to another.
266 </P>
267 <P class="">
268<SPAN class="stylepoint_section">Pros: </SPAN>
mmentovaidb989ec2010-11-23 18:02:36 +0000269 The namespace management convention is simple. The source of each
270 identifier is indicated in a consistent way; <code>x.Obj</code> says
271 that object <code>Obj</code> is defined in module <code>x</code>.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000272 </P>
273 <P class="">
mmentovaidb989ec2010-11-23 18:02:36 +0000274<SPAN class="stylepoint_section">Cons: </SPAN> Module names can still collide. Some module names are
275 inconveniently long.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000276 </P>
277 <P class="">
278<SPAN class="stylepoint_section">Decision: </SPAN>
mmentovaidb989ec2010-11-23 18:02:36 +0000279 Use <code>import x</code> for importing packages and modules.
280 <br>
281 Use <code>from x import y</code> where <code>x</code> is
282 the package prefix and <code>y</code> is the module name with no
283 prefix.
284 <br>
285 Use <code>from x import y as z</code> if two modules named
286 <code>z</code> are to be imported or if <code>y</code> is an
287 inconveniently long name.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000288 </P>
mmentovaidb989ec2010-11-23 18:02:36 +0000289 For example the module
290 <code>sound.effects.echo</code> may be imported as follows:
mmentovai9ec7bd62009-12-03 22:25:38 +0000291 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000292<span class="external"></span>from sound.effects import echo
293<span class="external"></span>...
mmentovaidb989ec2010-11-23 18:02:36 +0000294<span class="external"></span>echo.EchoFilter(input, output, delay=0.7, atten=4)
apicard@google.comf900c2c2009-07-23 20:09:56 +0000295<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000296</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000297 <p>
mmentovaidb989ec2010-11-23 18:02:36 +0000298 Do not use relative names in imports. Even if the module is in the
299 same package, use the full package name. This helps prevent
300 unintentionally importing a package twice.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000301 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000302 </DIV></DIV>
303 </DIV>
304 <DIV class="">
305<H3><A name="Packages" id="Packages">Packages</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000306<SPAN class="link_button" id="link-Packages__button" name="link-Packages__button"><A href="?showone=Packages#Packages">
307 link
308 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Packages__body','Packages__button')" name="Packages__button" id="Packages__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000309 <DIV style="display:inline;" class="">
mmentovaidb989ec2010-11-23 18:02:36 +0000310 Import each module using the full pathname location of the module.
mmentovai9ec7bd62009-12-03 22:25:38 +0000311 </DIV>
312 <DIV class=""><DIV class="stylepoint_body" name="Packages__body" id="Packages__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000313 <P class="">
314<SPAN class="stylepoint_section">Pros: </SPAN>
315 Avoids conflicts in module names. Makes it easier to find modules.
316 </P>
317 <P class="">
318<SPAN class="stylepoint_section">Cons: </SPAN>
319 Makes it harder to deploy code because you have to replicate the
320 package hierarchy.
321 </P>
322 <P class="">
323<SPAN class="stylepoint_section">Decision: </SPAN>
mmentovaidb989ec2010-11-23 18:02:36 +0000324 All new code should import each module by its full package name.
325
apicard@google.comf900c2c2009-07-23 20:09:56 +0000326 </P>
327 <p>
328 Imports should be as follows:
329 </p>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000330
mmentovai9ec7bd62009-12-03 22:25:38 +0000331 <DIV class=""><PRE># Reference in code with complete name.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000332import sound.effects.echo
333
mmentovaidb989ec2010-11-23 18:02:36 +0000334# Reference in code with just module name (preferred).
apicard@google.comf900c2c2009-07-23 20:09:56 +0000335from sound.effects import echo
mmentovai9ec7bd62009-12-03 22:25:38 +0000336</PRE></DIV>
mmentovai9ec7bd62009-12-03 22:25:38 +0000337 </DIV></DIV>
338 </DIV>
339 <DIV class="">
340<H3><A name="Exceptions" id="Exceptions">Exceptions</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000341<SPAN class="link_button" id="link-Exceptions__button" name="link-Exceptions__button"><A href="?showone=Exceptions#Exceptions">
342 link
343 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Exceptions__body','Exceptions__button')" name="Exceptions__button" id="Exceptions__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000344 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000345 Exceptions are allowed but must be used carefully.
mmentovai9ec7bd62009-12-03 22:25:38 +0000346 </DIV>
347 <DIV class=""><DIV class="stylepoint_body" name="Exceptions__body" id="Exceptions__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000348 <P class="">
349<SPAN class="stylepoint_section">Definition: </SPAN>
350 Exceptions are a means of breaking out of the normal flow of control
351 of a code block to handle errors or other exceptional conditions.
352 </P>
353 <P class="">
354<SPAN class="stylepoint_section">Pros: </SPAN>
355 The control flow of normal operation code is not cluttered by
356 error-handling code. It also allows the control flow to skip multiple
357 frames when a certain condition occurs, e.g., returning from N
358 nested functions in one step instead of having to carry-through
359 error codes.
360 </P>
361 <P class="">
362<SPAN class="stylepoint_section">Cons: </SPAN>
363 May cause the control flow to be confusing. Easy to miss error
364 cases when making library calls.
365 </P>
366 <P class="">
367<SPAN class="stylepoint_section">Decision: </SPAN>
368
369
370 Exceptions must follow certain conditions:
371
372 <ul>
373 <li>Raise exceptions like this: <code>raise MyException("Error
374 message")</code> or <code>raise MyException</code>. Do not
375 use the two-argument form (<code>raise MyException, "Error
376 message"</code>) or deprecated string-based exceptions
377 (<code>raise "Error message"</code>).</li>
378 <li>Modules or packages should define their own domain-specific
379 base exception class, which should inherit from the built-in
380 Exception class. The base exception for a module should be called
381 <code>Error</code>.
mmentovai9ec7bd62009-12-03 22:25:38 +0000382 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000383<span class="external"></span>class Error(Exception):
mmentovai9ec7bd62009-12-03 22:25:38 +0000384 <span class="external"> </span>pass</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000385</li>
386 <li>Never use catch-all <code>except:</code> statements, or
387 catch <code>Exception</code> or <code>StandardError</code>,
388 unless you are re-raising the exception or in the outermost
389 block in your thread (and printing an error message). Python
390 is very tolerant in this regard and <code>except:</code> will
391 really catch everything including Python syntax errors. It is
392 easy to hide real bugs using <code>except:</code>.</li>
393 <li>Minimize the amount of code in a
394 <code>try</code>/<code>except</code> block. The larger the
395 body of the <code>try</code>, the more likely that an
396 exception will be raised by a line of code that you didn't
397 expect to raise an exception. In those cases,
398 the <code>try</code>/<code>except</code> block hides a real
399 error.</li>
400 <li>Use the <code>finally</code> clause to execute code whether
401 or not an exception is raised in the <code>try</code> block.
402 This is often useful for cleanup, i.e., closing a file.</li>
403 </ul>
404 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000405 </DIV></DIV>
406 </DIV>
407 <DIV class="">
408<H3><A name="Global_variables" id="Global_variables">Global variables</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000409<SPAN class="link_button" id="link-Global_variables__button" name="link-Global_variables__button"><A href="?showone=Global_variables#Global_variables">
410 link
411 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Global_variables__body','Global_variables__button')" name="Global_variables__button" id="Global_variables__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000412 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000413 Avoid global variables.
mmentovai9ec7bd62009-12-03 22:25:38 +0000414 </DIV>
415 <DIV class=""><DIV class="stylepoint_body" name="Global_variables__body" id="Global_variables__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000416 <P class="">
417<SPAN class="stylepoint_section">Definition: </SPAN>
418 Variables that are declared at the module level.
419 </P>
420 <P class="">
421<SPAN class="stylepoint_section">Pros: </SPAN>
422 Occasionally useful.
423 </P>
424 <P class="">
425<SPAN class="stylepoint_section">Cons: </SPAN>
426 Has the potential to change module behavior during the import,
427 because assignments to module-level variables are done when the
428 module is imported.
429 </P>
430 <P class="">
431<SPAN class="stylepoint_section">Decision: </SPAN>
432 Avoid global variables in favor of class variables. Some
433 exceptions are:
434 <ul>
435 <li>Default options for scripts.</li>
436 <li>Module-level constants. For example: <code>PI = 3.14159</code>.
437 Constants should be named using all caps with underscores;
438 see <a HREF="#Naming">Naming</a> below.</li>
439 <li>It is sometimes useful for globals to cache values needed
440 or returned by functions.</li>
441 <li>If needed, globals should be made internal to the module
442 and accessed through public module level functions;
443 see <a HREF="#Naming">Naming</a> below.</li>
444 </ul>
445 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000446 </DIV></DIV>
447 </DIV>
448 <DIV class="">
449<H3><A name="Nested/Local/Inner_Classes_and_Functions" id="Nested/Local/Inner_Classes_and_Functions">Nested/Local/Inner Classes and Functions</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000450<SPAN class="link_button" id="link-Nested/Local/Inner_Classes_and_Functions__button" name="link-Nested/Local/Inner_Classes_and_Functions__button"><A href="?showone=Nested/Local/Inner_Classes_and_Functions#Nested/Local/Inner_Classes_and_Functions">
451 link
452 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Nested/Local/Inner_Classes_and_Functions__body','Nested/Local/Inner_Classes_and_Functions__button')" name="Nested/Local/Inner_Classes_and_Functions__button" id="Nested/Local/Inner_Classes_and_Functions__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000453 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000454 Nested/local/inner classes and functions are fine.
mmentovai9ec7bd62009-12-03 22:25:38 +0000455 </DIV>
456 <DIV class=""><DIV class="stylepoint_body" name="Nested/Local/Inner_Classes_and_Functions__body" id="Nested/Local/Inner_Classes_and_Functions__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000457 <P class="">
458<SPAN class="stylepoint_section">Definition: </SPAN>
mmentovaif7facf92009-10-23 21:01:49 +0000459 A class can be defined inside of a method, function, or class. A
460 function can be defined inside a method or function. Nested functions
461 have read-only access to variables defined in enclosing scopes.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000462 </P>
463 <P class="">
464<SPAN class="stylepoint_section">Pros: </SPAN>
465 Allows definition of utility classes and functions that are only
466 used inside of a very limited scope. Very <a HREF="http://en.wikipedia.org/wiki/Abstract_data_type">ADT</a>-y.
467 </P>
468 <P class="">
469<SPAN class="stylepoint_section">Cons: </SPAN>
470 Instances of nested or local classes cannot be pickled.
471 </P>
472 <P class="">
473<SPAN class="stylepoint_section">Decision: </SPAN>
474 They are fine.
475 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000476 </DIV></DIV>
477 </DIV>
478 <DIV class="">
479<H3><A name="List_Comprehensions" id="List_Comprehensions">List Comprehensions</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000480<SPAN class="link_button" id="link-List_Comprehensions__button" name="link-List_Comprehensions__button"><A href="?showone=List_Comprehensions#List_Comprehensions">
481 link
482 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('List_Comprehensions__body','List_Comprehensions__button')" name="List_Comprehensions__button" id="List_Comprehensions__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000483 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000484 Okay to use for simple cases.
mmentovai9ec7bd62009-12-03 22:25:38 +0000485 </DIV>
486 <DIV class=""><DIV class="stylepoint_body" name="List_Comprehensions__body" id="List_Comprehensions__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000487 <P class="">
488<SPAN class="stylepoint_section">Definition: </SPAN>
489 List comprehensions and generator expressions provide a concise
490 and efficient way to create lists and iterators without
491 resorting to the use of <code>map()</code>,
492 <code>filter()</code>, or <code>lambda</code>.
493 </P>
494 <P class="">
495<SPAN class="stylepoint_section">Pros: </SPAN>
496 Simple list comprehensions can be clearer and simpler than
497 other list creation techniques. Generator expressions can be
498 very efficient, since they avoid the creation of a list
499 entirely.
500 </P>
501 <P class="">
502<SPAN class="stylepoint_section">Cons: </SPAN>
503 Complicated list comprehensions or generator expressions can be
504 hard to read.
505 </P>
506 <P class="">
507<SPAN class="stylepoint_section">Decision: </SPAN>
508 Okay to use for simple cases. Each portion must fit on one line:
509 mapping expression, <code>for</code> clause, filter expression.
510 Multiple <code>for</code> clauses or filter expressions are not
511 permitted. Use loops instead when things get more complicated.
512 </P>
513
mmentovai9ec7bd62009-12-03 22:25:38 +0000514<DIV class=""><PRE class="badcode">No<span class="external"></span>:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000515 <span class="external"></span>result = [(x, y) for x in range(10) for y in range(5) if x * y &gt; 10]
516
517 <span class="external"></span>return ((x, y, z)
518 <span class="external"></span> for x in xrange(5)
519 <span class="external"></span> for y in xrange(5)
520 <span class="external"></span> if x != y
521 <span class="external"></span> for z in xrange(5)
mmentovai9ec7bd62009-12-03 22:25:38 +0000522 <span class="external"></span> if y != z)</PRE></DIV>
523<DIV class=""><PRE>Ye<span class="external"></span>s:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000524 <span class="external"></span>result = []
525 <span class="external"></span>for x in range(10):
526 <span class="external"> </span>for y in range(5):
527 <span class="external"> </span>if x * y &gt; 10:
528 <span class="external"> </span>result.append((x, y))
529
530 <span class="external"></span>for x in xrange(5):
531 <span class="external"> </span>for y in xrange(5):
532 <span class="external"> </span>if x != y:
533 <span class="external"> </span>for z in xrange(5):
534 <span class="external"> </span>if y != z:
535 <span class="external"> </span>yield (x, y, z)
536
537 <span class="external"></span>return ((x, complicated_transform(x))
538 <span class="external"></span> for x in long_generator_function(parameter)
539 <span class="external"></span> if x is not None)
540
541 <span class="external"></span>squares = [x * x for x in range(10)]
542
543 <span class="external"></span>eat(jelly_bean for jelly_bean in jelly_beans
mmentovai9ec7bd62009-12-03 22:25:38 +0000544 <span class="external"></span> if jelly_bean.color == 'black')</PRE></DIV>
545 </DIV></DIV>
546 </DIV>
547 <DIV class="">
548<H3><A name="Default_Iterators_and_Operators" id="Default_Iterators_and_Operators">Default Iterators and Operators</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000549<SPAN class="link_button" id="link-Default_Iterators_and_Operators__button" name="link-Default_Iterators_and_Operators__button"><A href="?showone=Default_Iterators_and_Operators#Default_Iterators_and_Operators">
550 link
551 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Default_Iterators_and_Operators__body','Default_Iterators_and_Operators__button')" name="Default_Iterators_and_Operators__button" id="Default_Iterators_and_Operators__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000552 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000553 Use default iterators and operators for types that support them,
554 like lists, dictionaries, and files.
mmentovai9ec7bd62009-12-03 22:25:38 +0000555 </DIV>
556 <DIV class=""><DIV class="stylepoint_body" name="Default_Iterators_and_Operators__body" id="Default_Iterators_and_Operators__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000557 <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>
mmentovai8411f0c2010-08-04 17:46:16 +0000594<SPAN class="link_button" id="link-Generators__button" name="link-Generators__button"><A href="?showone=Generators#Generators">
595 link
596 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Generators__body','Generators__button')" name="Generators__button" id="Generators__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000597 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000598 Use generators as needed.
mmentovai9ec7bd62009-12-03 22:25:38 +0000599 </DIV>
600 <DIV class=""><DIV class="stylepoint_body" name="Generators__body" id="Generators__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000601 <P class="">
602<SPAN class="stylepoint_section">Definition: </SPAN>
603 A generator function returns an iterator that yields a value each
604 time it executes a yield statement. After it yields a value, the
605 runtime state of the generator function is suspended until the
606 next value is needed.
607 </P>
608 <P class="">
609<SPAN class="stylepoint_section">Pros: </SPAN>
610 Simpler code, because the state of local variables and control flow
611 are preserved for each call. A generator uses less memory than a
612 function that creates an entire list of values at once.
613 </P>
614 <P class="">
615<SPAN class="stylepoint_section">Cons: </SPAN>
616 None.
617 </P>
618 <P class="">
619<SPAN class="stylepoint_section">Decision: </SPAN>
620 Fine. Use "Yields:" rather than "Returns:" in the
621 doc string for generator functions.
622 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000623 </DIV></DIV>
624 </DIV>
625 <DIV class="">
626<H3><A name="Lambda_Functions" id="Lambda_Functions">Lambda Functions</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000627<SPAN class="link_button" id="link-Lambda_Functions__button" name="link-Lambda_Functions__button"><A href="?showone=Lambda_Functions#Lambda_Functions">
628 link
629 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Lambda_Functions__body','Lambda_Functions__button')" name="Lambda_Functions__button" id="Lambda_Functions__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000630 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000631 Okay for one-liners.
mmentovai9ec7bd62009-12-03 22:25:38 +0000632 </DIV>
633 <DIV class=""><DIV class="stylepoint_body" name="Lambda_Functions__body" id="Lambda_Functions__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000634 <P class="">
635<SPAN class="stylepoint_section">Definition: </SPAN>
636 Lambdas define anonymous functions in an expression, as
637 opposed to a statement. They are often used to define callbacks or
638 operators for higher-order functions like <code>map()</code> and
639 <code>filter()</code>.
640 </P>
641 <P class="">
642<SPAN class="stylepoint_section">Pros: </SPAN>
643 Convenient.
644 </P>
645 <P class="">
646<SPAN class="stylepoint_section">Cons: </SPAN> Harder to read and debug than local functions. The
647 lack of names means stack traces are more difficult to
648 understand. Expressiveness is limited because the function may
649 only contain an expression.
650 </P>
651 <P class="">
652<SPAN class="stylepoint_section">Decision: </SPAN>
653 Okay to use them for one-liners. If the code inside the lambda
654 function is any longer than 60–80 chars, it's probably better to
655 define it as a regular (nested) function.
656 <p>
657 For common operations like multiplication, use the functions from the
658 <code>operator</code> module instead of lambda functions. For
659 example, prefer <code>operator.mul</code> to <code>lambda
660 x, y: x * y</code>.
661 </p>
662 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000663 </DIV></DIV>
664 </DIV>
665 <DIV class="">
666<H3><A name="Default_Argument_Values" id="Default_Argument_Values">Default Argument Values</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000667<SPAN class="link_button" id="link-Default_Argument_Values__button" name="link-Default_Argument_Values__button"><A href="?showone=Default_Argument_Values#Default_Argument_Values">
668 link
669 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Default_Argument_Values__body','Default_Argument_Values__button')" name="Default_Argument_Values__button" id="Default_Argument_Values__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +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">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000674 <P class="">
675<SPAN class="stylepoint_section">Definition: </SPAN>
676 You can specify values for variables at the end of a function's
677 parameter list, e.g., <code>def foo(a, b=0):</code>. If
678 <code>foo</code> is called with only one argument,
679 <code>b</code> is set to 0. If it is called with two arguments,
680 <code>b</code> has the value of the second argument.
681 </P>
682 <P class="">
683<SPAN class="stylepoint_section">Pros: </SPAN>
684 Often you have a function that uses lots of default values,
685 but—rarely—you want to override the
686 defaults. Default argument values provide an easy way to do this,
687 without having to define lots of functions for the rare
688 exceptions. Also, Python does not support overloaded
689 methods/functions and default arguments are an easy way of
690 "faking" the overloading behavior.
691 </P>
692 <P class="">
693<SPAN class="stylepoint_section">Cons: </SPAN>
694 Default arguments are evaluated once at module load
695 time. This may cause problems if the argument is a mutable
696 object such as a list or a dictionary. If the function modifies
697 the object (e.g., by appending an item to a list), the default
698 value is modified.
699 </P>
700 <P class="">
701<SPAN class="stylepoint_section">Decision: </SPAN>
702 Okay to use with the following caveats:
703 <p>
704 Do not use mutable objects as default values in the function or method
705 definition.
706 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000707<DIV class=""><PRE>Yes: <span class="external"></span>def foo(a, b=None):
apicard@google.comf900c2c2009-07-23 20:09:56 +0000708 <span class="external"> </span>if b is None:
mmentovai9ec7bd62009-12-03 22:25:38 +0000709 <span class="external"> </span>b = []</PRE></DIV>
710<DIV class=""><PRE class="badcode">No: <span class="external"></span>def foo(a, b=[]):
711 <span class="external"> </span>...</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000712 <p>
mmentovaif7facf92009-10-23 21:01:49 +0000713 Calling code must use named values for arguments with a default value.
714 This helps document the code somewhat and helps prevent and detect
apicard@google.comf900c2c2009-07-23 20:09:56 +0000715 interface breakage when more arguments are added.
716 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000717<DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000718<span class="external"></span>def foo(a, b=1):
mmentovai9ec7bd62009-12-03 22:25:38 +0000719 <span class="external"> </span>...</PRE></DIV>
720<DIV class=""><PRE>Yes: <span class="external"></span>foo(1)
721 <span class="external"></span>foo(1, b=2)</PRE></DIV>
722<DIV class=""><PRE class="badcode">No: <span class="external"></span>foo(1, 2)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000723 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000724 </DIV></DIV>
725 </DIV>
726 <DIV class="">
727<H3><A name="Properties" id="Properties">Properties</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000728<SPAN class="link_button" id="link-Properties__button" name="link-Properties__button"><A href="?showone=Properties#Properties">
729 link
730 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Properties__body','Properties__button')" name="Properties__button" id="Properties__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000731 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000732 Use properties for accessing or setting data where you would
733 normally have used simple, lightweight accessor or setter methods.
mmentovai9ec7bd62009-12-03 22:25:38 +0000734 </DIV>
735 <DIV class=""><DIV class="stylepoint_body" name="Properties__body" id="Properties__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000736 <P class="">
737<SPAN class="stylepoint_section">Definition: </SPAN> A way to wrap method calls for getting and
738 setting an attribute as a standard attribute access when the
739 computation is lightweight.
740 </P>
741 <P class="">
742<SPAN class="stylepoint_section">Pros: </SPAN> Readability is increased by eliminating explicit
743 get and set method calls for simple attribute access. Allows
744 calculations to be lazy. Considered the Pythonic way to
745 maintain the interface of a class. In terms of performance,
746 allowing properties bypasses needing trivial accessor methods
747 when a direct variable access is reasonable. This also allows
748 accessor methods to be added in the future without breaking the
749 interface.
750 </P>
751 <P class="">
752<SPAN class="stylepoint_section">Cons: </SPAN> Properties are specified after the getter and
753 setter methods are declared, requiring one to notice they are
754 used for properties farther down in the code (except for readonly
755 properties created with the <code>@property</code> decorator - see
756 below). Must inherit from
757 <code>object</code>. Can hide side-effects much like operator
758 overloading. Can be confusing for subclasses.
759 </P>
760 <P class="">
761<SPAN class="stylepoint_section">Decision: </SPAN> Use properties in new code to access or
762 set data where you would normally have used simple, lightweight
763 accessor or setter methods. Read-only properties should be created
764 with the <code>@property</code>
765 <a HREF="#Function_and_Method_Decorators">decorator</a>.
766
767 <p><a id="properties-template-dp">
768 Inheritance with properties can be non-obvious if the property itself is
769 not overridden. Thus one must make sure that accessor methods are
770 called indirectly to ensure methods overridden in subclasses are called
771 by the property (using the Template Method DP).
772 </a></p>
773
mmentovai9ec7bd62009-12-03 22:25:38 +0000774 <DIV class=""><PRE>Yes: <span class="external"></span>import math
apicard@google.comf900c2c2009-07-23 20:09:56 +0000775
776 <span class="external"></span>class Square(object):
777 <span class="external"> </span>"""A square with two properties: a writable area and a read-only perimeter.
778
779 <span class="external"> </span>To use:
780 <span class="external"> </span>&gt;&gt;&gt; sq = Square(3)
781 <span class="external"> </span>&gt;&gt;&gt; sq.area
782 <span class="external"> </span>9
783 <span class="external"> </span>&gt;&gt;&gt; sq.perimeter
784 <span class="external"> </span>12
785 <span class="external"> </span>&gt;&gt;&gt; sq.area = 16
786 <span class="external"> </span>&gt;&gt;&gt; sq.side
787 <span class="external"> </span>4
788 <span class="external"> </span>&gt;&gt;&gt; sq.perimeter
789 <span class="external"> </span>16
790 <span class="external"> </span>"""
791
792 <span class="external"> </span>def __init__(self, side):
793 <span class="external"> </span>self.side = side
794
795 <span class="external"> </span>def __get_area(self):
796 <span class="external"> </span>"""Calculates the 'area' property."""
797 <span class="external"> </span>return self.side ** 2
798
799 <span class="external"> </span>def ___get_area(self):
800 <span class="external"> </span>"""Indirect accessor for 'area' property."""
801 <span class="external"> </span>return self.__get_area()
802
803 <span class="external"> </span>def __set_area(self, area):
804 <span class="external"> </span>"""Sets the 'area' property."""
805 <span class="external"> </span>self.side = math.sqrt(area)
806
807 <span class="external"> </span>def ___set_area(self, area):
808 <span class="external"> </span>"""Indirect setter for 'area' property."""
809 <span class="external"> </span>self._SetArea(area)
810
811 <span class="external"> </span>area = property(___get_area, ___set_area,
812 <span class="external"> </span> doc="""Gets or sets the area of the square.""")
813
814 <span class="external"> </span>@property
815 <span class="external"> </span>def perimeter(self):
816 <span class="external"> </span>return self.side * 4
817<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000818</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000819 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000820 </DIV></DIV>
821 </DIV>
822 <DIV class="">
823<H3><A name="True/False_evaluations" id="True/False_evaluations">True/False evaluations</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000824<SPAN class="link_button" id="link-True/False_evaluations__button" name="link-True/False_evaluations__button"><A href="?showone=True/False_evaluations#True/False_evaluations">
825 link
826 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('True/False_evaluations__body','True/False_evaluations__button')" name="True/False_evaluations__button" id="True/False_evaluations__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000827 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000828 Use the "implicit" false if at all possible.
mmentovai9ec7bd62009-12-03 22:25:38 +0000829 </DIV>
830 <DIV class=""><DIV class="stylepoint_body" name="True/False_evaluations__body" id="True/False_evaluations__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000831 <P class="">
832<SPAN class="stylepoint_section">Definition: </SPAN> Python evaluates certain values as <code>false</code>
833 when in a boolean context. A quick "rule of thumb" is that all
834 "empty" values are considered <code>false</code> so <code>0, None, [], {},
835 ""</code> all evaluate as <code>false</code> in a boolean context.
836 </P>
837 <P class="">
838<SPAN class="stylepoint_section">Pros: </SPAN> Conditions using Python booleans are easier to read
839 and less error-prone. In most cases, they're also faster.
840 </P>
841 <P class="">
842<SPAN class="stylepoint_section">Cons: </SPAN>
843 May look strange to C/C++ developers.
844 </P>
845 <P class="">
846<SPAN class="stylepoint_section">Decision: </SPAN>
847 Use the "implicit" false if at all possible, e.g., <code>if
848 foo:</code> rather than <code>if foo != []:</code>. There are a
849 few caveats that you should keep in mind though:
850 <ul>
851 <li>
852 Never use <code>==</code> or <code>!=</code> to compare
853 singletons like <code>None</code>. Use <code>is</code>
854 or <code>is not</code>.</li>
855
856 <li>Beware of writing <code>if x:</code> when you really mean
857 <code>if x is not None:</code>—e.g., when testing whether
858 a variable or argument that defaults to <code>None</code> was
859 set to some other value. The other value might be a value
860 that's false in a boolean context!</li>
861
862 <li>
863 Never compare a boolean variable to <code>False</code> using
864 <code>==</code>. Use <code>if not x:</code> instead. If
865 you need to distinguish <code>False</code> from
866 <code>None</code> then chain the expressions,
867 such as <code>if not x and x is not None:</code>.
868 </li>
869
870 <li>
871 For sequences (strings, lists, tuples), use the fact that
872 empty sequences are false, so <code>if not seq:</code> or
873 <code>if seq:</code> is preferable to <code>if
874 len(seq):</code> or <code>if not
875 len(seq):</code>.</li>
876
877 <li>
878 When handling integers, implicit false may involve more risk than
879 benefit (i.e., accidentally handling <code>None</code> as 0). You may
880 compare a value which is known to be an integer (and is not the
881 result of <code>len()</code>) against the integer 0.
mmentovai9ec7bd62009-12-03 22:25:38 +0000882<DIV class=""><PRE>Yes: <span class="external"></span>if not users:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000883 <span class="external"> </span>print 'no users'
884
885 <span class="external"></span>if foo == 0:
886 <span class="external"> </span>self.handle_zero()
887
888 <span class="external"></span>if i % 10 == 0:
mmentovai9ec7bd62009-12-03 22:25:38 +0000889 <span class="external"> </span>self.handle_multiple_of_ten()</PRE></DIV>
890<DIV class=""><PRE class="badcode">No: <span class="external"></span>if len(users) == 0:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000891 <span class="external"> </span>print 'no users'
892
893 <span class="external"></span>if foo is not None and not foo:
894 <span class="external"> </span>self.handle_zero()
895
896 <span class="external"></span>if not i % 10:
mmentovai9ec7bd62009-12-03 22:25:38 +0000897 <span class="external"> </span>self.handle_multiple_of_ten()</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000898</li>
899
900 <li>
901 Note that <code>'0'</code> (i.e., <code>0</code> as string)
902 evaluates to true.</li>
903 </ul>
904 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000905 </DIV></DIV>
906 </DIV>
907 <DIV class="">
908<H3><A name="Deprecated_Language_Features" id="Deprecated_Language_Features">Deprecated Language Features</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000909<SPAN class="link_button" id="link-Deprecated_Language_Features__button" name="link-Deprecated_Language_Features__button"><A href="?showone=Deprecated_Language_Features#Deprecated_Language_Features">
910 link
911 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Deprecated_Language_Features__body','Deprecated_Language_Features__button')" name="Deprecated_Language_Features__button" id="Deprecated_Language_Features__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000912 <DIV style="display:inline;" class="">
mmentovaif7facf92009-10-23 21:01:49 +0000913 Use string methods instead of the <code>string</code> module
914 where possible. Use function call syntax instead
915 of <code>apply</code>. Use list comprehensions
916 and <code>for</code> loops instead of <code>filter</code>,
917 <code>map</code>, and <code>reduce</code>.
mmentovai9ec7bd62009-12-03 22:25:38 +0000918 </DIV>
919 <DIV class=""><DIV class="stylepoint_body" name="Deprecated_Language_Features__body" id="Deprecated_Language_Features__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000920 <P class="">
mmentovaif7facf92009-10-23 21:01:49 +0000921<SPAN class="stylepoint_section">Definition: </SPAN>
922 Current versions of Python provide alternative constructs
923 that people find generally preferable.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000924 </P>
925 <P class="">
mmentovaif7facf92009-10-23 21:01:49 +0000926<SPAN class="stylepoint_section">Decision: </SPAN>
927 We do not use any Python version which does not support
928 these features, so there is no reason not to use the new
929 styles.
mmentovai9ec7bd62009-12-03 22:25:38 +0000930<DIV class=""><PRE class="badcode">No: <span class="external"></span>words = string.split(foo, ':')
mmentovaif7facf92009-10-23 21:01:49 +0000931
932 <span class="external"></span>map(lambda x: x[1], filter(lambda x: x[2] == 5, my_list))
933
mmentovai9ec7bd62009-12-03 22:25:38 +0000934 <span class="external"></span>apply(fn, args, kwargs)</PRE></DIV>
935<DIV class=""><PRE>Yes: <span class="external"></span>words = foo.split(':')
mmentovaif7facf92009-10-23 21:01:49 +0000936
937 <span class="external"></span>[x[1] for x in my_list if x[2] == 5]
938
mmentovai9ec7bd62009-12-03 22:25:38 +0000939 <span class="external"></span>fn(*args, **kwargs)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000940 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000941 </DIV></DIV>
942 </DIV>
943 <DIV class="">
944<H3><A name="Lexical_Scoping" id="Lexical_Scoping">Lexical Scoping</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000945<SPAN class="link_button" id="link-Lexical_Scoping__button" name="link-Lexical_Scoping__button"><A href="?showone=Lexical_Scoping#Lexical_Scoping">
946 link
947 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Lexical_Scoping__body','Lexical_Scoping__button')" name="Lexical_Scoping__button" id="Lexical_Scoping__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000948 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000949 Okay to use.
mmentovai9ec7bd62009-12-03 22:25:38 +0000950 </DIV>
951 <DIV class=""><DIV class="stylepoint_body" name="Lexical_Scoping__body" id="Lexical_Scoping__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000952 <P class="">
953<SPAN class="stylepoint_section">Definition: </SPAN>
954 A nested Python function can refer to variables defined in
955 enclosing functions, but can not assign to them. Variable
956 bindings are resolved using lexical scoping, that is, based on
957 the static program text. Any assignment to a name in a block
958 will cause Python to treat all references to that name as a
959 local variable, even if the use precedes the assignment. If a
960 global declaration occurs, the name is treated as a global
961 variable.
962
963 <p>
964 An example of the use of this feature is:
965 </p>
966
mmentovai9ec7bd62009-12-03 22:25:38 +0000967 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000968<span class="external"></span>def get_adder(summand1):
969 <span class="external"> </span>"""Returns a function that adds numbers to a given number."""
970 <span class="external"> </span>def adder(summand2):
971 <span class="external"> </span>return summand1 + summand2
972
973 <span class="external"> </span>return adder
974<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000975</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000976 </P>
977 <P class="">
978<SPAN class="stylepoint_section">Pros: </SPAN>
979 Often results in clearer, more elegant code. Especially comforting
980 to experienced Lisp and Scheme (and Haskell and ML and …)
981 programmers.
982 </P>
983 <P class="">
984<SPAN class="stylepoint_section">Cons: </SPAN>
985 Can lead to confusing bugs. Such as this example based on
986 <a HREF="http://www.python.org/dev/peps/pep-0227/">PEP-0227</a>:
mmentovai9ec7bd62009-12-03 22:25:38 +0000987<DIV class=""><PRE class="badcode">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000988<span class="external"></span>i = 4
989<span class="external"></span>def foo(x):
990 <span class="external"> </span>def bar():
991 <span class="external"> </span>print i,
992 <span class="external"> </span># ...
993 <span class="external"> </span># A bunch of code here
994 <span class="external"> </span># ...
995 <span class="external"> </span>for i in x: # Ah, i *is* local to Foo, so this is what Bar sees
996 <span class="external"> </span>print i,
mmentovai9ec7bd62009-12-03 22:25:38 +0000997 <span class="external"> </span>bar()</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000998 <p>
999 So <code>foo([1, 2, 3])</code> will print <code>1 2 3 3</code>, not
1000 <code>1 2 3 4</code>.
1001 </p>
1002 </P>
1003 <P class="">
1004<SPAN class="stylepoint_section">Decision: </SPAN>
1005 Okay to use.
1006 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001007 </DIV></DIV>
1008 </DIV>
1009 <DIV class="">
1010<H3><A name="Function_and_Method_Decorators" id="Function_and_Method_Decorators">Function and Method Decorators</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001011<SPAN class="link_button" id="link-Function_and_Method_Decorators__button" name="link-Function_and_Method_Decorators__button"><A href="?showone=Function_and_Method_Decorators#Function_and_Method_Decorators">
1012 link
1013 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Function_and_Method_Decorators__body','Function_and_Method_Decorators__button')" name="Function_and_Method_Decorators__button" id="Function_and_Method_Decorators__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001014 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001015 Use decorators judiciously when there is a clear advantage.
mmentovai9ec7bd62009-12-03 22:25:38 +00001016 </DIV>
1017 <DIV class=""><DIV class="stylepoint_body" name="Function_and_Method_Decorators__body" id="Function_and_Method_Decorators__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001018 <P class="">
1019<SPAN class="stylepoint_section">Definition: </SPAN>
1020
1021 <a HREF="http://www.python.org/doc/2.4.3/whatsnew/node6.html">Decorators
1022 for Functions and Methods</a>
1023 (a.k.a "the <code>@</code> notation").
1024 The most common decorators are <code>@classmethod</code> and
1025 <code>@staticmethod</code>, for converting ordinary methods to class or
1026 static methods. However, the decorator syntax allows for
1027 user-defined decorators as well. Specifically, for some function
1028 <code>my_decorator</code>, this:
mmentovai9ec7bd62009-12-03 22:25:38 +00001029 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001030<span class="external"></span>class C(object):
1031 <span class="external"> </span>@my_decorator
1032 <span class="external"> </span>def method(self):
1033 <span class="external"> </span># method body ...
1034<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001035</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001036
1037 is equivalent to:
mmentovai9ec7bd62009-12-03 22:25:38 +00001038 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001039<span class="external"></span>class C(object):
1040 <span class="external"> </span>def method(self):
1041 <span class="external"> </span># method body ...
1042 <span class="external"> </span>method = my_decorator(method)
1043<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001044</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001045 </P>
1046 <P class="">
1047<SPAN class="stylepoint_section">Pros: </SPAN> Elegantly specifies some transformation on a method; the
1048 transformation might eliminate some repetitive code, enforce invariants,
1049 etc.
1050 </P>
1051 <P class="">
1052<SPAN class="stylepoint_section">Cons: </SPAN> Decorators can perform arbitrary operations on a
1053 function's arguments or return values, resulting in surprising
1054 implicit behavior.
1055 Additionally, decorators execute at import time. Failures in decorator
1056 code are pretty much impossible to recover from.
1057 </P>
1058 <P class="">
1059<SPAN class="stylepoint_section">Decision: </SPAN> Use decorators judiciously when there is a clear
1060 advantage. Decorators should follow the same import and naming
1061 guidelines as functions. Decorator pydoc should clearly state that the
1062 function is a decorator. Write unit tests for decorators.
1063
1064 <p>
1065 Avoid external dependencies in the decorator itself (e.g. don't rely on
1066 files, sockets, database connections, etc.), since they might not be
1067 available when the decorator runs (at import time, perhaps from
1068 <code>pychecker</code> or other tools). A decorator that is
1069 called with valid parameters should (as much as possible) be guaranteed
1070 to succeed in all cases.
1071 </p>
1072 <p>
1073 Decorators are a special case of "top level code" - see
1074 <a HREF="#Main">main</a> for more discussion.
1075 </p>
1076 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001077 </DIV></DIV>
1078 </DIV>
1079 <DIV class="">
1080<H3><A name="Threading" id="Threading">Threading</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001081<SPAN class="link_button" id="link-Threading__button" name="link-Threading__button"><A href="?showone=Threading#Threading">
1082 link
1083 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Threading__body','Threading__button')" name="Threading__button" id="Threading__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001084 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001085 Do not rely on the atomicity of built-in types.
mmentovai9ec7bd62009-12-03 22:25:38 +00001086 </DIV>
1087 <DIV class=""><DIV class="stylepoint_body" name="Threading__body" id="Threading__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001088 <p>
1089 While Python's built-in data types such as dictionaries appear
1090 to have atomic operations, there are corner cases where they
1091 aren't atomic (e.g. if <code>__hash__</code> or
1092 <code>__eq__</code> are implemented as Python methods) and their
1093 atomicity should not be relied upon. Neither should you rely on
1094 atomic variable assignment (since this in turn depends on
1095 dictionaries).
1096 </p>
1097
1098 <p>
1099 Use the Queue module's <code>Queue</code> data type as the preferred
1100 way to
1101 communicate data between threads. Otherwise, use the threading
1102 module and its locking primitives. Learn about the proper use
1103 of condition variables so you can use
1104 <code>threading.Condition</code> instead of using lower-level
1105 locks.
1106 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001107 </DIV></DIV>
1108 </DIV>
1109 <DIV class="">
1110<H3><A name="Power_Features" id="Power_Features">Power Features</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001111<SPAN class="link_button" id="link-Power_Features__button" name="link-Power_Features__button"><A href="?showone=Power_Features#Power_Features">
1112 link
1113 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Power_Features__body','Power_Features__button')" name="Power_Features__button" id="Power_Features__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001114 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001115 Avoid these features.
mmentovai9ec7bd62009-12-03 22:25:38 +00001116 </DIV>
1117 <DIV class=""><DIV class="stylepoint_body" name="Power_Features__body" id="Power_Features__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001118 <P class="">
1119<SPAN class="stylepoint_section">Definition: </SPAN> Python is an extremely flexible language and
1120 gives you many fancy features such as metaclasses, access to bytecode,
1121 on-the-fly compilation, dynamic inheritance, object reparenting,
1122 import hacks, reflection, modification of system internals,
1123 etc.
1124 </P>
1125 <P class="">
1126<SPAN class="stylepoint_section">Pros: </SPAN> These are powerful language features. They can
1127 make your code more compact.
1128 </P>
1129 <P class="">
1130<SPAN class="stylepoint_section">Cons: </SPAN> It's very tempting to use these "cool" features
1131 when they're not absolutely necessary. It's harder to read,
1132 understand, and debug code that's using unusual features
1133 underneath. It doesn't seem that way at first (to the original
1134 author), but when revisiting the code, it tends to be more
1135 difficult than code that is longer but is straightforward.
1136 </P>
1137 <P class="">
1138<SPAN class="stylepoint_section">Decision: </SPAN>
1139 Avoid these features in
1140 your code.
1141 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001142 </DIV></DIV>
1143 </DIV>
1144 </DIV>
1145 <DIV class="">
1146<H2 name="Python_Style_Rules" id="Python_Style_Rules">Python Style Rules</H2>
1147 <DIV class="">
1148<H3><A name="Semicolons" id="Semicolons">Semicolons</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001149<SPAN class="link_button" id="link-Semicolons__button" name="link-Semicolons__button"><A href="?showone=Semicolons#Semicolons">
1150 link
1151 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Semicolons__body','Semicolons__button')" name="Semicolons__button" id="Semicolons__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001152 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001153 Do not terminate your lines with semi-colons and do not use
1154 semi-colons to put two commands on the same line.
mmentovai9ec7bd62009-12-03 22:25:38 +00001155 </DIV>
1156 <DIV class=""><DIV class="stylepoint_body" name="Semicolons__body" id="Semicolons__body" style="display: none">
mmentovai9ec7bd62009-12-03 22:25:38 +00001157 </DIV></DIV>
1158 </DIV>
1159 <DIV class="">
1160<H3><A name="Line_length" id="Line_length">Line length</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001161<SPAN class="link_button" id="link-Line_length__button" name="link-Line_length__button"><A href="?showone=Line_length#Line_length">
1162 link
1163 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Line_length__body','Line_length__button')" name="Line_length__button" id="Line_length__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001164 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001165 Maximum line length is <em>80 characters</em>.
mmentovai9ec7bd62009-12-03 22:25:38 +00001166 </DIV>
1167 <DIV class=""><DIV class="stylepoint_body" name="Line_length__body" id="Line_length__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001168 <p>
1169 Exception: lines importing modules may end up longer than 80
1170 characters only if using Python 2.4 or
1171 earlier.
1172 </p>
1173
1174 <p>
1175 Make use of Python's
1176
1177 <a HREF="http://www.python.org/doc/ref/implicit-joining.html">implicit
1178 line joining inside parentheses, brackets and braces</a>.
1179 If necessary, you can add an extra pair of parentheses around an
1180 expression.
1181 </p>
1182
1183
mmentovai9ec7bd62009-12-03 22:25:38 +00001184 <DIV class=""><PRE>Yes: foo_bar(self, width, height, color='black', design=None, x='foo',
apicard@google.comf900c2c2009-07-23 20:09:56 +00001185 emphasis=None, highlight=0)
1186
1187 if (width == 0 and height == 0 and
mmentovai9ec7bd62009-12-03 22:25:38 +00001188 color == 'red' and emphasis == 'strong'):</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001189
1190
1191 <p>
1192 When a literal string won't fit on a single line, use parentheses for
1193 implicit line joining.
1194 </p>
1195
mmentovai9ec7bd62009-12-03 22:25:38 +00001196 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001197<span class="external"></span>x = ('This will build a very long long '
mmentovai9ec7bd62009-12-03 22:25:38 +00001198<span class="external"></span> 'long long long long long long string')</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001199
1200 <p>
1201 Make note of the indentation of the elements in the line
1202 continuation examples above; see the
1203 <a HREF="#indentation">indentation</a>
1204 section for explanation.
1205 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001206 </DIV></DIV>
1207 </DIV>
1208 <DIV class="">
1209<H3><A name="Parentheses" id="Parentheses">Parentheses</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001210<SPAN class="link_button" id="link-Parentheses__button" name="link-Parentheses__button"><A href="?showone=Parentheses#Parentheses">
1211 link
1212 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Parentheses__body','Parentheses__button')" name="Parentheses__button" id="Parentheses__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001213 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001214 Use parentheses sparingly.
mmentovai9ec7bd62009-12-03 22:25:38 +00001215 </DIV>
1216 <DIV class=""><DIV class="stylepoint_body" name="Parentheses__body" id="Parentheses__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001217 <p>
1218 Do not use them in return statements or conditional statements unless
1219 using parentheses for implied line continuation. (See above.)
1220 It is however fine to use parentheses around tuples.
1221 </p>
1222
mmentovai9ec7bd62009-12-03 22:25:38 +00001223<DIV class=""><PRE>Yes: <span class="external"></span>if foo:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001224 <span class="external"> </span>bar()
1225 <span class="external"></span>while x:
1226 <span class="external"> </span>x = bar()
1227 <span class="external"></span>if x and y:
1228 <span class="external"> </span>bar()
1229 <span class="external"></span>if not x:
1230 <span class="external"> </span>bar()
1231 <span class="external"></span>return foo
mmentovai9ec7bd62009-12-03 22:25:38 +00001232 <span class="external"></span>for (x, y) in dict.items(): ...</PRE></DIV>
1233<DIV class=""><PRE class="badcode">No: <span class="external"></span>if (x):
apicard@google.comf900c2c2009-07-23 20:09:56 +00001234 <span class="external"> </span>bar()
1235 <span class="external"></span>if not(x):
1236 <span class="external"> </span>bar()
mmentovai9ec7bd62009-12-03 22:25:38 +00001237 <span class="external"></span>return (foo)</PRE></DIV>
1238 </DIV></DIV>
1239 </DIV>
1240 <DIV class="">
1241<H3><A name="Indentation" id="Indentation">Indentation</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001242<SPAN class="link_button" id="link-Indentation__button" name="link-Indentation__button"><A href="?showone=Indentation#Indentation">
1243 link
1244 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Indentation__body','Indentation__button')" name="Indentation__button" id="Indentation__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001245 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001246 Indent your code blocks with <em>4 spaces</em>.
mmentovai9ec7bd62009-12-03 22:25:38 +00001247 </DIV>
1248 <DIV class=""><DIV class="stylepoint_body" name="Indentation__body" id="Indentation__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001249 <p>
1250 Never use tabs or mix tabs and spaces.
1251 In cases of implied line continuation, you should align wrapped elements
1252 either vertically, as per the examples in the
1253 <a HREF="#Line_length">line length</a> section; or using a hanging
1254 indent of 4 spaces, in which case there should be no argument on
1255 the first line.
1256 </p>
1257
1258
mmentovai9ec7bd62009-12-03 22:25:38 +00001259<DIV class=""><PRE>Yes: # Aligned with opening delimiter
apicard@google.comf900c2c2009-07-23 20:09:56 +00001260 foo = long_function_name(var_one, var_two,
1261 var_three, var_four)
1262
1263 # 4-space hanging indent; nothing on first line
1264 foo = long_function_name(
1265 var_one, var_two, var_three,
mmentovai9ec7bd62009-12-03 22:25:38 +00001266 var_four)</PRE></DIV>
1267<DIV class=""><PRE class="badcode">No: <span class="external"></span># Stuff on first line forbidden
apicard@google.comf900c2c2009-07-23 20:09:56 +00001268 <span class="external"></span>foo = long_function_name(var_one, var_two,
1269 <span class="external"></span> var_three, var_four)
1270
1271 <span class="external"></span># 2-space hanging indent forbidden
1272 <span class="external"></span>foo = long_function_name(
1273 <span class="external"></span> var_one, var_two, var_three,
mmentovai9ec7bd62009-12-03 22:25:38 +00001274 <span class="external"></span> var_four)</PRE></DIV>
1275 </DIV></DIV>
1276 </DIV>
1277 <DIV class="">
1278<H3><A name="Blank_Lines" id="Blank_Lines">Blank Lines</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001279<SPAN class="link_button" id="link-Blank_Lines__button" name="link-Blank_Lines__button"><A href="?showone=Blank_Lines#Blank_Lines">
1280 link
1281 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Blank_Lines__body','Blank_Lines__button')" name="Blank_Lines__button" id="Blank_Lines__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001282 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001283 Two blank lines between top-level definitions, one blank line
1284 between method definitions.
mmentovai9ec7bd62009-12-03 22:25:38 +00001285 </DIV>
1286 <DIV class=""><DIV class="stylepoint_body" name="Blank_Lines__body" id="Blank_Lines__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001287 <p>
1288 Two blank lines between top-level definitions, be they function
1289 or class definitions. One blank line between method definitions
1290 and between the <code>class</code> line and the first method.
1291 Use single blank lines as you judge appropriate within functions or
1292 methods.
1293 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001294 </DIV></DIV>
1295 </DIV>
1296 <DIV class="">
1297<H3><A name="Whitespace" id="Whitespace">Whitespace</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001298<SPAN class="link_button" id="link-Whitespace__button" name="link-Whitespace__button"><A href="?showone=Whitespace#Whitespace">
1299 link
1300 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Whitespace__body','Whitespace__button')" name="Whitespace__button" id="Whitespace__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001301 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001302 Follow standard typographic rules for the use of spaces around
1303 punctuation.
mmentovai9ec7bd62009-12-03 22:25:38 +00001304 </DIV>
1305 <DIV class=""><DIV class="stylepoint_body" name="Whitespace__body" id="Whitespace__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001306 <p>
1307 No whitespace inside parentheses, brackets or braces.
1308 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001309<DIV class=""><PRE>Yes: <span class="external"></span>spam(ham[1], {eggs: 2}, [])</PRE></DIV>
1310<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 +00001311 <p>
1312 No whitespace before a comma, semicolon, or colon. Do use
1313 whitespace after a comma, semicolon, or colon except at the end
1314 of the line.
1315 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001316<DIV class=""><PRE>Yes: <span class="external"></span>if x == 4:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001317 <span class="external"> </span>print x, y
mmentovai9ec7bd62009-12-03 22:25:38 +00001318 <span class="external"></span>x, y = y, x</PRE></DIV>
1319<DIV class=""><PRE class="badcode">No: <span class="external"></span>if x == 4 :
apicard@google.comf900c2c2009-07-23 20:09:56 +00001320 <span class="external"> </span>print x , y
mmentovai9ec7bd62009-12-03 22:25:38 +00001321 <span class="external"></span>x , y = y , x</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001322 <p>
1323 No whitespace before the open paren/bracket that starts an argument list,
1324 indexing or slicing.
1325 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001326 <DIV class=""><PRE>Yes: <span class="external"></span>spam(1)</PRE></DIV>
1327<DIV class=""><PRE class="badcode">No: <span class="external"></span>spam (1)</PRE></DIV>
1328<DIV class=""><PRE>Yes: <span class="external"></span>dict['key'] = list[index]</PRE></DIV>
1329<DIV class=""><PRE class="badcode">No: <span class="external"></span>dict ['key'] = list [index]</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001330
1331 <p>
1332 Surround binary operators with a single space on either side for
1333 assignment (<code>=</code>), comparisons (<code>==, &lt;, &gt;, !=,
1334 &lt;&gt;, &lt;=, &gt;=, in, not in, is, is not</code>), and Booleans
1335 (<code>and, or, not</code>). Use your better judgment for the
1336 insertion of spaces around arithmetic operators but always be
1337 consistent about whitespace on either side of a binary operator.
1338 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001339<DIV class=""><PRE>Yes: <span class="external"></span>x == 1</PRE></DIV>
1340<DIV class=""><PRE class="badcode">No: <span class="external"></span>x&lt;1</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001341 <p>
1342 Don't use spaces around the '=' sign when used to indicate a
1343 keyword argument or a default parameter value.
1344 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001345<DIV class=""><PRE>Yes: <span class="external"></span>def complex(real, imag=0.0): return magic(r=real, i=imag)</PRE></DIV>
1346<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 +00001347
1348 <p>
1349 Don't use spaces to vertically align tokens on consecutive lines, since it
1350 becomes a maintenance burden (applies to <code>:</code>, <code>#</code>,
1351 <code>=</code>, etc.):
1352 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001353<DIV class=""><PRE>Yes:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001354 foo = 1000 # comment
1355 long_name = 2 # comment that should not be aligned
1356
1357 dictionary = {
1358 "foo": 1,
1359 "long_name": 2,
mmentovai9ec7bd62009-12-03 22:25:38 +00001360 }</PRE></DIV>
1361<DIV class=""><PRE class="badcode">No:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001362 foo = 1000 # comment
1363 long_name = 2 # comment that should not be aligned
1364
1365 dictionary = {
1366 "foo" : 1,
1367 "long_name": 2,
mmentovai9ec7bd62009-12-03 22:25:38 +00001368 }</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001369
1370
mmentovai9ec7bd62009-12-03 22:25:38 +00001371 </DIV></DIV>
1372 </DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001373
mmentovaicd4ce0f2011-03-29 20:30:47 +00001374 <a name="Python_Interpreter"></a>
1375 <DIV class="">
1376<H3><A name="Shebang_Line" id="Shebang_Line">Shebang Line</A></H3>
1377<SPAN class="link_button" id="link-Shebang_Line__button" name="link-Shebang_Line__button"><A href="?showone=Shebang_Line#Shebang_Line">
1378 link
1379 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Shebang_Line__body','Shebang_Line__button')" name="Shebang_Line__button" id="Shebang_Line__button"></SPAN>
1380 <DIV style="display:inline;" class="">
1381 All <code>.py</code> files (except <code>__init__.py</code> package
1382 files) should begin with a
1383
1384 <code>#!/usr/bin/python&lt;version&gt;</code>
1385 shebang line.
1386 </DIV>
1387 <DIV class=""><DIV class="stylepoint_body" name="Shebang_Line__body" id="Shebang_Line__body" style="display: none">
1388
1389 <p>
1390 Always use the most specific version that you can to ensure
1391 compatibility. For examples, if your program uses a language feature
1392 that that first appeared in Python 2.4, use
1393 <code>/usr/bin/python2.4</code> (or something newer) instead of
1394 <code>/usr/bin/python2</code>. Otherwise, your program might not
1395 behave the way you expect it to, because the interpreter uses an
1396 older version of the language.
1397 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001398 </DIV></DIV>
1399 </DIV>
mmentovaicd4ce0f2011-03-29 20:30:47 +00001400
mmentovai9ec7bd62009-12-03 22:25:38 +00001401 <DIV class="">
1402<H3><A name="Comments" id="Comments">Comments</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001403<SPAN class="link_button" id="link-Comments__button" name="link-Comments__button"><A href="?showone=Comments#Comments">
1404 link
1405 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Comments__body','Comments__button')" name="Comments__button" id="Comments__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001406 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001407 Be sure to use the right style for module, function, method and in-line
1408 comments.
mmentovai9ec7bd62009-12-03 22:25:38 +00001409 </DIV>
1410 <DIV class=""><DIV class="stylepoint_body" name="Comments__body" id="Comments__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001411
1412 <P class="">
1413<SPAN class="stylepoint_subsection">Doc Strings</SPAN>
1414
1415 <p>
1416 Python has a unique commenting style using doc strings. A doc
1417 string is a string that is the first statement in a package,
1418 module, class or function. These strings can be extracted
1419 automatically through the <code>__doc__</code> member of the
1420 object and are used by <code>pydoc</code>. (Try running
1421 <code>pydoc</code> on your module to see how it looks.) Our
1422 convention for doc strings is to use the three double-quote
1423 format for strings. A doc string should be organized as a
1424 summary line (one physical line) terminated by a period,
1425 question mark, or exclamation point, followed by a blank line,
1426 followed by the rest of the doc string starting at the same
1427 cursor position as the first quote of the first line. There are
1428 more formatting guidelines for doc strings below.
1429 </p>
1430
1431 </P>
1432 <P class="">
1433<SPAN class="stylepoint_subsection">Modules</SPAN>
1434
1435
1436
1437 <p>
1438 Every file should contain the following items, in order:
1439 <ul>
1440 <li>a copyright statement (for example,
1441 <code>Copyright 2008 Google Inc.</code>)</li>
1442 <li>a license boilerplate. Choose the appropriate boilerplate
1443 for the license used by the project (for example, Apache 2.0, BSD,
1444 LGPL, GPL)</li>
1445 <li>an author line to identify the original author of the file</li>
1446 </ul>
1447 </p>
1448 </P>
1449 <P class="">
1450<SPAN class="stylepoint_subsection">Functions and Methods</SPAN>
1451
1452 <p>
1453 Any function or method which is not both obvious and very short
1454 needs a doc string. Additionally, any externally accessible
1455 function or method regardless of length or simplicity needs a
1456 doc string. The doc string should include what the function does
1457 and have detailed descriptions of the input and output. It
1458 should not, generally, describe how it does it unless it's some
1459 complicated algorithm. For tricky code block/inline comments
1460 within the code are more appropriate. The doc string should give
1461 enough information to write a call to the function without
1462 looking at a single line of the function's code. Args should be
1463 individually documented, an explanation following after a colon,
1464 and should use a uniform hanging indent of 2 or 4 spaces. The
1465 doc string should specify the expected types where specific types
1466 are required. A "Raises:" section should list all exceptions
1467 that can be raised by the function. The doc string for generator
1468 functions should use "Yields:" rather than "Returns:".
1469 </p>
1470
mmentovai9ec7bd62009-12-03 22:25:38 +00001471 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001472<span class="external"></span>def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
1473 <span class="external"> </span>"""Fetches rows from a Bigtable.
1474
1475 <span class="external"> </span>Retrieves rows pertaining to the given keys from the Table instance
1476 <span class="external"> </span>represented by big_table. Silly things may happen if
1477 <span class="external"> </span>other_silly_variable is not None.
1478
1479 <span class="external"> </span>Args:
1480 <span class="external"> </span>big_table: An open Bigtable Table instance.
1481 <span class="external"> </span>keys: A sequence of strings representing the key of each table row
1482 <span class="external"> </span> to fetch.
1483 <span class="external"> </span>other_silly_variable: Another optional variable, that has a much
1484 <span class="external"> </span> longer name than the other args, and which does nothing.
1485
1486 <span class="external"> </span>Returns:
1487 <span class="external"> </span>A dict mapping keys to the corresponding table row data
1488 <span class="external"> </span>fetched. Each row is represented as a tuple of strings. For
1489 <span class="external"> </span>example:
1490
1491 <span class="external"> </span>{'Serak': ('Rigel VII', 'Preparer'),
1492 <span class="external"> </span> 'Zim': ('Irk', 'Invader'),
1493 <span class="external"> </span> 'Lrrr': ('Omicron Persei 8', 'Emperor')}
1494
1495 <span class="external"> </span>If a key from the keys argument is missing from the dictionary,
1496 <span class="external"> </span>then that row was not found in the table.
1497
1498 <span class="external"> </span>Raises:
1499 <span class="external"> </span>IOError: An error occurred accessing the bigtable.Table object.
1500 <span class="external"> </span>"""
1501 <span class="external"> </span>pass
1502<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001503</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001504 </P>
1505 <P class="">
1506<SPAN class="stylepoint_subsection">Classes</SPAN>
1507
1508 <p>
1509 Classes should have a doc string below the class definition describing
1510 the class. If your class has public attributes, they should be documented
1511 here in an Attributes section and follow the same formatting as a
1512 function's Args section.
1513 </p>
1514
mmentovai9ec7bd62009-12-03 22:25:38 +00001515 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001516<span class="external"></span>class SampleClass(object):
1517 <span class="external"> </span>"""Summary of class here.
1518
1519 <span class="external"> </span>Longer class information....
1520 <span class="external"> </span>Longer class information....
1521
1522 <span class="external"> </span>Attributes:
1523 <span class="external"> </span>likes_spam: A boolean indicating if we like SPAM or not.
1524 <span class="external"> </span>eggs: An integer count of the eggs we have laid.
1525 <span class="external"> </span>"""
1526
1527 <span class="external"> </span>def __init__(self, likes_spam=False):
1528 <span class="external"> </span>"""Inits SampleClass with blah."""
1529 <span class="external"> </span>self.likes_spam = likes_spam
1530 <span class="external"> </span>self.eggs = 0
1531
1532 <span class="external"> </span>def public_method(self):
1533 <span class="external"> </span>"""Performs operation blah."""
1534<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001535</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001536
1537 </P>
1538 <P class="">
1539<SPAN class="stylepoint_subsection">Block and Inline Comments</SPAN>
1540
1541 <p>
1542 The final place to have comments is in tricky parts of the
1543 code. If you're going to have to explain it at the next
1544 <a HREF="http://en.wikipedia.org/wiki/Code_review">code review</a>,
1545 you should comment it now. Complicated operations get a few lines of
1546 comments before the operations
1547 commence. Non-obvious ones get comments at the end of the line.
1548 </p>
1549
mmentovai9ec7bd62009-12-03 22:25:38 +00001550 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001551<span class="external"></span># We use a weighted dictionary search to find out where i is in
1552<span class="external"></span># the array. We extrapolate position based on the largest num
1553<span class="external"></span># in the array and the array size and then do binary search to
1554<span class="external"></span># get the exact number.
1555
1556<span class="external"></span>if i &amp; (i-1) == 0: # true iff i is a power of 2
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 To improve legibility, these comments should be at least 2 spaces away
1562 from the code.
1563 </p>
1564
1565 <p>
1566 On the other hand, never describe the code. Assume the person
1567 reading the code knows Python (though not what you're trying to
1568 do) better than you do.
1569 </p>
1570
mmentovai9ec7bd62009-12-03 22:25:38 +00001571 <DIV class=""><PRE class="badcode">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001572<span class="external"></span># BAD COMMENT: Now go through the b array and make sure whenever i occurs
1573<span class="external"></span># the next element is i+1
1574<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001575</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001576
1577 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001578 </DIV></DIV>
1579 </DIV>
1580 <DIV class="">
1581<H3><A name="Classes" id="Classes">Classes</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001582<SPAN class="link_button" id="link-Classes__button" name="link-Classes__button"><A href="?showone=Classes#Classes">
1583 link
1584 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Classes__body','Classes__button')" name="Classes__button" id="Classes__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001585 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001586 If a class inherits from no other base classes, explicitly inherit
1587 from <code>object</code>. This also applies to nested classes.
mmentovai9ec7bd62009-12-03 22:25:38 +00001588 </DIV>
1589 <DIV class=""><DIV class="stylepoint_body" name="Classes__body" id="Classes__body" style="display: none">
mmentovai9ec7bd62009-12-03 22:25:38 +00001590 <DIV class=""><PRE class="badcode">No: <span class="external"></span>class SampleClass:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001591 <span class="external"> </span>pass
1592
1593
1594 <span class="external"></span>class OuterClass:
1595
1596 <span class="external"> </span>class InnerClass:
1597 <span class="external"> </span>pass
1598<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001599</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001600
mmentovai9ec7bd62009-12-03 22:25:38 +00001601 <DIV class=""><PRE>Yes: <span class="external"></span>class SampleClass(object):
apicard@google.comf900c2c2009-07-23 20:09:56 +00001602 <span class="external"> </span>pass
1603
1604
1605 <span class="external"></span>class OuterClass(object):
1606
1607 <span class="external"> </span>class InnerClass(object):
1608 <span class="external"> </span>pass
1609
1610
1611 <span class="external"></span>class ChildClass(ParentClass):
1612 <span class="external"> </span>"""Explicitly inherits from another class already."""
1613<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001614</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001615
1616 <p>Inheriting from <code>object</code> is needed to make properties work
1617 properly, and it will protect your code from one particular potential
1618 incompatibility with Python 3000. It also defines
1619 special methods that implement the default semantics of objects including
1620 <code>__new__</code>, <code>__init__</code>, <code>__delattr__</code>,
1621 <code>__getattribute__</code>, <code>__setattr__</code>,
1622 <code>__hash__</code>, <code>__repr__</code>, and <code>__str__</code>.
1623 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001624 </DIV></DIV>
1625 </DIV>
1626 <DIV class="">
1627<H3><A name="Strings" id="Strings">Strings</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001628<SPAN class="link_button" id="link-Strings__button" name="link-Strings__button"><A href="?showone=Strings#Strings">
1629 link
1630 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Strings__body','Strings__button')" name="Strings__button" id="Strings__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001631 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001632 Use the <code>%</code> operator for formatting strings,
1633 even when the parameters are all strings. Use your best judgement
1634 to decide between <code>+</code> and <code>%</code> though.
mmentovai9ec7bd62009-12-03 22:25:38 +00001635 </DIV>
1636 <DIV class=""><DIV class="stylepoint_body" name="Strings__body" id="Strings__body" style="display: none">
mmentovai9ec7bd62009-12-03 22:25:38 +00001637<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 +00001638 <span class="external"></span>x = imperative + ', ' + expletive + '!'
mmentovai9ec7bd62009-12-03 22:25:38 +00001639 <span class="external"></span>x = 'name: ' + name + '; score: ' + str(n)</PRE></DIV>
1640<DIV class=""><PRE>Yes: <span class="external"></span>x = a + b
apicard@google.comf900c2c2009-07-23 20:09:56 +00001641 <span class="external"></span>x = '%s, %s!' % (imperative, expletive)
mmentovai9ec7bd62009-12-03 22:25:38 +00001642 <span class="external"></span>x = 'name: %s; score: %d' % (name, n)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001643
1644 <p>
1645 Avoid using the <code>+</code> and <code>+=</code> operators to
1646 accumulate a string within a loop. Since strings are immutable, this
1647 creates unnecessary temporary objects and results in quadratic rather
1648 than linear running time. Instead, add each substring to a list and
1649 <code>''.join</code> the list after the loop terminates (or, write each
1650 substring to a <code>cStringIO.StringIO</code> buffer).
1651 </p>
1652
mmentovai9ec7bd62009-12-03 22:25:38 +00001653<DIV class=""><PRE class="badcode">No: <span class="external"></span>employee_table = '&lt;table&gt;'
apicard@google.comf900c2c2009-07-23 20:09:56 +00001654 <span class="external"></span>for last_name, first_name in employee_list:
1655 <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 +00001656 <span class="external"></span>employee_table += '&lt;/table&gt;'</PRE></DIV>
1657<DIV class=""><PRE>Yes: <span class="external"></span>items = ['&lt;table&gt;']
apicard@google.comf900c2c2009-07-23 20:09:56 +00001658 <span class="external"></span>for last_name, first_name in employee_list:
1659 <span class="external"> </span>items.append('&lt;tr&gt;&lt;td&gt;%s, %s&lt;/td&gt;&lt;/tr&gt;' % (last_name, first_name))
1660 <span class="external"></span>items.append('&lt;/table&gt;')
mmentovai9ec7bd62009-12-03 22:25:38 +00001661 <span class="external"></span>employee_table = ''.join(items)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001662
1663 <p>
1664 Use <code>"""</code> for multi-line strings rather than
1665 <code>'''</code>. Note, however, that it is often cleaner to
1666 use implicit line joining since multi-line strings do
1667 not flow with the indentation of the rest of the program:
1668 </p>
1669
mmentovai9ec7bd62009-12-03 22:25:38 +00001670 <DIV class=""><PRE class="badcode"> No<span class="external"></span>:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001671 <span class="external"></span>print """This is pretty ugly.
1672Don'<span class="external"></span>t do this.
1673"""<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001674</PRE></DIV>
1675<DIV class=""><PRE>Ye<span class="external"></span>s:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001676 <span class="external"></span>print ("This is much nicer.\n"
mmentovai9ec7bd62009-12-03 22:25:38 +00001677 <span class="external"></span> "Do it this way.\n")</PRE></DIV>
1678 </DIV></DIV>
1679 </DIV>
1680 <DIV class="">
1681<H3><A name="TODO_Comments" id="TODO_Comments">TODO Comments</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001682<SPAN class="link_button" id="link-TODO_Comments__button" name="link-TODO_Comments__button"><A href="?showone=TODO_Comments#TODO_Comments">
1683 link
1684 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('TODO_Comments__body','TODO_Comments__button')" name="TODO_Comments__button" id="TODO_Comments__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001685 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001686 Use <code>TODO</code> comments for code that is temporary, a
1687 short-term solution, or good-enough but not perfect.
mmentovai9ec7bd62009-12-03 22:25:38 +00001688 </DIV>
1689 <DIV class=""><DIV class="stylepoint_body" name="TODO_Comments__body" id="TODO_Comments__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001690 <p>
1691 <code>TODO</code>s should include the string <code>TODO</code> in
1692 all caps, followed by your
1693
1694 name, e-mail address, or other
1695 identifier
1696 in parentheses. A colon is optional. A comment explaining what there
1697 is to do is required. The main purpose is to have
1698 a consistent <code>TODO</code> format searchable by the person
1699 adding the comment (who can provide more details upon request). A
1700 <code>TODO</code> is not a commitment to provide the fix yourself.
1701 </p>
1702
mmentovai9ec7bd62009-12-03 22:25:38 +00001703 <DIV class=""><PRE># TODO(kl@gmail.com): Drop the use of "has_key".
1704# TODO(Zeke) change this to use relations.</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001705 <p>
1706 If your <code>TODO</code> is of the form "At a future date do
1707 something" make sure that you either include a very specific
1708 date ("Fix by November 2009") or a very specific event
1709 ("Remove this code when all clients can handle XML responses.").
1710 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001711 </DIV></DIV>
1712 </DIV>
1713 <DIV class="">
1714<H3><A name="Imports_formatting" id="Imports_formatting">Imports formatting</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001715<SPAN class="link_button" id="link-Imports_formatting__button" name="link-Imports_formatting__button"><A href="?showone=Imports_formatting#Imports_formatting">
1716 link
1717 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Imports_formatting__body','Imports_formatting__button')" name="Imports_formatting__button" id="Imports_formatting__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001718 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001719 Imports should be on separate lines.
mmentovai9ec7bd62009-12-03 22:25:38 +00001720 </DIV>
1721 <DIV class=""><DIV class="stylepoint_body" name="Imports_formatting__body" id="Imports_formatting__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001722 <p>
1723 E.g.:
1724 </p>
1725
mmentovai9ec7bd62009-12-03 22:25:38 +00001726<DIV class=""><PRE>Yes: <span class="external"></span>import os
1727 <span class="external"></span>import sys</PRE></DIV>
1728<DIV class=""><PRE class="badcode">No: <span class="external"></span>import os, sys</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001729 <p>
1730 Imports are always put at the top of the file, just after any
1731 module comments and doc strings and before module globals and
1732 constants. Imports should be grouped with the order being most generic
1733 to least generic:
1734 </p>
1735 <ul>
1736 <li>standard library imports</li>
1737 <li>third-party imports</li>
1738
1739 <li>application-specific imports</li>
1740 </ul>
1741 <p>
1742 Within each grouping, imports should be sorted lexicographically,
1743 ignoring case, according to each module's full package path.
1744 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001745 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001746<span class="external"></span>import foo
1747<span class="external"></span>from foo import bar
1748<span class="external"></span>from foo.bar import baz
1749<span class="external"></span>from foo.bar import Quux
mmentovai9ec7bd62009-12-03 22:25:38 +00001750<span class="external"></span>from Foob import ar</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001751
1752
mmentovai9ec7bd62009-12-03 22:25:38 +00001753
1754 </DIV></DIV>
1755 </DIV>
1756 <DIV class="">
1757<H3><A name="Statements" id="Statements">Statements</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001758<SPAN class="link_button" id="link-Statements__button" name="link-Statements__button"><A href="?showone=Statements#Statements">
1759 link
1760 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Statements__body','Statements__button')" name="Statements__button" id="Statements__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001761 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001762 Generally only one statement per line.
mmentovai9ec7bd62009-12-03 22:25:38 +00001763 </DIV>
1764 <DIV class=""><DIV class="stylepoint_body" name="Statements__body" id="Statements__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001765 <p>
1766 However, you may put the
1767 result of a test on the same line as the test only if the entire
1768 statement fits on one line. In particular, you can never do so
1769 with <code>try</code>/<code>except</code> since the
1770 <code>try</code> and <code>except</code> can't both fit on the
1771 same line, and you can only do so with an <code>if</code> if
1772 there is no <code>else</code>.
1773 </p>
1774
mmentovai9ec7bd62009-12-03 22:25:38 +00001775 <DIV class=""><PRE>Ye<span class="external"></span>s:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001776
mmentovai9ec7bd62009-12-03 22:25:38 +00001777 <span class="external"></span>if foo: bar(foo)</PRE></DIV>
1778<DIV class=""><PRE class="badcode">No<span class="external"></span>:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001779
1780 <span class="external"></span>if foo: bar(foo)
1781 <span class="external"></span>else: baz(foo)
1782
1783 <span class="external"></span>try: bar(foo)
1784 <span class="external"></span>except ValueError: baz(foo)
1785
1786 <span class="external"></span>try:
1787 <span class="external"> </span>bar(foo)
1788 <span class="external"></span>except ValueError: baz(foo)
1789<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001790</PRE></DIV>
1791 </DIV></DIV>
1792 </DIV>
1793 <DIV class="">
1794<H3><A name="Access_Control" id="Access_Control">Access Control</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001795<SPAN class="link_button" id="link-Access_Control__button" name="link-Access_Control__button"><A href="?showone=Access_Control#Access_Control">
1796 link
1797 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Access_Control__body','Access_Control__button')" name="Access_Control__button" id="Access_Control__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001798 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001799 If an accessor function would be trivial you should use public variables
1800 instead of accessor functions to avoid the extra cost of function
1801 calls in Python. When more functionality is added you can use
1802 <code>property</code> to keep the syntax consistent.
mmentovai9ec7bd62009-12-03 22:25:38 +00001803 </DIV>
1804 <DIV class=""><DIV class="stylepoint_body" name="Access_Control__body" id="Access_Control__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001805 <p>
1806 On the other hand, if access is more complex, or the cost of accessing
1807 the variable is significant, you should use function calls (following the
1808 <a HREF="#naming">Naming</a> guidelines) such as <code>get_foo()</code>
1809 and <code>set_foo()</code>. If the past behavior allowed access through a
1810 property, do not bind the new accessor functions to the property. Any
1811 code still attempting to access the variable by the old method should
1812 break visibly so they are made aware of the change in complexity.
1813 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001814 </DIV></DIV>
1815 </DIV>
1816 <DIV class="">
1817<H3><A name="Naming" id="Naming">Naming</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001818<SPAN class="link_button" id="link-Naming__button" name="link-Naming__button"><A href="?showone=Naming#Naming">
1819 link
1820 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Naming__body','Naming__button')" name="Naming__button" id="Naming__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001821 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001822 <code>module_name, package_name, ClassName, method_name, ExceptionName,
1823 function_name, GLOBAL_VAR_NAME, instance_var_name,
1824 function_parameter_name, local_var_name.</code>
mmentovai9ec7bd62009-12-03 22:25:38 +00001825 </DIV>
1826 <DIV class=""><DIV class="stylepoint_body" name="Naming__body" id="Naming__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001827 <P class="">
1828<SPAN class="stylepoint_subsection">Names to Avoid</SPAN>
1829
1830 <ul>
1831 <li>single character names except for counters or iterators</li>
1832 <li>dashes (<code>-</code>) in any package/module name</li>
1833 <li>
1834<code>__double_leading_and_trailing_underscore__</code> names
1835 (reserved by Python)</li>
1836 </ul>
1837
1838 </P>
1839 <P class="">
1840<SPAN class="stylepoint_subsection">Naming Convention</SPAN>
1841
1842 <ul>
1843 <li>
1844 "Internal" means internal to a module or protected
1845 or private within a class.</li>
1846 <li>
1847 Prepending a single underscore (<code>_</code>) has some
1848 support for protecting module variables and functions (not included
1849 with <code>import * from</code>). Prepending a double underscore
1850 (<code>__</code>) to an instance variable or method
1851 effectively serves to make the variable or method private to its class
1852 (using name mangling).</li>
1853 <li>
1854 Place related classes and top-level functions together in a
1855 module. Unlike Java,
1856 there is no need to limit yourself to one class per module.</li>
1857 <li>
1858 Use CapWords for class names, but lower_with_under.py for module names.
1859 Although there are many existing modules named CapWords.py, this is now
1860 discouraged because it's confusing when the module happens to be
1861 named after a class. ("wait -- did I write
1862 <code>import StringIO</code> or <code>from StringIO import
1863 StringIO</code>?")</li>
1864 </ul>
1865
1866 </P>
1867 <P class="">
1868<SPAN class="stylepoint_subsection">Guidelines derived from Guido's Recommendations</SPAN>
1869
1870 <table rules="all" border="1" cellspacing="2" cellpadding="2">
1871
1872 <tr>
1873 <th>Type</th>
1874 <th>Public</th>
1875 <th>Internal</th>
1876 </tr>
1877
1878
1879
1880 <tr>
1881 <td>Packages</td>
1882 <td><code>lower_with_under</code></td>
1883 <td></td>
1884 </tr>
1885
1886 <tr>
1887 <td>Modules</td>
1888 <td><code>lower_with_under</code></td>
1889 <td><code>_lower_with_under</code></td>
1890 </tr>
1891
1892 <tr>
1893 <td>Classes</td>
1894 <td><code>CapWords</code></td>
1895 <td><code>_CapWords</code></td>
1896 </tr>
1897
1898 <tr>
1899 <td>Exceptions</td>
1900 <td><code>CapWords</code></td>
1901 <td></td>
1902 </tr>
1903
1904
1905
1906 <tr>
1907 <td>Functions</td>
1908 <td><code>lower_with_under()</code></td>
1909 <td><code>_lower_with_under()</code></td>
1910 </tr>
1911
1912 <tr>
1913 <td>Global/Class Constants</td>
1914 <td><code>CAPS_WITH_UNDER</code></td>
1915 <td><code>_CAPS_WITH_UNDER</code></td>
1916 </tr>
1917
1918 <tr>
1919 <td>Global/Class Variables</td>
1920 <td><code>lower_with_under</code></td>
1921 <td><code>_lower_with_under</code></td>
1922 </tr>
1923
1924 <tr>
1925 <td>Instance Variables</td>
1926 <td><code>lower_with_under</code></td>
1927 <td><code>_lower_with_under (protected) or __lower_with_under (private)</code></td>
1928 </tr>
1929
1930
1931
1932 <tr>
1933 <td>Method Names</td>
1934 <td><code>lower_with_under()</code></td>
1935 <td><code>_lower_with_under() (protected) or __lower_with_under() (private)</code></td>
1936 </tr>
1937
1938 <tr>
1939 <td>Function/Method Parameters</td>
1940 <td><code>lower_with_under</code></td>
1941 <td></td>
1942 </tr>
1943
1944 <tr>
1945 <td>Local Variables</td>
1946 <td><code>lower_with_under</code></td>
1947 <td></td>
1948 </tr>
1949
1950
1951 </table>
1952
1953
1954 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001955 </DIV></DIV>
1956 </DIV>
1957 <DIV class="">
1958<H3><A name="Main" id="Main">Main</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001959<SPAN class="link_button" id="link-Main__button" name="link-Main__button"><A href="?showone=Main#Main">
1960 link
1961 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Main__body','Main__button')" name="Main__button" id="Main__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001962 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001963 Even a file meant to be used as a script should be importable and a
1964 mere import should not have the side effect of executing the script's
1965 main functionality. The main functionality should be in a main()
1966 function.
mmentovai9ec7bd62009-12-03 22:25:38 +00001967 </DIV>
1968 <DIV class=""><DIV class="stylepoint_body" name="Main__body" id="Main__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001969 <p>
1970 In Python,
1971 <code>pychecker</code>, <code>pydoc</code>, and unit tests
1972 require modules to be importable. Your code should always check
1973 <code>if __name__ == '__main__'</code> before executing your
1974 main program so that the main program is not executed when the
1975 module is imported.
1976
1977 </p>
1978
1979
1980
1981
1982
1983
1984
mmentovai9ec7bd62009-12-03 22:25:38 +00001985 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001986<span class="external"></span>def main():
1987 <span class="external"> </span>...
1988
1989<span class="external"></span>if __name__ == '__main__':
1990 <span class="external"> </span>main()
1991<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001992</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001993
1994 <p>
1995 All code at the top level will be executed when the module is
1996 imported. Be careful not to call functions, create objects, or
1997 perform other operations that should not be executed when the
1998 file is being <code>pycheck</code>ed or <code>pydoc</code>ed.
1999 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00002000 </DIV></DIV>
2001 </DIV>
2002 </DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002003
2004<H2>Parting Words</H2>
2005 <p>
2006 <em>BE CONSISTENT</em>.
2007 </p>
2008
2009 <p>
2010 If you're editing code, take a few minutes to look at the code
2011 around you and determine its style. If they use spaces around
2012 all their arithmetic operators, you should too. If their
2013 comments have little boxes of hash marks around them, make your
2014 comments have little boxes of hash marks around them too.
2015 </p>
2016
2017 <p>
2018 The point of having style guidelines is to have a common vocabulary
2019 of coding so people can concentrate on what you're saying rather
2020 than on how you're saying it. We present global style rules here so
2021 people know the vocabulary, but local style is also important. If
2022 code you add to a file looks drastically different from the existing
2023 code around it, it throws readers out of their rhythm when they go to
2024 read it. Avoid this.
2025 </p>
2026
2027
2028
2029<p align="right">
mmentovaicd4ce0f2011-03-29 20:30:47 +00002030Revision 2.20
apicard@google.comf900c2c2009-07-23 20:09:56 +00002031</p>
2032
2033
2034<address>
2035 Amit Patel<br>
2036 Antoine Picard<br>
2037 Eugene Jhong<br>
2038 Jeremy Hylton<br>
2039 Matt Smart<br>
2040 Mike Shields<br>
2041</address>
2042</BODY>
2043</HTML>