blob: d1d75c62a0ac8b541b1dd0b4083ba2b7485857a6 [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
mark@chromium.orge33361f2011-11-04 16:55:22 +00009 function GetElementsByName(name) {
10 // Workaround a bug on old versions of opera.
apicard@google.comf900c2c2009-07-23 20:09:56 +000011 if (document.getElementsByName) {
mark@chromium.orge33361f2011-11-04 16:55:22 +000012 return document.getElementsByName(name);
apicard@google.comf900c2c2009-07-23 20:09:56 +000013 } else {
mark@chromium.orge33361f2011-11-04 16:55:22 +000014 return [document.getElementById(name)];
apicard@google.comf900c2c2009-07-23 20:09:56 +000015 }
mark@chromium.orge33361f2011-11-04 16:55:22 +000016 }
17
18 /**
19 * @param {string} namePrefix The prefix of the body name.
20 * @param {function(boolean): boolean} getVisibility Computes the new
21 * visibility state, given the current one.
22 */
23 function ChangeVisibility(namePrefix, getVisibility) {
24 var bodyName = namePrefix + '__body';
25 var buttonName = namePrefix + '__button';
26 var bodyElements = GetElementsByName(bodyName);
27 var linkElement = GetElementsByName('link-' + buttonName)[0];
apicard@google.comf900c2c2009-07-23 20:09:56 +000028 if (bodyElements.length != 1) {
mark@chromium.orge33361f2011-11-04 16:55:22 +000029 throw Error('ShowHideByName() got the wrong number of bodyElements: ' +
30 bodyElements.length);
apicard@google.comf900c2c2009-07-23 20:09:56 +000031 } else {
32 var bodyElement = bodyElements[0];
mark@chromium.orge33361f2011-11-04 16:55:22 +000033 var buttonElement = GetElementsByName(buttonName)[0];
34 var isVisible = bodyElement.style.display != "none";
35 if (getVisibility(isVisible)) {
apicard@google.comf900c2c2009-07-23 20:09:56 +000036 bodyElement.style.display = "inline";
mmentovai8411f0c2010-08-04 17:46:16 +000037 linkElement.style.display = "block";
apicard@google.comf900c2c2009-07-23 20:09:56 +000038 buttonElement.innerHTML = '▽';
39 } else {
40 bodyElement.style.display = "none";
mmentovai8411f0c2010-08-04 17:46:16 +000041 linkElement.style.display = "none";
apicard@google.comf900c2c2009-07-23 20:09:56 +000042 buttonElement.innerHTML = '▶';
43 }
44 }
45 }
46
mark@chromium.orge33361f2011-11-04 16:55:22 +000047 function ShowHideByName(namePrefix) {
48 ChangeVisibility(namePrefix, function(old) { return !old; });
49 }
50
51 function ShowByName(namePrefix) {
52 ChangeVisibility(namePrefix, function() { return true; });
53 }
54
apicard@google.comf900c2c2009-07-23 20:09:56 +000055 function ShowHideAll() {
mark@chromium.orge33361f2011-11-04 16:55:22 +000056 var allButton = GetElementsByName("show_hide_all_button")[0];
apicard@google.comf900c2c2009-07-23 20:09:56 +000057 if (allButton.innerHTML == '▽') {
58 allButton.innerHTML = '▶';
59 SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "none", '▶');
60 } else {
61 allButton.innerHTML = '▽';
62 SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "inline", '▽');
63 }
64 }
65
66 // Recursively sets state of all children
67 // of a particular node.
68 function SetHiddenState(root, newState, newButton) {
69 for (var i = 0; i != root.length; i++) {
70 SetHiddenState(root[i].childNodes, newState, newButton);
71 if (root[i].className == 'showhide_button') {
72 root[i].innerHTML = newButton;
73 }
mmentovai8411f0c2010-08-04 17:46:16 +000074 if (root[i].className == 'stylepoint_body' ||
75 root[i].className == 'link_button') {
apicard@google.comf900c2c2009-07-23 20:09:56 +000076 root[i].style.display = newState;
77 }
78 }
79 }
80
81
mark@chromium.orge33361f2011-11-04 16:55:22 +000082 function EndsWith(str, suffix) {
83 var l = str.length - suffix.length;
84 return l >= 0 && str.indexOf(suffix, l) == l;
85 }
86
87 function RefreshVisibilityFromHashParam() {
88 var hashRegexp = new RegExp('#([^&#]*)$');
89 var hashMatch = hashRegexp.exec(window.location.href);
90 var anchor = hashMatch && GetElementsByName(hashMatch[1])[0];
91 var node = anchor;
92 var suffix = '__body';
93 while (node) {
94 var id = node.id;
95 var matched = id && EndsWith(id, suffix);
96 if (matched) {
97 var len = id.length - suffix.length;
98 ShowByName(matched.substring(0, len));
99 if (anchor.scrollIntoView) {
100 anchor.scrollIntoView();
101 }
102
103 return;
104 }
105 node = node.parentNode;
106 }
107 }
108
109 window.onhashchange = RefreshVisibilityFromHashParam;
110
apicard@google.comf900c2c2009-07-23 20:09:56 +0000111 window.onload = function() {
112 // if the URL contains "?showall=y", expand the details of all children
mark@chromium.orge33361f2011-11-04 16:55:22 +0000113 var showHideAllRegex = new RegExp("[\\?&](showall)=([^&#]*)");
114 var showHideAllValue = showHideAllRegex.exec(window.location.href);
115 if (showHideAllValue != null) {
116 if (showHideAllValue[2] == "y") {
117 SetHiddenState(document.getElementsByTagName("body")[0].childNodes,
118 "inline", '▽');
119 } else {
120 SetHiddenState(document.getElementsByTagName("body")[0].childNodes,
121 "none", '▶');
apicard@google.comf900c2c2009-07-23 20:09:56 +0000122 }
apicard@google.comf900c2c2009-07-23 20:09:56 +0000123 }
mark@chromium.orge33361f2011-11-04 16:55:22 +0000124 var showOneRegex = new RegExp("[\\?&](showone)=([^&#]*)");
125 var showOneValue = showOneRegex.exec(window.location.href);
126 if (showOneValue) {
127 ShowHideByName(showOneValue[2]);
128 }
129
130
131 RefreshVisibilityFromHashParam();
apicard@google.comf900c2c2009-07-23 20:09:56 +0000132 }
133 </SCRIPT>
134</HEAD>
135<BODY>
136<H1>Google Python Style Guide</H1>
137 <p align="right">
138
mark@chromium.orge33361f2011-11-04 16:55:22 +0000139 Revision 2.28
apicard@google.comf900c2c2009-07-23 20:09:56 +0000140 </p>
141
142 <address>
143 Amit Patel<br>
144 Antoine Picard<br>
145 Eugene Jhong<br>
146 Jeremy Hylton<br>
147 Matt Smart<br>
148 Mike Shields<br>
149 </address>
150 <DIV style="margin-left: 50%; font-size: 75%;">
151<P>
152 Each style point has a summary for which additional information is available
153 by toggling the accompanying arrow button that looks this way:
mmentovai8411f0c2010-08-04 17:46:16 +0000154 <SPAN class="showhide_button" style="margin-left: 0; float: none"></SPAN>.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000155 You may toggle all summaries with the big arrow button:
156 </P>
157<DIV style=" font-size: larger; margin-left: +2em;">
mmentovai8411f0c2010-08-04 17:46:16 +0000158<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 +0000159 Toggle all summaries
160 </DIV>
161</DIV>
162<DIV class="toc">
163<DIV class="toc_title">Table of Contents</DIV>
164<TABLE>
165<TR valign="top" class="">
166<TD><DIV class="toc_category"><A href="#Python_Language_Rules">Python Language Rules</A></DIV></TD>
167<TD><DIV class="toc_stylepoint">
mmentovaif7facf92009-10-23 21:01:49 +0000168<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 +0000169</TR>
170<TR valign="top" class="">
171<TD><DIV class="toc_category"><A href="#Python_Style_Rules">Python Style Rules</A></DIV></TD>
172<TD><DIV class="toc_stylepoint">
mmentovaicd4ce0f2011-03-29 20:30:47 +0000173<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 +0000174</TR>
175</TABLE>
176</DIV>
mmentovai9ec7bd62009-12-03 22:25:38 +0000177 <DIV class="">
178<H2 name="Important_Note" id="Important_Note">Important Note</H2>
179 <DIV class="">
180<H3><A name="Displaying_Hidden_Details_in_this_Guide" id="Displaying_Hidden_Details_in_this_Guide">Displaying Hidden Details in this Guide</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000181<SPAN class="link_button" id="link-Displaying_Hidden_Details_in_this_Guide__button" name="link-Displaying_Hidden_Details_in_this_Guide__button"><A href="?showone=Displaying_Hidden_Details_in_this_Guide#Displaying_Hidden_Details_in_this_Guide">
182 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000183 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Displaying_Hidden_Details_in_this_Guide')" name="Displaying_Hidden_Details_in_this_Guide__button" id="Displaying_Hidden_Details_in_this_Guide__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000184 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000185 This style guide contains many details that are initially
186 hidden from view. They are marked by the triangle icon, which you
187 see here on your left. Click it now.
188 You should see "Hooray" appear below.
mmentovai9ec7bd62009-12-03 22:25:38 +0000189 </DIV>
190 <DIV class=""><DIV class="stylepoint_body" name="Displaying_Hidden_Details_in_this_Guide__body" id="Displaying_Hidden_Details_in_this_Guide__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000191 <p>
192 Hooray! Now you know you can expand points to get more
193 details. Alternatively, there's a "toggle all" at the
194 top of this document.
195 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000196 </DIV></DIV>
197 </DIV>
198 </DIV>
199 <DIV class="">
200<H2 name="Background" id="Background">Background</H2>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000201 <p>
202 Python is the main scripting language used at Google. This
203 style guide is a list of <em>do</em>s and <em>don't</em>s for Python
204 programs.
205 </p>
206
mshields@google.com222e6da2010-11-29 20:32:06 +0000207 <p>
208 To help you format code correctly, we've created a <a href="google_python_style.vim">settings
209 file for Vim</a>. For Emacs, the default settings should be fine.
210 </p>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000211
212
mmentovai9ec7bd62009-12-03 22:25:38 +0000213 </DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000214
mmentovai9ec7bd62009-12-03 22:25:38 +0000215 <DIV class="">
216<H2 name="Python_Language_Rules" id="Python_Language_Rules">Python Language Rules</H2>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000217
mmentovai9ec7bd62009-12-03 22:25:38 +0000218 <DIV class="">
219<H3><A name="pychecker" id="pychecker">pychecker</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000220<SPAN class="link_button" id="link-pychecker__button" name="link-pychecker__button"><A href="?showone=pychecker#pychecker">
221 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000222 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('pychecker')" name="pychecker__button" id="pychecker__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000223 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000224 Run <code>pychecker</code> over your code.
mmentovai9ec7bd62009-12-03 22:25:38 +0000225 </DIV>
mmentovai8411f0c2010-08-04 17:46:16 +0000226 <DIV class=""><DIV class="stylepoint_body" name="pychecker__body" id="pychecker__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000227 <P class="">
228<SPAN class="stylepoint_section">Definition: </SPAN>
229 PyChecker is a tool for finding bugs in Python source code. It finds
230 problems that are typically caught by a compiler for less dynamic
231 languages like C and C++. It is similar to lint. Because of the
232 dynamic nature of Python, some warnings may be incorrect; however,
233 spurious warnings should be fairly infrequent.
234 </P>
235 <P class="">
236<SPAN class="stylepoint_section">Pros: </SPAN>
237 Catches easy-to-miss errors like typos, use-vars-before-assignment, etc.
238 </P>
239 <P class="">
240<SPAN class="stylepoint_section">Cons: </SPAN>
241 <code>pychecker</code> isn't perfect. To take
242 advantage of it, we'll need to sometimes: a) Write around it b)
243 Suppress its warnings c) Improve it or d) Ignore it.
244 </P>
245 <P class="">
246<SPAN class="stylepoint_section">Decision: </SPAN>
247 Make sure you run <code>pychecker</code> on your code.
248 </P>
249
250 <p>
251 For information on how to run <code>pychecker</code>, see the
252 <a HREF="http://pychecker.sourceforge.net">pychecker
253 homepage</a>
254 </p>
255 <p>
256 To suppress warnings, you can set a module-level variable named
257 <code>__pychecker__</code> to suppress appropriate warnings.
258 For example:
259 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000260 <DIV class=""><PRE>
261<span class="external"></span>__pychecker__ = 'no-callinit no-classattr'</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000262 <p>
263 Suppressing in this way has the advantage that we can easily search
264 for suppressions and revisit them.
265 </p>
266 <p>
267 You can get a list of pychecker warnings by doing
268 <code>pychecker --help</code>.
269 </p>
270 <p>
271 Unused argument warnings can be suppressed by using `_' as the
272 identifier for the unused argument or prefixing the argument name with
273 `unused_'. In situations where changing the argument names is
274 infeasible, you can mention them at the beginning of the function.
275 For example:
276 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000277 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000278<span class="external"></span>def foo(a, unused_b, unused_c, d=None, e=None):
279 <span class="external"> </span>(d, e) = (d, e) # Silence pychecker
280 <span class="external"> </span>return a
281<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000282</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000283 <p>
284 Ideally, pychecker would be extended to ensure that such `unused
285 declarations' were true.
286 </p>
287
mmentovai9ec7bd62009-12-03 22:25:38 +0000288 </DIV></DIV>
289 </DIV>
290 <DIV class="">
291<H3><A name="Imports" id="Imports">Imports</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000292<SPAN class="link_button" id="link-Imports__button" name="link-Imports__button"><A href="?showone=Imports#Imports">
293 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000294 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Imports')" name="Imports__button" id="Imports__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000295 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000296 Use <code>import</code>s for packages and modules only.
mmentovai9ec7bd62009-12-03 22:25:38 +0000297 </DIV>
298 <DIV class=""><DIV class="stylepoint_body" name="Imports__body" id="Imports__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000299 <P class="">
300<SPAN class="stylepoint_section">Definition: </SPAN>
301 Reusability mechanism for sharing code from one module to another.
302 </P>
303 <P class="">
304<SPAN class="stylepoint_section">Pros: </SPAN>
mmentovaidb989ec2010-11-23 18:02:36 +0000305 The namespace management convention is simple. The source of each
306 identifier is indicated in a consistent way; <code>x.Obj</code> says
307 that object <code>Obj</code> is defined in module <code>x</code>.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000308 </P>
309 <P class="">
mmentovaidb989ec2010-11-23 18:02:36 +0000310<SPAN class="stylepoint_section">Cons: </SPAN> Module names can still collide. Some module names are
311 inconveniently long.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000312 </P>
313 <P class="">
314<SPAN class="stylepoint_section">Decision: </SPAN>
mmentovaidb989ec2010-11-23 18:02:36 +0000315 Use <code>import x</code> for importing packages and modules.
316 <br>
317 Use <code>from x import y</code> where <code>x</code> is
318 the package prefix and <code>y</code> is the module name with no
319 prefix.
320 <br>
321 Use <code>from x import y as z</code> if two modules named
mark@chromium.orge33361f2011-11-04 16:55:22 +0000322 <code>y</code> are to be imported or if <code>y</code> is an
mmentovaidb989ec2010-11-23 18:02:36 +0000323 inconveniently long name.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000324 </P>
mmentovaidb989ec2010-11-23 18:02:36 +0000325 For example the module
326 <code>sound.effects.echo</code> may be imported as follows:
mmentovai9ec7bd62009-12-03 22:25:38 +0000327 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000328<span class="external"></span>from sound.effects import echo
329<span class="external"></span>...
mmentovaidb989ec2010-11-23 18:02:36 +0000330<span class="external"></span>echo.EchoFilter(input, output, delay=0.7, atten=4)
apicard@google.comf900c2c2009-07-23 20:09:56 +0000331<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000332</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000333 <p>
mmentovaidb989ec2010-11-23 18:02:36 +0000334 Do not use relative names in imports. Even if the module is in the
335 same package, use the full package name. This helps prevent
336 unintentionally importing a package twice.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000337 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000338 </DIV></DIV>
339 </DIV>
340 <DIV class="">
341<H3><A name="Packages" id="Packages">Packages</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000342<SPAN class="link_button" id="link-Packages__button" name="link-Packages__button"><A href="?showone=Packages#Packages">
343 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000344 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Packages')" name="Packages__button" id="Packages__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000345 <DIV style="display:inline;" class="">
mmentovaidb989ec2010-11-23 18:02:36 +0000346 Import each module using the full pathname location of the module.
mmentovai9ec7bd62009-12-03 22:25:38 +0000347 </DIV>
348 <DIV class=""><DIV class="stylepoint_body" name="Packages__body" id="Packages__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000349 <P class="">
350<SPAN class="stylepoint_section">Pros: </SPAN>
351 Avoids conflicts in module names. Makes it easier to find modules.
352 </P>
353 <P class="">
354<SPAN class="stylepoint_section">Cons: </SPAN>
355 Makes it harder to deploy code because you have to replicate the
356 package hierarchy.
357 </P>
358 <P class="">
359<SPAN class="stylepoint_section">Decision: </SPAN>
mmentovaidb989ec2010-11-23 18:02:36 +0000360 All new code should import each module by its full package name.
361
apicard@google.comf900c2c2009-07-23 20:09:56 +0000362 </P>
363 <p>
364 Imports should be as follows:
365 </p>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000366
mmentovai9ec7bd62009-12-03 22:25:38 +0000367 <DIV class=""><PRE># Reference in code with complete name.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000368import sound.effects.echo
369
mmentovaidb989ec2010-11-23 18:02:36 +0000370# Reference in code with just module name (preferred).
apicard@google.comf900c2c2009-07-23 20:09:56 +0000371from sound.effects import echo
mmentovai9ec7bd62009-12-03 22:25:38 +0000372</PRE></DIV>
mmentovai9ec7bd62009-12-03 22:25:38 +0000373 </DIV></DIV>
374 </DIV>
375 <DIV class="">
376<H3><A name="Exceptions" id="Exceptions">Exceptions</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000377<SPAN class="link_button" id="link-Exceptions__button" name="link-Exceptions__button"><A href="?showone=Exceptions#Exceptions">
378 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000379 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Exceptions')" name="Exceptions__button" id="Exceptions__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000380 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000381 Exceptions are allowed but must be used carefully.
mmentovai9ec7bd62009-12-03 22:25:38 +0000382 </DIV>
383 <DIV class=""><DIV class="stylepoint_body" name="Exceptions__body" id="Exceptions__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000384 <P class="">
385<SPAN class="stylepoint_section">Definition: </SPAN>
386 Exceptions are a means of breaking out of the normal flow of control
387 of a code block to handle errors or other exceptional conditions.
388 </P>
389 <P class="">
390<SPAN class="stylepoint_section">Pros: </SPAN>
391 The control flow of normal operation code is not cluttered by
392 error-handling code. It also allows the control flow to skip multiple
393 frames when a certain condition occurs, e.g., returning from N
394 nested functions in one step instead of having to carry-through
395 error codes.
396 </P>
397 <P class="">
398<SPAN class="stylepoint_section">Cons: </SPAN>
399 May cause the control flow to be confusing. Easy to miss error
400 cases when making library calls.
401 </P>
402 <P class="">
403<SPAN class="stylepoint_section">Decision: </SPAN>
404
405
406 Exceptions must follow certain conditions:
407
408 <ul>
409 <li>Raise exceptions like this: <code>raise MyException("Error
410 message")</code> or <code>raise MyException</code>. Do not
411 use the two-argument form (<code>raise MyException, "Error
412 message"</code>) or deprecated string-based exceptions
413 (<code>raise "Error message"</code>).</li>
414 <li>Modules or packages should define their own domain-specific
415 base exception class, which should inherit from the built-in
416 Exception class. The base exception for a module should be called
417 <code>Error</code>.
mmentovai9ec7bd62009-12-03 22:25:38 +0000418 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000419<span class="external"></span>class Error(Exception):
mmentovai9ec7bd62009-12-03 22:25:38 +0000420 <span class="external"> </span>pass</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000421</li>
422 <li>Never use catch-all <code>except:</code> statements, or
423 catch <code>Exception</code> or <code>StandardError</code>,
424 unless you are re-raising the exception or in the outermost
425 block in your thread (and printing an error message). Python
426 is very tolerant in this regard and <code>except:</code> will
427 really catch everything including Python syntax errors. It is
428 easy to hide real bugs using <code>except:</code>.</li>
429 <li>Minimize the amount of code in a
430 <code>try</code>/<code>except</code> block. The larger the
431 body of the <code>try</code>, the more likely that an
432 exception will be raised by a line of code that you didn't
433 expect to raise an exception. In those cases,
434 the <code>try</code>/<code>except</code> block hides a real
435 error.</li>
436 <li>Use the <code>finally</code> clause to execute code whether
437 or not an exception is raised in the <code>try</code> block.
438 This is often useful for cleanup, i.e., closing a file.</li>
439 </ul>
440 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000441 </DIV></DIV>
442 </DIV>
443 <DIV class="">
444<H3><A name="Global_variables" id="Global_variables">Global variables</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000445<SPAN class="link_button" id="link-Global_variables__button" name="link-Global_variables__button"><A href="?showone=Global_variables#Global_variables">
446 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000447 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Global_variables')" name="Global_variables__button" id="Global_variables__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000448 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000449 Avoid global variables.
mmentovai9ec7bd62009-12-03 22:25:38 +0000450 </DIV>
451 <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 +0000452 <P class="">
453<SPAN class="stylepoint_section">Definition: </SPAN>
454 Variables that are declared at the module level.
455 </P>
456 <P class="">
457<SPAN class="stylepoint_section">Pros: </SPAN>
458 Occasionally useful.
459 </P>
460 <P class="">
461<SPAN class="stylepoint_section">Cons: </SPAN>
462 Has the potential to change module behavior during the import,
463 because assignments to module-level variables are done when the
464 module is imported.
465 </P>
466 <P class="">
467<SPAN class="stylepoint_section">Decision: </SPAN>
468 Avoid global variables in favor of class variables. Some
469 exceptions are:
470 <ul>
471 <li>Default options for scripts.</li>
472 <li>Module-level constants. For example: <code>PI = 3.14159</code>.
473 Constants should be named using all caps with underscores;
474 see <a HREF="#Naming">Naming</a> below.</li>
475 <li>It is sometimes useful for globals to cache values needed
476 or returned by functions.</li>
477 <li>If needed, globals should be made internal to the module
478 and accessed through public module level functions;
479 see <a HREF="#Naming">Naming</a> below.</li>
480 </ul>
481 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000482 </DIV></DIV>
483 </DIV>
484 <DIV class="">
485<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 +0000486<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">
487 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000488 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Nested/Local/Inner_Classes_and_Functions')" name="Nested/Local/Inner_Classes_and_Functions__button" id="Nested/Local/Inner_Classes_and_Functions__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000489 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000490 Nested/local/inner classes and functions are fine.
mmentovai9ec7bd62009-12-03 22:25:38 +0000491 </DIV>
492 <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 +0000493 <P class="">
494<SPAN class="stylepoint_section">Definition: </SPAN>
mmentovaif7facf92009-10-23 21:01:49 +0000495 A class can be defined inside of a method, function, or class. A
496 function can be defined inside a method or function. Nested functions
497 have read-only access to variables defined in enclosing scopes.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000498 </P>
499 <P class="">
500<SPAN class="stylepoint_section">Pros: </SPAN>
501 Allows definition of utility classes and functions that are only
502 used inside of a very limited scope. Very <a HREF="http://en.wikipedia.org/wiki/Abstract_data_type">ADT</a>-y.
503 </P>
504 <P class="">
505<SPAN class="stylepoint_section">Cons: </SPAN>
506 Instances of nested or local classes cannot be pickled.
507 </P>
508 <P class="">
509<SPAN class="stylepoint_section">Decision: </SPAN>
510 They are fine.
511 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000512 </DIV></DIV>
513 </DIV>
514 <DIV class="">
515<H3><A name="List_Comprehensions" id="List_Comprehensions">List Comprehensions</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000516<SPAN class="link_button" id="link-List_Comprehensions__button" name="link-List_Comprehensions__button"><A href="?showone=List_Comprehensions#List_Comprehensions">
517 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000518 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('List_Comprehensions')" name="List_Comprehensions__button" id="List_Comprehensions__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000519 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000520 Okay to use for simple cases.
mmentovai9ec7bd62009-12-03 22:25:38 +0000521 </DIV>
522 <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 +0000523 <P class="">
524<SPAN class="stylepoint_section">Definition: </SPAN>
525 List comprehensions and generator expressions provide a concise
526 and efficient way to create lists and iterators without
527 resorting to the use of <code>map()</code>,
528 <code>filter()</code>, or <code>lambda</code>.
529 </P>
530 <P class="">
531<SPAN class="stylepoint_section">Pros: </SPAN>
532 Simple list comprehensions can be clearer and simpler than
533 other list creation techniques. Generator expressions can be
534 very efficient, since they avoid the creation of a list
535 entirely.
536 </P>
537 <P class="">
538<SPAN class="stylepoint_section">Cons: </SPAN>
539 Complicated list comprehensions or generator expressions can be
540 hard to read.
541 </P>
542 <P class="">
543<SPAN class="stylepoint_section">Decision: </SPAN>
544 Okay to use for simple cases. Each portion must fit on one line:
545 mapping expression, <code>for</code> clause, filter expression.
546 Multiple <code>for</code> clauses or filter expressions are not
547 permitted. Use loops instead when things get more complicated.
548 </P>
549
mmentovai9ec7bd62009-12-03 22:25:38 +0000550<DIV class=""><PRE class="badcode">No<span class="external"></span>:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000551 <span class="external"></span>result = [(x, y) for x in range(10) for y in range(5) if x * y &gt; 10]
552
553 <span class="external"></span>return ((x, y, z)
554 <span class="external"></span> for x in xrange(5)
555 <span class="external"></span> for y in xrange(5)
556 <span class="external"></span> if x != y
557 <span class="external"></span> for z in xrange(5)
mmentovai9ec7bd62009-12-03 22:25:38 +0000558 <span class="external"></span> if y != z)</PRE></DIV>
559<DIV class=""><PRE>Ye<span class="external"></span>s:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000560 <span class="external"></span>result = []
561 <span class="external"></span>for x in range(10):
562 <span class="external"> </span>for y in range(5):
563 <span class="external"> </span>if x * y &gt; 10:
564 <span class="external"> </span>result.append((x, y))
565
566 <span class="external"></span>for x in xrange(5):
567 <span class="external"> </span>for y in xrange(5):
568 <span class="external"> </span>if x != y:
569 <span class="external"> </span>for z in xrange(5):
570 <span class="external"> </span>if y != z:
571 <span class="external"> </span>yield (x, y, z)
572
573 <span class="external"></span>return ((x, complicated_transform(x))
574 <span class="external"></span> for x in long_generator_function(parameter)
575 <span class="external"></span> if x is not None)
576
577 <span class="external"></span>squares = [x * x for x in range(10)]
578
579 <span class="external"></span>eat(jelly_bean for jelly_bean in jelly_beans
mmentovai9ec7bd62009-12-03 22:25:38 +0000580 <span class="external"></span> if jelly_bean.color == 'black')</PRE></DIV>
581 </DIV></DIV>
582 </DIV>
583 <DIV class="">
584<H3><A name="Default_Iterators_and_Operators" id="Default_Iterators_and_Operators">Default Iterators and Operators</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000585<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">
586 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000587 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Default_Iterators_and_Operators')" name="Default_Iterators_and_Operators__button" id="Default_Iterators_and_Operators__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000588 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000589 Use default iterators and operators for types that support them,
590 like lists, dictionaries, and files.
mmentovai9ec7bd62009-12-03 22:25:38 +0000591 </DIV>
592 <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 +0000593 <P class="">
594<SPAN class="stylepoint_section">Definition: </SPAN>
595 Container types, like dictionaries and lists, define default
596 iterators and membership test operators ("in" and "not in").
597 </P>
598 <P class="">
599<SPAN class="stylepoint_section">Pros: </SPAN>
600 The default iterators and operators are simple and efficient.
601 They express the operation directly, without extra method calls.
602 A function that uses default operators is generic. It can be
603 used with any type that supports the operation.
604 </P>
605 <P class="">
606<SPAN class="stylepoint_section">Cons: </SPAN>
607 You can't tell the type of objects by reading the method names
608 (e.g. has_key() means a dictionary). This is also an advantage.
609 </P>
610 <P class="">
611<SPAN class="stylepoint_section">Decision: </SPAN> Use default iterators and operators for types
612 that support them, like lists, dictionaries, and files. The
613 built-in types define iterator methods, too. Prefer these
614 methods to methods that return lists, except that you should not
615 mutate a container while iterating over it.
616
mmentovai9ec7bd62009-12-03 22:25:38 +0000617<DIV class=""><PRE>Yes: <span class="external"></span>for key in adict: ...
apicard@google.comf900c2c2009-07-23 20:09:56 +0000618 <span class="external"></span>if key not in adict: ...
619 <span class="external"></span>if obj in alist: ...
620 <span class="external"></span>for line in afile: ...
mmentovai9ec7bd62009-12-03 22:25:38 +0000621 <span class="external"></span>for k, v in dict.iteritems(): ...</PRE></DIV>
622<DIV class=""><PRE class="badcode">No: <span class="external"></span>for key in adict.keys(): ...
apicard@google.comf900c2c2009-07-23 20:09:56 +0000623 <span class="external"></span>if not adict.has_key(key): ...
mmentovai9ec7bd62009-12-03 22:25:38 +0000624 <span class="external"></span>for line in afile.readlines(): ...</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000625 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000626 </DIV></DIV>
627 </DIV>
628 <DIV class="">
629<H3><A name="Generators" id="Generators">Generators</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000630<SPAN class="link_button" id="link-Generators__button" name="link-Generators__button"><A href="?showone=Generators#Generators">
631 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000632 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Generators')" name="Generators__button" id="Generators__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000633 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000634 Use generators as needed.
mmentovai9ec7bd62009-12-03 22:25:38 +0000635 </DIV>
636 <DIV class=""><DIV class="stylepoint_body" name="Generators__body" id="Generators__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000637 <P class="">
638<SPAN class="stylepoint_section">Definition: </SPAN>
639 A generator function returns an iterator that yields a value each
640 time it executes a yield statement. After it yields a value, the
641 runtime state of the generator function is suspended until the
642 next value is needed.
643 </P>
644 <P class="">
645<SPAN class="stylepoint_section">Pros: </SPAN>
646 Simpler code, because the state of local variables and control flow
647 are preserved for each call. A generator uses less memory than a
648 function that creates an entire list of values at once.
649 </P>
650 <P class="">
651<SPAN class="stylepoint_section">Cons: </SPAN>
652 None.
653 </P>
654 <P class="">
655<SPAN class="stylepoint_section">Decision: </SPAN>
656 Fine. Use "Yields:" rather than "Returns:" in the
657 doc string for generator functions.
658 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000659 </DIV></DIV>
660 </DIV>
661 <DIV class="">
662<H3><A name="Lambda_Functions" id="Lambda_Functions">Lambda Functions</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000663<SPAN class="link_button" id="link-Lambda_Functions__button" name="link-Lambda_Functions__button"><A href="?showone=Lambda_Functions#Lambda_Functions">
664 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000665 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Lambda_Functions')" name="Lambda_Functions__button" id="Lambda_Functions__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000666 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000667 Okay for one-liners.
mmentovai9ec7bd62009-12-03 22:25:38 +0000668 </DIV>
669 <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 +0000670 <P class="">
671<SPAN class="stylepoint_section">Definition: </SPAN>
672 Lambdas define anonymous functions in an expression, as
673 opposed to a statement. They are often used to define callbacks or
674 operators for higher-order functions like <code>map()</code> and
675 <code>filter()</code>.
676 </P>
677 <P class="">
678<SPAN class="stylepoint_section">Pros: </SPAN>
679 Convenient.
680 </P>
681 <P class="">
682<SPAN class="stylepoint_section">Cons: </SPAN> Harder to read and debug than local functions. The
683 lack of names means stack traces are more difficult to
684 understand. Expressiveness is limited because the function may
685 only contain an expression.
686 </P>
687 <P class="">
688<SPAN class="stylepoint_section">Decision: </SPAN>
689 Okay to use them for one-liners. If the code inside the lambda
690 function is any longer than 60–80 chars, it's probably better to
691 define it as a regular (nested) function.
692 <p>
693 For common operations like multiplication, use the functions from the
694 <code>operator</code> module instead of lambda functions. For
695 example, prefer <code>operator.mul</code> to <code>lambda
696 x, y: x * y</code>.
697 </p>
698 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000699 </DIV></DIV>
700 </DIV>
701 <DIV class="">
702<H3><A name="Default_Argument_Values" id="Default_Argument_Values">Default Argument Values</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000703<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">
704 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000705 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Default_Argument_Values')" name="Default_Argument_Values__button" id="Default_Argument_Values__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000706 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000707 Okay in most cases.
mmentovai9ec7bd62009-12-03 22:25:38 +0000708 </DIV>
709 <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 +0000710 <P class="">
711<SPAN class="stylepoint_section">Definition: </SPAN>
712 You can specify values for variables at the end of a function's
713 parameter list, e.g., <code>def foo(a, b=0):</code>. If
714 <code>foo</code> is called with only one argument,
715 <code>b</code> is set to 0. If it is called with two arguments,
716 <code>b</code> has the value of the second argument.
717 </P>
718 <P class="">
719<SPAN class="stylepoint_section">Pros: </SPAN>
720 Often you have a function that uses lots of default values,
721 but—rarely—you want to override the
722 defaults. Default argument values provide an easy way to do this,
723 without having to define lots of functions for the rare
724 exceptions. Also, Python does not support overloaded
725 methods/functions and default arguments are an easy way of
726 "faking" the overloading behavior.
727 </P>
728 <P class="">
729<SPAN class="stylepoint_section">Cons: </SPAN>
730 Default arguments are evaluated once at module load
731 time. This may cause problems if the argument is a mutable
732 object such as a list or a dictionary. If the function modifies
733 the object (e.g., by appending an item to a list), the default
734 value is modified.
735 </P>
736 <P class="">
737<SPAN class="stylepoint_section">Decision: </SPAN>
738 Okay to use with the following caveats:
739 <p>
740 Do not use mutable objects as default values in the function or method
741 definition.
742 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000743<DIV class=""><PRE>Yes: <span class="external"></span>def foo(a, b=None):
apicard@google.comf900c2c2009-07-23 20:09:56 +0000744 <span class="external"> </span>if b is None:
mmentovai9ec7bd62009-12-03 22:25:38 +0000745 <span class="external"> </span>b = []</PRE></DIV>
746<DIV class=""><PRE class="badcode">No: <span class="external"></span>def foo(a, b=[]):
747 <span class="external"> </span>...</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000748 <p>
mmentovaif7facf92009-10-23 21:01:49 +0000749 Calling code must use named values for arguments with a default value.
750 This helps document the code somewhat and helps prevent and detect
apicard@google.comf900c2c2009-07-23 20:09:56 +0000751 interface breakage when more arguments are added.
752 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000753<DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000754<span class="external"></span>def foo(a, b=1):
mmentovai9ec7bd62009-12-03 22:25:38 +0000755 <span class="external"> </span>...</PRE></DIV>
756<DIV class=""><PRE>Yes: <span class="external"></span>foo(1)
757 <span class="external"></span>foo(1, b=2)</PRE></DIV>
758<DIV class=""><PRE class="badcode">No: <span class="external"></span>foo(1, 2)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000759 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000760 </DIV></DIV>
761 </DIV>
762 <DIV class="">
763<H3><A name="Properties" id="Properties">Properties</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000764<SPAN class="link_button" id="link-Properties__button" name="link-Properties__button"><A href="?showone=Properties#Properties">
765 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000766 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Properties')" name="Properties__button" id="Properties__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000767 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000768 Use properties for accessing or setting data where you would
769 normally have used simple, lightweight accessor or setter methods.
mmentovai9ec7bd62009-12-03 22:25:38 +0000770 </DIV>
771 <DIV class=""><DIV class="stylepoint_body" name="Properties__body" id="Properties__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000772 <P class="">
773<SPAN class="stylepoint_section">Definition: </SPAN> A way to wrap method calls for getting and
774 setting an attribute as a standard attribute access when the
775 computation is lightweight.
776 </P>
777 <P class="">
778<SPAN class="stylepoint_section">Pros: </SPAN> Readability is increased by eliminating explicit
779 get and set method calls for simple attribute access. Allows
780 calculations to be lazy. Considered the Pythonic way to
781 maintain the interface of a class. In terms of performance,
782 allowing properties bypasses needing trivial accessor methods
783 when a direct variable access is reasonable. This also allows
784 accessor methods to be added in the future without breaking the
785 interface.
786 </P>
787 <P class="">
788<SPAN class="stylepoint_section">Cons: </SPAN> Properties are specified after the getter and
789 setter methods are declared, requiring one to notice they are
790 used for properties farther down in the code (except for readonly
791 properties created with the <code>@property</code> decorator - see
792 below). Must inherit from
793 <code>object</code>. Can hide side-effects much like operator
794 overloading. Can be confusing for subclasses.
795 </P>
796 <P class="">
797<SPAN class="stylepoint_section">Decision: </SPAN> Use properties in new code to access or
798 set data where you would normally have used simple, lightweight
799 accessor or setter methods. Read-only properties should be created
800 with the <code>@property</code>
801 <a HREF="#Function_and_Method_Decorators">decorator</a>.
802
803 <p><a id="properties-template-dp">
804 Inheritance with properties can be non-obvious if the property itself is
805 not overridden. Thus one must make sure that accessor methods are
806 called indirectly to ensure methods overridden in subclasses are called
807 by the property (using the Template Method DP).
808 </a></p>
809
mmentovai9ec7bd62009-12-03 22:25:38 +0000810 <DIV class=""><PRE>Yes: <span class="external"></span>import math
apicard@google.comf900c2c2009-07-23 20:09:56 +0000811
812 <span class="external"></span>class Square(object):
813 <span class="external"> </span>"""A square with two properties: a writable area and a read-only perimeter.
814
815 <span class="external"> </span>To use:
816 <span class="external"> </span>&gt;&gt;&gt; sq = Square(3)
817 <span class="external"> </span>&gt;&gt;&gt; sq.area
818 <span class="external"> </span>9
819 <span class="external"> </span>&gt;&gt;&gt; sq.perimeter
820 <span class="external"> </span>12
821 <span class="external"> </span>&gt;&gt;&gt; sq.area = 16
822 <span class="external"> </span>&gt;&gt;&gt; sq.side
823 <span class="external"> </span>4
824 <span class="external"> </span>&gt;&gt;&gt; sq.perimeter
825 <span class="external"> </span>16
826 <span class="external"> </span>"""
827
828 <span class="external"> </span>def __init__(self, side):
829 <span class="external"> </span>self.side = side
830
831 <span class="external"> </span>def __get_area(self):
832 <span class="external"> </span>"""Calculates the 'area' property."""
833 <span class="external"> </span>return self.side ** 2
834
835 <span class="external"> </span>def ___get_area(self):
836 <span class="external"> </span>"""Indirect accessor for 'area' property."""
837 <span class="external"> </span>return self.__get_area()
838
839 <span class="external"> </span>def __set_area(self, area):
840 <span class="external"> </span>"""Sets the 'area' property."""
841 <span class="external"> </span>self.side = math.sqrt(area)
842
843 <span class="external"> </span>def ___set_area(self, area):
844 <span class="external"> </span>"""Indirect setter for 'area' property."""
845 <span class="external"> </span>self._SetArea(area)
846
847 <span class="external"> </span>area = property(___get_area, ___set_area,
848 <span class="external"> </span> doc="""Gets or sets the area of the square.""")
849
850 <span class="external"> </span>@property
851 <span class="external"> </span>def perimeter(self):
852 <span class="external"> </span>return self.side * 4
853<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000854</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000855 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000856 </DIV></DIV>
857 </DIV>
858 <DIV class="">
859<H3><A name="True/False_evaluations" id="True/False_evaluations">True/False evaluations</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000860<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">
861 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000862 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('True/False_evaluations')" name="True/False_evaluations__button" id="True/False_evaluations__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000863 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000864 Use the "implicit" false if at all possible.
mmentovai9ec7bd62009-12-03 22:25:38 +0000865 </DIV>
866 <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 +0000867 <P class="">
868<SPAN class="stylepoint_section">Definition: </SPAN> Python evaluates certain values as <code>false</code>
869 when in a boolean context. A quick "rule of thumb" is that all
870 "empty" values are considered <code>false</code> so <code>0, None, [], {},
871 ""</code> all evaluate as <code>false</code> in a boolean context.
872 </P>
873 <P class="">
874<SPAN class="stylepoint_section">Pros: </SPAN> Conditions using Python booleans are easier to read
875 and less error-prone. In most cases, they're also faster.
876 </P>
877 <P class="">
878<SPAN class="stylepoint_section">Cons: </SPAN>
879 May look strange to C/C++ developers.
880 </P>
881 <P class="">
882<SPAN class="stylepoint_section">Decision: </SPAN>
883 Use the "implicit" false if at all possible, e.g., <code>if
884 foo:</code> rather than <code>if foo != []:</code>. There are a
885 few caveats that you should keep in mind though:
886 <ul>
887 <li>
888 Never use <code>==</code> or <code>!=</code> to compare
889 singletons like <code>None</code>. Use <code>is</code>
890 or <code>is not</code>.</li>
891
892 <li>Beware of writing <code>if x:</code> when you really mean
893 <code>if x is not None:</code>—e.g., when testing whether
894 a variable or argument that defaults to <code>None</code> was
895 set to some other value. The other value might be a value
896 that's false in a boolean context!</li>
897
898 <li>
899 Never compare a boolean variable to <code>False</code> using
900 <code>==</code>. Use <code>if not x:</code> instead. If
901 you need to distinguish <code>False</code> from
902 <code>None</code> then chain the expressions,
903 such as <code>if not x and x is not None:</code>.
904 </li>
905
906 <li>
907 For sequences (strings, lists, tuples), use the fact that
908 empty sequences are false, so <code>if not seq:</code> or
909 <code>if seq:</code> is preferable to <code>if
910 len(seq):</code> or <code>if not
911 len(seq):</code>.</li>
912
913 <li>
914 When handling integers, implicit false may involve more risk than
915 benefit (i.e., accidentally handling <code>None</code> as 0). You may
916 compare a value which is known to be an integer (and is not the
917 result of <code>len()</code>) against the integer 0.
mmentovai9ec7bd62009-12-03 22:25:38 +0000918<DIV class=""><PRE>Yes: <span class="external"></span>if not users:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000919 <span class="external"> </span>print 'no users'
920
921 <span class="external"></span>if foo == 0:
922 <span class="external"> </span>self.handle_zero()
923
924 <span class="external"></span>if i % 10 == 0:
mmentovai9ec7bd62009-12-03 22:25:38 +0000925 <span class="external"> </span>self.handle_multiple_of_ten()</PRE></DIV>
926<DIV class=""><PRE class="badcode">No: <span class="external"></span>if len(users) == 0:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000927 <span class="external"> </span>print 'no users'
928
929 <span class="external"></span>if foo is not None and not foo:
930 <span class="external"> </span>self.handle_zero()
931
932 <span class="external"></span>if not i % 10:
mmentovai9ec7bd62009-12-03 22:25:38 +0000933 <span class="external"> </span>self.handle_multiple_of_ten()</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000934</li>
935
936 <li>
937 Note that <code>'0'</code> (i.e., <code>0</code> as string)
938 evaluates to true.</li>
939 </ul>
940 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000941 </DIV></DIV>
942 </DIV>
943 <DIV class="">
944<H3><A name="Deprecated_Language_Features" id="Deprecated_Language_Features">Deprecated Language Features</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000945<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">
946 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000947 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Deprecated_Language_Features')" name="Deprecated_Language_Features__button" id="Deprecated_Language_Features__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000948 <DIV style="display:inline;" class="">
mmentovaif7facf92009-10-23 21:01:49 +0000949 Use string methods instead of the <code>string</code> module
950 where possible. Use function call syntax instead
951 of <code>apply</code>. Use list comprehensions
952 and <code>for</code> loops instead of <code>filter</code>,
953 <code>map</code>, and <code>reduce</code>.
mmentovai9ec7bd62009-12-03 22:25:38 +0000954 </DIV>
955 <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 +0000956 <P class="">
mmentovaif7facf92009-10-23 21:01:49 +0000957<SPAN class="stylepoint_section">Definition: </SPAN>
958 Current versions of Python provide alternative constructs
959 that people find generally preferable.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000960 </P>
961 <P class="">
mmentovaif7facf92009-10-23 21:01:49 +0000962<SPAN class="stylepoint_section">Decision: </SPAN>
963 We do not use any Python version which does not support
964 these features, so there is no reason not to use the new
965 styles.
mmentovai9ec7bd62009-12-03 22:25:38 +0000966<DIV class=""><PRE class="badcode">No: <span class="external"></span>words = string.split(foo, ':')
mmentovaif7facf92009-10-23 21:01:49 +0000967
968 <span class="external"></span>map(lambda x: x[1], filter(lambda x: x[2] == 5, my_list))
969
mmentovai9ec7bd62009-12-03 22:25:38 +0000970 <span class="external"></span>apply(fn, args, kwargs)</PRE></DIV>
971<DIV class=""><PRE>Yes: <span class="external"></span>words = foo.split(':')
mmentovaif7facf92009-10-23 21:01:49 +0000972
973 <span class="external"></span>[x[1] for x in my_list if x[2] == 5]
974
mmentovai9ec7bd62009-12-03 22:25:38 +0000975 <span class="external"></span>fn(*args, **kwargs)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000976 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000977 </DIV></DIV>
978 </DIV>
979 <DIV class="">
980<H3><A name="Lexical_Scoping" id="Lexical_Scoping">Lexical Scoping</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000981<SPAN class="link_button" id="link-Lexical_Scoping__button" name="link-Lexical_Scoping__button"><A href="?showone=Lexical_Scoping#Lexical_Scoping">
982 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000983 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Lexical_Scoping')" name="Lexical_Scoping__button" id="Lexical_Scoping__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000984 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000985 Okay to use.
mmentovai9ec7bd62009-12-03 22:25:38 +0000986 </DIV>
987 <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 +0000988 <P class="">
989<SPAN class="stylepoint_section">Definition: </SPAN>
990 A nested Python function can refer to variables defined in
991 enclosing functions, but can not assign to them. Variable
992 bindings are resolved using lexical scoping, that is, based on
993 the static program text. Any assignment to a name in a block
994 will cause Python to treat all references to that name as a
995 local variable, even if the use precedes the assignment. If a
996 global declaration occurs, the name is treated as a global
997 variable.
998
999 <p>
1000 An example of the use of this feature is:
1001 </p>
1002
mmentovai9ec7bd62009-12-03 22:25:38 +00001003 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001004<span class="external"></span>def get_adder(summand1):
1005 <span class="external"> </span>"""Returns a function that adds numbers to a given number."""
1006 <span class="external"> </span>def adder(summand2):
1007 <span class="external"> </span>return summand1 + summand2
1008
1009 <span class="external"> </span>return adder
1010<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001011</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001012 </P>
1013 <P class="">
1014<SPAN class="stylepoint_section">Pros: </SPAN>
1015 Often results in clearer, more elegant code. Especially comforting
1016 to experienced Lisp and Scheme (and Haskell and ML and …)
1017 programmers.
1018 </P>
1019 <P class="">
1020<SPAN class="stylepoint_section">Cons: </SPAN>
1021 Can lead to confusing bugs. Such as this example based on
1022 <a HREF="http://www.python.org/dev/peps/pep-0227/">PEP-0227</a>:
mmentovai9ec7bd62009-12-03 22:25:38 +00001023<DIV class=""><PRE class="badcode">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001024<span class="external"></span>i = 4
1025<span class="external"></span>def foo(x):
1026 <span class="external"> </span>def bar():
1027 <span class="external"> </span>print i,
1028 <span class="external"> </span># ...
1029 <span class="external"> </span># A bunch of code here
1030 <span class="external"> </span># ...
1031 <span class="external"> </span>for i in x: # Ah, i *is* local to Foo, so this is what Bar sees
1032 <span class="external"> </span>print i,
mmentovai9ec7bd62009-12-03 22:25:38 +00001033 <span class="external"> </span>bar()</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001034 <p>
1035 So <code>foo([1, 2, 3])</code> will print <code>1 2 3 3</code>, not
1036 <code>1 2 3 4</code>.
1037 </p>
1038 </P>
1039 <P class="">
1040<SPAN class="stylepoint_section">Decision: </SPAN>
1041 Okay to use.
1042 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001043 </DIV></DIV>
1044 </DIV>
1045 <DIV class="">
1046<H3><A name="Function_and_Method_Decorators" id="Function_and_Method_Decorators">Function and Method Decorators</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001047<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">
1048 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001049 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Function_and_Method_Decorators')" name="Function_and_Method_Decorators__button" id="Function_and_Method_Decorators__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001050 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001051 Use decorators judiciously when there is a clear advantage.
mmentovai9ec7bd62009-12-03 22:25:38 +00001052 </DIV>
1053 <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 +00001054 <P class="">
1055<SPAN class="stylepoint_section">Definition: </SPAN>
1056
1057 <a HREF="http://www.python.org/doc/2.4.3/whatsnew/node6.html">Decorators
1058 for Functions and Methods</a>
1059 (a.k.a "the <code>@</code> notation").
1060 The most common decorators are <code>@classmethod</code> and
1061 <code>@staticmethod</code>, for converting ordinary methods to class or
1062 static methods. However, the decorator syntax allows for
1063 user-defined decorators as well. Specifically, for some function
1064 <code>my_decorator</code>, this:
mmentovai9ec7bd62009-12-03 22:25:38 +00001065 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001066<span class="external"></span>class C(object):
1067 <span class="external"> </span>@my_decorator
1068 <span class="external"> </span>def method(self):
1069 <span class="external"> </span># method body ...
1070<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001071</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001072
1073 is equivalent to:
mmentovai9ec7bd62009-12-03 22:25:38 +00001074 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001075<span class="external"></span>class C(object):
1076 <span class="external"> </span>def method(self):
1077 <span class="external"> </span># method body ...
1078 <span class="external"> </span>method = my_decorator(method)
1079<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001080</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001081 </P>
1082 <P class="">
1083<SPAN class="stylepoint_section">Pros: </SPAN> Elegantly specifies some transformation on a method; the
1084 transformation might eliminate some repetitive code, enforce invariants,
1085 etc.
1086 </P>
1087 <P class="">
1088<SPAN class="stylepoint_section">Cons: </SPAN> Decorators can perform arbitrary operations on a
1089 function's arguments or return values, resulting in surprising
1090 implicit behavior.
1091 Additionally, decorators execute at import time. Failures in decorator
1092 code are pretty much impossible to recover from.
1093 </P>
1094 <P class="">
1095<SPAN class="stylepoint_section">Decision: </SPAN> Use decorators judiciously when there is a clear
1096 advantage. Decorators should follow the same import and naming
1097 guidelines as functions. Decorator pydoc should clearly state that the
1098 function is a decorator. Write unit tests for decorators.
1099
1100 <p>
1101 Avoid external dependencies in the decorator itself (e.g. don't rely on
1102 files, sockets, database connections, etc.), since they might not be
1103 available when the decorator runs (at import time, perhaps from
1104 <code>pychecker</code> or other tools). A decorator that is
1105 called with valid parameters should (as much as possible) be guaranteed
1106 to succeed in all cases.
1107 </p>
1108 <p>
1109 Decorators are a special case of "top level code" - see
1110 <a HREF="#Main">main</a> for more discussion.
1111 </p>
1112 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001113 </DIV></DIV>
1114 </DIV>
1115 <DIV class="">
1116<H3><A name="Threading" id="Threading">Threading</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001117<SPAN class="link_button" id="link-Threading__button" name="link-Threading__button"><A href="?showone=Threading#Threading">
1118 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001119 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Threading')" name="Threading__button" id="Threading__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001120 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001121 Do not rely on the atomicity of built-in types.
mmentovai9ec7bd62009-12-03 22:25:38 +00001122 </DIV>
1123 <DIV class=""><DIV class="stylepoint_body" name="Threading__body" id="Threading__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001124 <p>
1125 While Python's built-in data types such as dictionaries appear
1126 to have atomic operations, there are corner cases where they
1127 aren't atomic (e.g. if <code>__hash__</code> or
1128 <code>__eq__</code> are implemented as Python methods) and their
1129 atomicity should not be relied upon. Neither should you rely on
1130 atomic variable assignment (since this in turn depends on
1131 dictionaries).
1132 </p>
1133
1134 <p>
1135 Use the Queue module's <code>Queue</code> data type as the preferred
1136 way to
1137 communicate data between threads. Otherwise, use the threading
1138 module and its locking primitives. Learn about the proper use
1139 of condition variables so you can use
1140 <code>threading.Condition</code> instead of using lower-level
1141 locks.
1142 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001143 </DIV></DIV>
1144 </DIV>
1145 <DIV class="">
1146<H3><A name="Power_Features" id="Power_Features">Power Features</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001147<SPAN class="link_button" id="link-Power_Features__button" name="link-Power_Features__button"><A href="?showone=Power_Features#Power_Features">
1148 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001149 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Power_Features')" name="Power_Features__button" id="Power_Features__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001150 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001151 Avoid these features.
mmentovai9ec7bd62009-12-03 22:25:38 +00001152 </DIV>
1153 <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 +00001154 <P class="">
1155<SPAN class="stylepoint_section">Definition: </SPAN> Python is an extremely flexible language and
1156 gives you many fancy features such as metaclasses, access to bytecode,
1157 on-the-fly compilation, dynamic inheritance, object reparenting,
1158 import hacks, reflection, modification of system internals,
1159 etc.
1160 </P>
1161 <P class="">
1162<SPAN class="stylepoint_section">Pros: </SPAN> These are powerful language features. They can
1163 make your code more compact.
1164 </P>
1165 <P class="">
1166<SPAN class="stylepoint_section">Cons: </SPAN> It's very tempting to use these "cool" features
1167 when they're not absolutely necessary. It's harder to read,
1168 understand, and debug code that's using unusual features
1169 underneath. It doesn't seem that way at first (to the original
1170 author), but when revisiting the code, it tends to be more
1171 difficult than code that is longer but is straightforward.
1172 </P>
1173 <P class="">
1174<SPAN class="stylepoint_section">Decision: </SPAN>
1175 Avoid these features in
1176 your code.
1177 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001178 </DIV></DIV>
1179 </DIV>
1180 </DIV>
1181 <DIV class="">
1182<H2 name="Python_Style_Rules" id="Python_Style_Rules">Python Style Rules</H2>
1183 <DIV class="">
1184<H3><A name="Semicolons" id="Semicolons">Semicolons</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001185<SPAN class="link_button" id="link-Semicolons__button" name="link-Semicolons__button"><A href="?showone=Semicolons#Semicolons">
1186 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001187 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Semicolons')" name="Semicolons__button" id="Semicolons__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001188 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001189 Do not terminate your lines with semi-colons and do not use
1190 semi-colons to put two commands on the same line.
mmentovai9ec7bd62009-12-03 22:25:38 +00001191 </DIV>
1192 <DIV class=""><DIV class="stylepoint_body" name="Semicolons__body" id="Semicolons__body" style="display: none">
mmentovai9ec7bd62009-12-03 22:25:38 +00001193 </DIV></DIV>
1194 </DIV>
1195 <DIV class="">
1196<H3><A name="Line_length" id="Line_length">Line length</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001197<SPAN class="link_button" id="link-Line_length__button" name="link-Line_length__button"><A href="?showone=Line_length#Line_length">
1198 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001199 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Line_length')" name="Line_length__button" id="Line_length__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001200 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001201 Maximum line length is <em>80 characters</em>.
mmentovai9ec7bd62009-12-03 22:25:38 +00001202 </DIV>
1203 <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 +00001204 <p>
1205 Exception: lines importing modules may end up longer than 80
1206 characters only if using Python 2.4 or
1207 earlier.
1208 </p>
1209
1210 <p>
mark@chromium.orge33361f2011-11-04 16:55:22 +00001211 Do not use backslash line continuation.
1212 </p>
1213
1214 <p>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001215 Make use of Python's
1216
1217 <a HREF="http://www.python.org/doc/ref/implicit-joining.html">implicit
1218 line joining inside parentheses, brackets and braces</a>.
1219 If necessary, you can add an extra pair of parentheses around an
1220 expression.
1221 </p>
1222
1223
mmentovai9ec7bd62009-12-03 22:25:38 +00001224 <DIV class=""><PRE>Yes: foo_bar(self, width, height, color='black', design=None, x='foo',
apicard@google.comf900c2c2009-07-23 20:09:56 +00001225 emphasis=None, highlight=0)
1226
1227 if (width == 0 and height == 0 and
mmentovai9ec7bd62009-12-03 22:25:38 +00001228 color == 'red' and emphasis == 'strong'):</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001229
1230
1231 <p>
1232 When a literal string won't fit on a single line, use parentheses for
1233 implicit line joining.
1234 </p>
1235
mmentovai9ec7bd62009-12-03 22:25:38 +00001236 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001237<span class="external"></span>x = ('This will build a very long long '
mmentovai9ec7bd62009-12-03 22:25:38 +00001238<span class="external"></span> 'long long long long long long string')</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001239
1240 <p>
1241 Make note of the indentation of the elements in the line
1242 continuation examples above; see the
1243 <a HREF="#indentation">indentation</a>
1244 section for explanation.
1245 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001246 </DIV></DIV>
1247 </DIV>
1248 <DIV class="">
1249<H3><A name="Parentheses" id="Parentheses">Parentheses</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001250<SPAN class="link_button" id="link-Parentheses__button" name="link-Parentheses__button"><A href="?showone=Parentheses#Parentheses">
1251 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001252 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Parentheses')" name="Parentheses__button" id="Parentheses__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001253 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001254 Use parentheses sparingly.
mmentovai9ec7bd62009-12-03 22:25:38 +00001255 </DIV>
1256 <DIV class=""><DIV class="stylepoint_body" name="Parentheses__body" id="Parentheses__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001257 <p>
1258 Do not use them in return statements or conditional statements unless
1259 using parentheses for implied line continuation. (See above.)
1260 It is however fine to use parentheses around tuples.
1261 </p>
1262
mmentovai9ec7bd62009-12-03 22:25:38 +00001263<DIV class=""><PRE>Yes: <span class="external"></span>if foo:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001264 <span class="external"> </span>bar()
1265 <span class="external"></span>while x:
1266 <span class="external"> </span>x = bar()
1267 <span class="external"></span>if x and y:
1268 <span class="external"> </span>bar()
1269 <span class="external"></span>if not x:
1270 <span class="external"> </span>bar()
1271 <span class="external"></span>return foo
mmentovai9ec7bd62009-12-03 22:25:38 +00001272 <span class="external"></span>for (x, y) in dict.items(): ...</PRE></DIV>
1273<DIV class=""><PRE class="badcode">No: <span class="external"></span>if (x):
apicard@google.comf900c2c2009-07-23 20:09:56 +00001274 <span class="external"> </span>bar()
1275 <span class="external"></span>if not(x):
1276 <span class="external"> </span>bar()
mmentovai9ec7bd62009-12-03 22:25:38 +00001277 <span class="external"></span>return (foo)</PRE></DIV>
1278 </DIV></DIV>
1279 </DIV>
1280 <DIV class="">
1281<H3><A name="Indentation" id="Indentation">Indentation</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001282<SPAN class="link_button" id="link-Indentation__button" name="link-Indentation__button"><A href="?showone=Indentation#Indentation">
1283 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001284 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Indentation')" name="Indentation__button" id="Indentation__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001285 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001286 Indent your code blocks with <em>4 spaces</em>.
mmentovai9ec7bd62009-12-03 22:25:38 +00001287 </DIV>
1288 <DIV class=""><DIV class="stylepoint_body" name="Indentation__body" id="Indentation__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001289 <p>
1290 Never use tabs or mix tabs and spaces.
1291 In cases of implied line continuation, you should align wrapped elements
1292 either vertically, as per the examples in the
1293 <a HREF="#Line_length">line length</a> section; or using a hanging
1294 indent of 4 spaces, in which case there should be no argument on
1295 the first line.
1296 </p>
1297
1298
mmentovai9ec7bd62009-12-03 22:25:38 +00001299<DIV class=""><PRE>Yes: # Aligned with opening delimiter
apicard@google.comf900c2c2009-07-23 20:09:56 +00001300 foo = long_function_name(var_one, var_two,
1301 var_three, var_four)
1302
1303 # 4-space hanging indent; nothing on first line
1304 foo = long_function_name(
1305 var_one, var_two, var_three,
mmentovai9ec7bd62009-12-03 22:25:38 +00001306 var_four)</PRE></DIV>
1307<DIV class=""><PRE class="badcode">No: <span class="external"></span># Stuff on first line forbidden
apicard@google.comf900c2c2009-07-23 20:09:56 +00001308 <span class="external"></span>foo = long_function_name(var_one, var_two,
1309 <span class="external"></span> var_three, var_four)
1310
1311 <span class="external"></span># 2-space hanging indent forbidden
1312 <span class="external"></span>foo = long_function_name(
1313 <span class="external"></span> var_one, var_two, var_three,
mmentovai9ec7bd62009-12-03 22:25:38 +00001314 <span class="external"></span> var_four)</PRE></DIV>
1315 </DIV></DIV>
1316 </DIV>
1317 <DIV class="">
1318<H3><A name="Blank_Lines" id="Blank_Lines">Blank Lines</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001319<SPAN class="link_button" id="link-Blank_Lines__button" name="link-Blank_Lines__button"><A href="?showone=Blank_Lines#Blank_Lines">
1320 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001321 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Blank_Lines')" name="Blank_Lines__button" id="Blank_Lines__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001322 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001323 Two blank lines between top-level definitions, one blank line
1324 between method definitions.
mmentovai9ec7bd62009-12-03 22:25:38 +00001325 </DIV>
1326 <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 +00001327 <p>
1328 Two blank lines between top-level definitions, be they function
1329 or class definitions. One blank line between method definitions
1330 and between the <code>class</code> line and the first method.
1331 Use single blank lines as you judge appropriate within functions or
1332 methods.
1333 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001334 </DIV></DIV>
1335 </DIV>
1336 <DIV class="">
1337<H3><A name="Whitespace" id="Whitespace">Whitespace</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001338<SPAN class="link_button" id="link-Whitespace__button" name="link-Whitespace__button"><A href="?showone=Whitespace#Whitespace">
1339 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001340 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Whitespace')" name="Whitespace__button" id="Whitespace__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001341 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001342 Follow standard typographic rules for the use of spaces around
1343 punctuation.
mmentovai9ec7bd62009-12-03 22:25:38 +00001344 </DIV>
1345 <DIV class=""><DIV class="stylepoint_body" name="Whitespace__body" id="Whitespace__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001346 <p>
1347 No whitespace inside parentheses, brackets or braces.
1348 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001349<DIV class=""><PRE>Yes: <span class="external"></span>spam(ham[1], {eggs: 2}, [])</PRE></DIV>
1350<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 +00001351 <p>
1352 No whitespace before a comma, semicolon, or colon. Do use
1353 whitespace after a comma, semicolon, or colon except at the end
1354 of the line.
1355 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001356<DIV class=""><PRE>Yes: <span class="external"></span>if x == 4:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001357 <span class="external"> </span>print x, y
mmentovai9ec7bd62009-12-03 22:25:38 +00001358 <span class="external"></span>x, y = y, x</PRE></DIV>
1359<DIV class=""><PRE class="badcode">No: <span class="external"></span>if x == 4 :
apicard@google.comf900c2c2009-07-23 20:09:56 +00001360 <span class="external"> </span>print x , y
mmentovai9ec7bd62009-12-03 22:25:38 +00001361 <span class="external"></span>x , y = y , x</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001362 <p>
1363 No whitespace before the open paren/bracket that starts an argument list,
1364 indexing or slicing.
1365 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001366 <DIV class=""><PRE>Yes: <span class="external"></span>spam(1)</PRE></DIV>
1367<DIV class=""><PRE class="badcode">No: <span class="external"></span>spam (1)</PRE></DIV>
1368<DIV class=""><PRE>Yes: <span class="external"></span>dict['key'] = list[index]</PRE></DIV>
1369<DIV class=""><PRE class="badcode">No: <span class="external"></span>dict ['key'] = list [index]</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001370
1371 <p>
1372 Surround binary operators with a single space on either side for
1373 assignment (<code>=</code>), comparisons (<code>==, &lt;, &gt;, !=,
1374 &lt;&gt;, &lt;=, &gt;=, in, not in, is, is not</code>), and Booleans
1375 (<code>and, or, not</code>). Use your better judgment for the
1376 insertion of spaces around arithmetic operators but always be
1377 consistent about whitespace on either side of a binary operator.
1378 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001379<DIV class=""><PRE>Yes: <span class="external"></span>x == 1</PRE></DIV>
1380<DIV class=""><PRE class="badcode">No: <span class="external"></span>x&lt;1</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001381 <p>
1382 Don't use spaces around the '=' sign when used to indicate a
1383 keyword argument or a default parameter value.
1384 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001385<DIV class=""><PRE>Yes: <span class="external"></span>def complex(real, imag=0.0): return magic(r=real, i=imag)</PRE></DIV>
1386<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 +00001387
1388 <p>
1389 Don't use spaces to vertically align tokens on consecutive lines, since it
1390 becomes a maintenance burden (applies to <code>:</code>, <code>#</code>,
1391 <code>=</code>, etc.):
1392 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001393<DIV class=""><PRE>Yes:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001394 foo = 1000 # comment
1395 long_name = 2 # comment that should not be aligned
1396
1397 dictionary = {
1398 "foo": 1,
1399 "long_name": 2,
mmentovai9ec7bd62009-12-03 22:25:38 +00001400 }</PRE></DIV>
1401<DIV class=""><PRE class="badcode">No:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001402 foo = 1000 # comment
1403 long_name = 2 # comment that should not be aligned
1404
1405 dictionary = {
1406 "foo" : 1,
1407 "long_name": 2,
mmentovai9ec7bd62009-12-03 22:25:38 +00001408 }</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001409
1410
mmentovai9ec7bd62009-12-03 22:25:38 +00001411 </DIV></DIV>
1412 </DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001413
mmentovaicd4ce0f2011-03-29 20:30:47 +00001414 <a name="Python_Interpreter"></a>
1415 <DIV class="">
1416<H3><A name="Shebang_Line" id="Shebang_Line">Shebang Line</A></H3>
1417<SPAN class="link_button" id="link-Shebang_Line__button" name="link-Shebang_Line__button"><A href="?showone=Shebang_Line#Shebang_Line">
1418 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001419 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Shebang_Line')" name="Shebang_Line__button" id="Shebang_Line__button"></SPAN>
mmentovaicd4ce0f2011-03-29 20:30:47 +00001420 <DIV style="display:inline;" class="">
mark@chromium.orge33361f2011-11-04 16:55:22 +00001421 Most <code>.py</code> files do not need to start with a
1422 <code>#!</code> line. Start the main file of a binary with
1423 <code>#!/usr/bin/python</code>.
mmentovaicd4ce0f2011-03-29 20:30:47 +00001424 </DIV>
1425 <DIV class=""><DIV class="stylepoint_body" name="Shebang_Line__body" id="Shebang_Line__body" style="display: none">
1426
1427 <p>
mark@chromium.orge33361f2011-11-04 16:55:22 +00001428 This line is used by the kernel to find the Python interpreter, but is
1429 ignored by Python when importing modules. It is only necessary on a
1430 file that will be executed directly.
mmentovaicd4ce0f2011-03-29 20:30:47 +00001431 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001432 </DIV></DIV>
1433 </DIV>
mmentovaicd4ce0f2011-03-29 20:30:47 +00001434
mmentovai9ec7bd62009-12-03 22:25:38 +00001435 <DIV class="">
1436<H3><A name="Comments" id="Comments">Comments</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001437<SPAN class="link_button" id="link-Comments__button" name="link-Comments__button"><A href="?showone=Comments#Comments">
1438 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001439 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Comments')" name="Comments__button" id="Comments__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001440 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001441 Be sure to use the right style for module, function, method and in-line
1442 comments.
mmentovai9ec7bd62009-12-03 22:25:38 +00001443 </DIV>
1444 <DIV class=""><DIV class="stylepoint_body" name="Comments__body" id="Comments__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001445
1446 <P class="">
1447<SPAN class="stylepoint_subsection">Doc Strings</SPAN>
1448
1449 <p>
1450 Python has a unique commenting style using doc strings. A doc
1451 string is a string that is the first statement in a package,
1452 module, class or function. These strings can be extracted
1453 automatically through the <code>__doc__</code> member of the
1454 object and are used by <code>pydoc</code>. (Try running
1455 <code>pydoc</code> on your module to see how it looks.) Our
1456 convention for doc strings is to use the three double-quote
1457 format for strings. A doc string should be organized as a
1458 summary line (one physical line) terminated by a period,
1459 question mark, or exclamation point, followed by a blank line,
1460 followed by the rest of the doc string starting at the same
1461 cursor position as the first quote of the first line. There are
1462 more formatting guidelines for doc strings below.
1463 </p>
1464
1465 </P>
1466 <P class="">
1467<SPAN class="stylepoint_subsection">Modules</SPAN>
1468
1469
1470
1471 <p>
1472 Every file should contain the following items, in order:
1473 <ul>
1474 <li>a copyright statement (for example,
1475 <code>Copyright 2008 Google Inc.</code>)</li>
1476 <li>a license boilerplate. Choose the appropriate boilerplate
1477 for the license used by the project (for example, Apache 2.0, BSD,
1478 LGPL, GPL)</li>
1479 <li>an author line to identify the original author of the file</li>
1480 </ul>
1481 </p>
1482 </P>
1483 <P class="">
1484<SPAN class="stylepoint_subsection">Functions and Methods</SPAN>
1485
1486 <p>
mark@chromium.orge33361f2011-11-04 16:55:22 +00001487 As used in this section "function" applies to methods, function, and
1488 generators.
apicard@google.comf900c2c2009-07-23 20:09:56 +00001489 </p>
1490
mark@chromium.orge33361f2011-11-04 16:55:22 +00001491 <p>
1492 A function must have a docstring, unless it meets all of the following
1493 criteria:
1494 <ul>
1495 <li>not externally visible</li>
1496 <li>very short</li>
1497 <li>obvious</li>
1498 </ul>
1499 </p>
1500
1501 <p>
1502 A docstring should give enough information to write a call to the function
1503 without reading the function's code. A docstring should describe the
1504 function's calling syntax and its semantics, not its implementation. For
1505 tricky code, comments alongside the code are more appropriate than using
1506 docstrings.
1507 </p>
1508
1509 <p>
1510 Certain aspects of a function should be documented in special sections,
1511 listed below. Each section begins with a heading line, which ends with a
1512 colon. Sections should be indented two spaces, except for the heading.
1513 </p>
1514
1515 <dl>
1516 <dt>Args:</dt>
1517 <dd>
1518 List each parameter by name. A description should follow the name, and
1519 be separated by a colon and a space. If the description is too long to
1520 fit on a single 80-character line, use a hanging indent of 2 or 4 spaces
1521 (be consistent with the rest of the file).
1522
1523 <p>
1524 The description should mention required type(s) and the meaning of
1525 the argument.
1526 </p>
1527
1528 <p>
1529 If a function accepts *foo (variable length argument lists) and/or
1530 **bar (arbitrary keyword arguments), they should be listed as *foo and
1531 **bar.
1532 </p>
1533 </dd>
1534
1535 <dt>Returns: (or Yields: for generators)</dt>
1536 <dd>
1537 Describe the type and semantics of the return value. If the function
1538 only returns None, this section is not required.
1539 </dd>
1540
1541 <dt>Raises:</dt>
1542 <dd>
1543 List all exceptions that are relevant to the interface.
1544 </dd>
1545 </dl>
1546
mmentovai9ec7bd62009-12-03 22:25:38 +00001547 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001548<span class="external"></span>def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
1549 <span class="external"> </span>"""Fetches rows from a Bigtable.
1550
1551 <span class="external"> </span>Retrieves rows pertaining to the given keys from the Table instance
1552 <span class="external"> </span>represented by big_table. Silly things may happen if
1553 <span class="external"> </span>other_silly_variable is not None.
1554
1555 <span class="external"> </span>Args:
1556 <span class="external"> </span>big_table: An open Bigtable Table instance.
1557 <span class="external"> </span>keys: A sequence of strings representing the key of each table row
1558 <span class="external"> </span> to fetch.
1559 <span class="external"> </span>other_silly_variable: Another optional variable, that has a much
1560 <span class="external"> </span> longer name than the other args, and which does nothing.
1561
1562 <span class="external"> </span>Returns:
1563 <span class="external"> </span>A dict mapping keys to the corresponding table row data
1564 <span class="external"> </span>fetched. Each row is represented as a tuple of strings. For
1565 <span class="external"> </span>example:
1566
1567 <span class="external"> </span>{'Serak': ('Rigel VII', 'Preparer'),
1568 <span class="external"> </span> 'Zim': ('Irk', 'Invader'),
1569 <span class="external"> </span> 'Lrrr': ('Omicron Persei 8', 'Emperor')}
1570
1571 <span class="external"> </span>If a key from the keys argument is missing from the dictionary,
1572 <span class="external"> </span>then that row was not found in the table.
1573
1574 <span class="external"> </span>Raises:
1575 <span class="external"> </span>IOError: An error occurred accessing the bigtable.Table object.
1576 <span class="external"> </span>"""
1577 <span class="external"> </span>pass
1578<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001579</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001580 </P>
1581 <P class="">
1582<SPAN class="stylepoint_subsection">Classes</SPAN>
1583
1584 <p>
1585 Classes should have a doc string below the class definition describing
1586 the class. If your class has public attributes, they should be documented
1587 here in an Attributes section and follow the same formatting as a
1588 function's Args section.
1589 </p>
1590
mmentovai9ec7bd62009-12-03 22:25:38 +00001591 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001592<span class="external"></span>class SampleClass(object):
1593 <span class="external"> </span>"""Summary of class here.
1594
1595 <span class="external"> </span>Longer class information....
1596 <span class="external"> </span>Longer class information....
1597
1598 <span class="external"> </span>Attributes:
1599 <span class="external"> </span>likes_spam: A boolean indicating if we like SPAM or not.
1600 <span class="external"> </span>eggs: An integer count of the eggs we have laid.
1601 <span class="external"> </span>"""
1602
1603 <span class="external"> </span>def __init__(self, likes_spam=False):
1604 <span class="external"> </span>"""Inits SampleClass with blah."""
1605 <span class="external"> </span>self.likes_spam = likes_spam
1606 <span class="external"> </span>self.eggs = 0
1607
1608 <span class="external"> </span>def public_method(self):
1609 <span class="external"> </span>"""Performs operation blah."""
1610<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001611</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001612
1613 </P>
1614 <P class="">
1615<SPAN class="stylepoint_subsection">Block and Inline Comments</SPAN>
1616
1617 <p>
1618 The final place to have comments is in tricky parts of the
1619 code. If you're going to have to explain it at the next
1620 <a HREF="http://en.wikipedia.org/wiki/Code_review">code review</a>,
1621 you should comment it now. Complicated operations get a few lines of
1622 comments before the operations
1623 commence. Non-obvious ones get comments at the end of the line.
1624 </p>
1625
mmentovai9ec7bd62009-12-03 22:25:38 +00001626 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001627<span class="external"></span># We use a weighted dictionary search to find out where i is in
1628<span class="external"></span># the array. We extrapolate position based on the largest num
1629<span class="external"></span># in the array and the array size and then do binary search to
1630<span class="external"></span># get the exact number.
1631
1632<span class="external"></span>if i &amp; (i-1) == 0: # true iff i is a power of 2
1633<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001634</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001635
1636 <p>
1637 To improve legibility, these comments should be at least 2 spaces away
1638 from the code.
1639 </p>
1640
1641 <p>
1642 On the other hand, never describe the code. Assume the person
1643 reading the code knows Python (though not what you're trying to
1644 do) better than you do.
1645 </p>
1646
mmentovai9ec7bd62009-12-03 22:25:38 +00001647 <DIV class=""><PRE class="badcode">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001648<span class="external"></span># BAD COMMENT: Now go through the b array and make sure whenever i occurs
1649<span class="external"></span># the next element is i+1
1650<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001651</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001652
1653 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001654 </DIV></DIV>
1655 </DIV>
1656 <DIV class="">
1657<H3><A name="Classes" id="Classes">Classes</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001658<SPAN class="link_button" id="link-Classes__button" name="link-Classes__button"><A href="?showone=Classes#Classes">
1659 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001660 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Classes')" name="Classes__button" id="Classes__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001661 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001662 If a class inherits from no other base classes, explicitly inherit
1663 from <code>object</code>. This also applies to nested classes.
mmentovai9ec7bd62009-12-03 22:25:38 +00001664 </DIV>
1665 <DIV class=""><DIV class="stylepoint_body" name="Classes__body" id="Classes__body" style="display: none">
mmentovai9ec7bd62009-12-03 22:25:38 +00001666 <DIV class=""><PRE class="badcode">No: <span class="external"></span>class SampleClass:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001667 <span class="external"> </span>pass
1668
1669
1670 <span class="external"></span>class OuterClass:
1671
1672 <span class="external"> </span>class InnerClass:
1673 <span class="external"> </span>pass
1674<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001675</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001676
mmentovai9ec7bd62009-12-03 22:25:38 +00001677 <DIV class=""><PRE>Yes: <span class="external"></span>class SampleClass(object):
apicard@google.comf900c2c2009-07-23 20:09:56 +00001678 <span class="external"> </span>pass
1679
1680
1681 <span class="external"></span>class OuterClass(object):
1682
1683 <span class="external"> </span>class InnerClass(object):
1684 <span class="external"> </span>pass
1685
1686
1687 <span class="external"></span>class ChildClass(ParentClass):
1688 <span class="external"> </span>"""Explicitly inherits from another class already."""
1689<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001690</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001691
1692 <p>Inheriting from <code>object</code> is needed to make properties work
1693 properly, and it will protect your code from one particular potential
1694 incompatibility with Python 3000. It also defines
1695 special methods that implement the default semantics of objects including
1696 <code>__new__</code>, <code>__init__</code>, <code>__delattr__</code>,
1697 <code>__getattribute__</code>, <code>__setattr__</code>,
1698 <code>__hash__</code>, <code>__repr__</code>, and <code>__str__</code>.
1699 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001700 </DIV></DIV>
1701 </DIV>
1702 <DIV class="">
1703<H3><A name="Strings" id="Strings">Strings</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001704<SPAN class="link_button" id="link-Strings__button" name="link-Strings__button"><A href="?showone=Strings#Strings">
1705 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001706 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Strings')" name="Strings__button" id="Strings__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001707 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001708 Use the <code>%</code> operator for formatting strings,
1709 even when the parameters are all strings. Use your best judgement
1710 to decide between <code>+</code> and <code>%</code> though.
mmentovai9ec7bd62009-12-03 22:25:38 +00001711 </DIV>
1712 <DIV class=""><DIV class="stylepoint_body" name="Strings__body" id="Strings__body" style="display: none">
mmentovai9ec7bd62009-12-03 22:25:38 +00001713<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 +00001714 <span class="external"></span>x = imperative + ', ' + expletive + '!'
mmentovai9ec7bd62009-12-03 22:25:38 +00001715 <span class="external"></span>x = 'name: ' + name + '; score: ' + str(n)</PRE></DIV>
1716<DIV class=""><PRE>Yes: <span class="external"></span>x = a + b
apicard@google.comf900c2c2009-07-23 20:09:56 +00001717 <span class="external"></span>x = '%s, %s!' % (imperative, expletive)
mmentovai9ec7bd62009-12-03 22:25:38 +00001718 <span class="external"></span>x = 'name: %s; score: %d' % (name, n)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001719
1720 <p>
1721 Avoid using the <code>+</code> and <code>+=</code> operators to
1722 accumulate a string within a loop. Since strings are immutable, this
1723 creates unnecessary temporary objects and results in quadratic rather
1724 than linear running time. Instead, add each substring to a list and
1725 <code>''.join</code> the list after the loop terminates (or, write each
1726 substring to a <code>cStringIO.StringIO</code> buffer).
1727 </p>
1728
mmentovai9ec7bd62009-12-03 22:25:38 +00001729<DIV class=""><PRE class="badcode">No: <span class="external"></span>employee_table = '&lt;table&gt;'
apicard@google.comf900c2c2009-07-23 20:09:56 +00001730 <span class="external"></span>for last_name, first_name in employee_list:
1731 <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 +00001732 <span class="external"></span>employee_table += '&lt;/table&gt;'</PRE></DIV>
1733<DIV class=""><PRE>Yes: <span class="external"></span>items = ['&lt;table&gt;']
apicard@google.comf900c2c2009-07-23 20:09:56 +00001734 <span class="external"></span>for last_name, first_name in employee_list:
1735 <span class="external"> </span>items.append('&lt;tr&gt;&lt;td&gt;%s, %s&lt;/td&gt;&lt;/tr&gt;' % (last_name, first_name))
1736 <span class="external"></span>items.append('&lt;/table&gt;')
mmentovai9ec7bd62009-12-03 22:25:38 +00001737 <span class="external"></span>employee_table = ''.join(items)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001738
1739 <p>
1740 Use <code>"""</code> for multi-line strings rather than
1741 <code>'''</code>. Note, however, that it is often cleaner to
1742 use implicit line joining since multi-line strings do
1743 not flow with the indentation of the rest of the program:
1744 </p>
1745
mmentovai9ec7bd62009-12-03 22:25:38 +00001746 <DIV class=""><PRE class="badcode"> No<span class="external"></span>:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001747 <span class="external"></span>print """This is pretty ugly.
1748Don'<span class="external"></span>t do this.
1749"""<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001750</PRE></DIV>
1751<DIV class=""><PRE>Ye<span class="external"></span>s:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001752 <span class="external"></span>print ("This is much nicer.\n"
mmentovai9ec7bd62009-12-03 22:25:38 +00001753 <span class="external"></span> "Do it this way.\n")</PRE></DIV>
1754 </DIV></DIV>
1755 </DIV>
1756 <DIV class="">
1757<H3><A name="TODO_Comments" id="TODO_Comments">TODO Comments</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001758<SPAN class="link_button" id="link-TODO_Comments__button" name="link-TODO_Comments__button"><A href="?showone=TODO_Comments#TODO_Comments">
1759 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001760 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('TODO_Comments')" name="TODO_Comments__button" id="TODO_Comments__button"></SPAN>
1761 <DIV style="display:inline;" class="">
1762 Use <code>TODO</code> comments for code that is temporary, a
1763 short-term solution, or good-enough but not perfect.
1764 </DIV>
1765 <DIV class=""><DIV class="stylepoint_body" name="TODO_Comments__body" id="TODO_Comments__body" style="display: none">
1766 <p>
1767 <code>TODO</code>s should include the string <code>TODO</code> in
1768 all caps, followed by the
1769
1770 name, e-mail address, or other
1771 identifier
1772 of the person who can best provide context about the problem
1773 referenced by the <code>TODO</code>,
1774 in parentheses. A colon is optional. A comment explaining what there
1775 is to do is required. The main purpose is to have
1776 a consistent <code>TODO</code> format that can be searched to find the
1777 person who can provide more details upon request. A
1778 <code>TODO</code> is not a commitment that the person referenced
1779 will fix the problem. Thus when you create a <code>TODO</code>, it is
1780 almost always your
1781
1782 name
1783 that is given.
1784 </p>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001785
mark@chromium.orge33361f2011-11-04 16:55:22 +00001786 <DIV class=""><PRE># TODO(kl@gmail.com): Use a "*" here for string repetition.
1787# TODO(Zeke) Change this to use relations.</PRE></DIV>
1788 <p>
1789 If your <code>TODO</code> is of the form "At a future date do
1790 something" make sure that you either include a very specific
1791 date ("Fix by November 2009") or a very specific event
1792 ("Remove this code when all clients can handle XML responses.").
1793 </p>
1794 </DIV></DIV>
1795 </DIV>
mmentovai9ec7bd62009-12-03 22:25:38 +00001796 <DIV class="">
1797<H3><A name="Imports_formatting" id="Imports_formatting">Imports formatting</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001798<SPAN class="link_button" id="link-Imports_formatting__button" name="link-Imports_formatting__button"><A href="?showone=Imports_formatting#Imports_formatting">
1799 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001800 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Imports_formatting')" name="Imports_formatting__button" id="Imports_formatting__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001801 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001802 Imports should be on separate lines.
mmentovai9ec7bd62009-12-03 22:25:38 +00001803 </DIV>
1804 <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 +00001805 <p>
1806 E.g.:
1807 </p>
1808
mmentovai9ec7bd62009-12-03 22:25:38 +00001809<DIV class=""><PRE>Yes: <span class="external"></span>import os
1810 <span class="external"></span>import sys</PRE></DIV>
1811<DIV class=""><PRE class="badcode">No: <span class="external"></span>import os, sys</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001812 <p>
1813 Imports are always put at the top of the file, just after any
1814 module comments and doc strings and before module globals and
1815 constants. Imports should be grouped with the order being most generic
1816 to least generic:
1817 </p>
1818 <ul>
1819 <li>standard library imports</li>
1820 <li>third-party imports</li>
1821
1822 <li>application-specific imports</li>
1823 </ul>
1824 <p>
1825 Within each grouping, imports should be sorted lexicographically,
1826 ignoring case, according to each module's full package path.
1827 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001828 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001829<span class="external"></span>import foo
1830<span class="external"></span>from foo import bar
1831<span class="external"></span>from foo.bar import baz
1832<span class="external"></span>from foo.bar import Quux
mmentovai9ec7bd62009-12-03 22:25:38 +00001833<span class="external"></span>from Foob import ar</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001834
1835
mmentovai9ec7bd62009-12-03 22:25:38 +00001836
1837 </DIV></DIV>
1838 </DIV>
1839 <DIV class="">
1840<H3><A name="Statements" id="Statements">Statements</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001841<SPAN class="link_button" id="link-Statements__button" name="link-Statements__button"><A href="?showone=Statements#Statements">
1842 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001843 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Statements')" name="Statements__button" id="Statements__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001844 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001845 Generally only one statement per line.
mmentovai9ec7bd62009-12-03 22:25:38 +00001846 </DIV>
1847 <DIV class=""><DIV class="stylepoint_body" name="Statements__body" id="Statements__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001848 <p>
1849 However, you may put the
1850 result of a test on the same line as the test only if the entire
1851 statement fits on one line. In particular, you can never do so
1852 with <code>try</code>/<code>except</code> since the
1853 <code>try</code> and <code>except</code> can't both fit on the
1854 same line, and you can only do so with an <code>if</code> if
1855 there is no <code>else</code>.
1856 </p>
1857
mmentovai9ec7bd62009-12-03 22:25:38 +00001858 <DIV class=""><PRE>Ye<span class="external"></span>s:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001859
mmentovai9ec7bd62009-12-03 22:25:38 +00001860 <span class="external"></span>if foo: bar(foo)</PRE></DIV>
1861<DIV class=""><PRE class="badcode">No<span class="external"></span>:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001862
1863 <span class="external"></span>if foo: bar(foo)
1864 <span class="external"></span>else: baz(foo)
1865
1866 <span class="external"></span>try: bar(foo)
1867 <span class="external"></span>except ValueError: baz(foo)
1868
1869 <span class="external"></span>try:
1870 <span class="external"> </span>bar(foo)
1871 <span class="external"></span>except ValueError: baz(foo)
1872<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001873</PRE></DIV>
1874 </DIV></DIV>
1875 </DIV>
1876 <DIV class="">
1877<H3><A name="Access_Control" id="Access_Control">Access Control</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001878<SPAN class="link_button" id="link-Access_Control__button" name="link-Access_Control__button"><A href="?showone=Access_Control#Access_Control">
1879 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001880 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Access_Control')" name="Access_Control__button" id="Access_Control__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001881 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001882 If an accessor function would be trivial you should use public variables
1883 instead of accessor functions to avoid the extra cost of function
1884 calls in Python. When more functionality is added you can use
1885 <code>property</code> to keep the syntax consistent.
mmentovai9ec7bd62009-12-03 22:25:38 +00001886 </DIV>
1887 <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 +00001888 <p>
1889 On the other hand, if access is more complex, or the cost of accessing
1890 the variable is significant, you should use function calls (following the
1891 <a HREF="#naming">Naming</a> guidelines) such as <code>get_foo()</code>
1892 and <code>set_foo()</code>. If the past behavior allowed access through a
1893 property, do not bind the new accessor functions to the property. Any
1894 code still attempting to access the variable by the old method should
1895 break visibly so they are made aware of the change in complexity.
1896 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001897 </DIV></DIV>
1898 </DIV>
1899 <DIV class="">
1900<H3><A name="Naming" id="Naming">Naming</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001901<SPAN class="link_button" id="link-Naming__button" name="link-Naming__button"><A href="?showone=Naming#Naming">
1902 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001903 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Naming')" name="Naming__button" id="Naming__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001904 <DIV style="display:inline;" class="">
mark@chromium.orge33361f2011-11-04 16:55:22 +00001905 <code>module_name, package_name, ClassName,
1906 method_name, ExceptionName,
1907 function_name, GLOBAL_CONSTANT_NAME,
1908 global_var_name, instance_var_name, function_parameter_name,
1909 local_var_name.</code>
mmentovai9ec7bd62009-12-03 22:25:38 +00001910 </DIV>
1911 <DIV class=""><DIV class="stylepoint_body" name="Naming__body" id="Naming__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001912 <P class="">
1913<SPAN class="stylepoint_subsection">Names to Avoid</SPAN>
1914
1915 <ul>
1916 <li>single character names except for counters or iterators</li>
1917 <li>dashes (<code>-</code>) in any package/module name</li>
1918 <li>
1919<code>__double_leading_and_trailing_underscore__</code> names
1920 (reserved by Python)</li>
1921 </ul>
1922
1923 </P>
1924 <P class="">
1925<SPAN class="stylepoint_subsection">Naming Convention</SPAN>
1926
1927 <ul>
1928 <li>
1929 "Internal" means internal to a module or protected
1930 or private within a class.</li>
1931 <li>
1932 Prepending a single underscore (<code>_</code>) has some
1933 support for protecting module variables and functions (not included
1934 with <code>import * from</code>). Prepending a double underscore
1935 (<code>__</code>) to an instance variable or method
1936 effectively serves to make the variable or method private to its class
1937 (using name mangling).</li>
1938 <li>
1939 Place related classes and top-level functions together in a
1940 module. Unlike Java,
1941 there is no need to limit yourself to one class per module.</li>
1942 <li>
1943 Use CapWords for class names, but lower_with_under.py for module names.
1944 Although there are many existing modules named CapWords.py, this is now
1945 discouraged because it's confusing when the module happens to be
1946 named after a class. ("wait -- did I write
1947 <code>import StringIO</code> or <code>from StringIO import
1948 StringIO</code>?")</li>
1949 </ul>
1950
1951 </P>
1952 <P class="">
1953<SPAN class="stylepoint_subsection">Guidelines derived from Guido's Recommendations</SPAN>
1954
1955 <table rules="all" border="1" cellspacing="2" cellpadding="2">
1956
1957 <tr>
1958 <th>Type</th>
1959 <th>Public</th>
1960 <th>Internal</th>
1961 </tr>
1962
1963
1964
1965 <tr>
1966 <td>Packages</td>
1967 <td><code>lower_with_under</code></td>
1968 <td></td>
1969 </tr>
1970
1971 <tr>
1972 <td>Modules</td>
1973 <td><code>lower_with_under</code></td>
1974 <td><code>_lower_with_under</code></td>
1975 </tr>
1976
1977 <tr>
1978 <td>Classes</td>
1979 <td><code>CapWords</code></td>
1980 <td><code>_CapWords</code></td>
1981 </tr>
1982
1983 <tr>
1984 <td>Exceptions</td>
1985 <td><code>CapWords</code></td>
1986 <td></td>
1987 </tr>
1988
1989
1990
1991 <tr>
1992 <td>Functions</td>
1993 <td><code>lower_with_under()</code></td>
1994 <td><code>_lower_with_under()</code></td>
1995 </tr>
1996
1997 <tr>
1998 <td>Global/Class Constants</td>
1999 <td><code>CAPS_WITH_UNDER</code></td>
2000 <td><code>_CAPS_WITH_UNDER</code></td>
2001 </tr>
2002
2003 <tr>
2004 <td>Global/Class Variables</td>
2005 <td><code>lower_with_under</code></td>
2006 <td><code>_lower_with_under</code></td>
2007 </tr>
2008
2009 <tr>
2010 <td>Instance Variables</td>
2011 <td><code>lower_with_under</code></td>
2012 <td><code>_lower_with_under (protected) or __lower_with_under (private)</code></td>
2013 </tr>
2014
2015
2016
2017 <tr>
2018 <td>Method Names</td>
2019 <td><code>lower_with_under()</code></td>
2020 <td><code>_lower_with_under() (protected) or __lower_with_under() (private)</code></td>
2021 </tr>
2022
2023 <tr>
2024 <td>Function/Method Parameters</td>
2025 <td><code>lower_with_under</code></td>
2026 <td></td>
2027 </tr>
2028
2029 <tr>
2030 <td>Local Variables</td>
2031 <td><code>lower_with_under</code></td>
2032 <td></td>
2033 </tr>
2034
2035
2036 </table>
2037
2038
2039 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00002040 </DIV></DIV>
2041 </DIV>
2042 <DIV class="">
2043<H3><A name="Main" id="Main">Main</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00002044<SPAN class="link_button" id="link-Main__button" name="link-Main__button"><A href="?showone=Main#Main">
2045 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00002046 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Main')" name="Main__button" id="Main__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00002047 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00002048 Even a file meant to be used as a script should be importable and a
2049 mere import should not have the side effect of executing the script's
2050 main functionality. The main functionality should be in a main()
2051 function.
mmentovai9ec7bd62009-12-03 22:25:38 +00002052 </DIV>
2053 <DIV class=""><DIV class="stylepoint_body" name="Main__body" id="Main__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00002054 <p>
2055 In Python,
2056 <code>pychecker</code>, <code>pydoc</code>, and unit tests
2057 require modules to be importable. Your code should always check
2058 <code>if __name__ == '__main__'</code> before executing your
2059 main program so that the main program is not executed when the
2060 module is imported.
2061
2062 </p>
2063
2064
2065
2066
2067
2068
2069
mmentovai9ec7bd62009-12-03 22:25:38 +00002070 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002071<span class="external"></span>def main():
2072 <span class="external"> </span>...
2073
2074<span class="external"></span>if __name__ == '__main__':
2075 <span class="external"> </span>main()
2076<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00002077</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002078
2079 <p>
2080 All code at the top level will be executed when the module is
2081 imported. Be careful not to call functions, create objects, or
2082 perform other operations that should not be executed when the
2083 file is being <code>pycheck</code>ed or <code>pydoc</code>ed.
2084 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00002085 </DIV></DIV>
2086 </DIV>
2087 </DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002088
2089<H2>Parting Words</H2>
2090 <p>
2091 <em>BE CONSISTENT</em>.
2092 </p>
2093
2094 <p>
2095 If you're editing code, take a few minutes to look at the code
2096 around you and determine its style. If they use spaces around
2097 all their arithmetic operators, you should too. If their
2098 comments have little boxes of hash marks around them, make your
2099 comments have little boxes of hash marks around them too.
2100 </p>
2101
2102 <p>
2103 The point of having style guidelines is to have a common vocabulary
2104 of coding so people can concentrate on what you're saying rather
2105 than on how you're saying it. We present global style rules here so
2106 people know the vocabulary, but local style is also important. If
2107 code you add to a file looks drastically different from the existing
2108 code around it, it throws readers out of their rhythm when they go to
2109 read it. Avoid this.
2110 </p>
2111
2112
2113
2114<p align="right">
mark@chromium.orge33361f2011-11-04 16:55:22 +00002115Revision 2.28
apicard@google.comf900c2c2009-07-23 20:09:56 +00002116</p>
2117
2118
2119<address>
2120 Amit Patel<br>
2121 Antoine Picard<br>
2122 Eugene Jhong<br>
2123 Jeremy Hylton<br>
2124 Matt Smart<br>
2125 Mike Shields<br>
2126</address>
2127</BODY>
2128</HTML>