blob: 3c6a3e0ba941a08e4f18857bcfa4deb133feca25 [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;
mark@chromium.orgc8c76a22012-11-28 20:26:27 +000098 ShowByName(id.substring(0, len));
mark@chromium.orge33361f2011-11-04 16:55:22 +000099 if (anchor.scrollIntoView) {
100 anchor.scrollIntoView();
101 }
mark@chromium.orgc8c76a22012-11-28 20:26:27 +0000102
mark@chromium.orge33361f2011-11-04 16:55:22 +0000103 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.orgc8c76a22012-11-28 20:26:27 +0000139 Revision 2.45
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">
apicard@google.com424ad342012-09-18 23:16:02 +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="#Conditional_Expressions">Conditional Expressions</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">
apicard@google.com424ad342012-09-18 23:16:02 +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="#Files_and_Sockets">Files and Sockets</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>
apicard@google.com424ad342012-09-18 23:16:02 +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="">
apicard@google.com424ad342012-09-18 23:16:02 +0000246<SPAN class="stylepoint_section">Decision: </SPAN>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000247 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
apicard@google.com424ad342012-09-18 23:16:02 +0000257 <code>__pychecker__</code> to suppress appropriate warnings.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000258 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>
apicard@google.com424ad342012-09-18 23:16:02 +0000267 You can get a list of pychecker warnings by doing
apicard@google.comf900c2c2009-07-23 20:09:56 +0000268 <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):
apicard@google.com424ad342012-09-18 23:16:02 +0000279 <span class="external"> </span>_ = d, e
apicard@google.comf900c2c2009-07-23 20:09:56 +0000280 <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>
apicard@google.com424ad342012-09-18 23:16:02 +0000409 <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>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000414 <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
mark@chromium.orgc8c76a22012-11-28 20:26:27 +0000427 really catch everything including misspelled names, sys.exit()
428 calls, Ctrl+C interrupts, unittest failures and all kinds of
429 other exceptions that you simply don't want to catch.</li>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000430 <li>Minimize the amount of code in a
431 <code>try</code>/<code>except</code> block. The larger the
432 body of the <code>try</code>, the more likely that an
433 exception will be raised by a line of code that you didn't
434 expect to raise an exception. In those cases,
435 the <code>try</code>/<code>except</code> block hides a real
436 error.</li>
437 <li>Use the <code>finally</code> clause to execute code whether
438 or not an exception is raised in the <code>try</code> block.
439 This is often useful for cleanup, i.e., closing a file.</li>
apicard@google.com424ad342012-09-18 23:16:02 +0000440 <li>When capturing an exception, use <code>as</code> rather than
441 a comma. For example:
442 <DIV class=""><PRE>
443<span class="external"></span>try:
444 <span class="external"> </span>raise Error
445<span class="external"></span>except Error as error:
446 <span class="external"> </span>pass</PRE></DIV>
447</li>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000448 </ul>
449 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000450 </DIV></DIV>
451 </DIV>
452 <DIV class="">
453<H3><A name="Global_variables" id="Global_variables">Global variables</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000454<SPAN class="link_button" id="link-Global_variables__button" name="link-Global_variables__button"><A href="?showone=Global_variables#Global_variables">
455 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000456 </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 +0000457 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000458 Avoid global variables.
mmentovai9ec7bd62009-12-03 22:25:38 +0000459 </DIV>
460 <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 +0000461 <P class="">
462<SPAN class="stylepoint_section">Definition: </SPAN>
463 Variables that are declared at the module level.
464 </P>
465 <P class="">
466<SPAN class="stylepoint_section">Pros: </SPAN>
467 Occasionally useful.
468 </P>
469 <P class="">
470<SPAN class="stylepoint_section">Cons: </SPAN>
471 Has the potential to change module behavior during the import,
472 because assignments to module-level variables are done when the
473 module is imported.
474 </P>
475 <P class="">
476<SPAN class="stylepoint_section">Decision: </SPAN>
477 Avoid global variables in favor of class variables. Some
478 exceptions are:
479 <ul>
480 <li>Default options for scripts.</li>
481 <li>Module-level constants. For example: <code>PI = 3.14159</code>.
482 Constants should be named using all caps with underscores;
483 see <a HREF="#Naming">Naming</a> below.</li>
484 <li>It is sometimes useful for globals to cache values needed
485 or returned by functions.</li>
486 <li>If needed, globals should be made internal to the module
487 and accessed through public module level functions;
488 see <a HREF="#Naming">Naming</a> below.</li>
489 </ul>
490 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000491 </DIV></DIV>
492 </DIV>
493 <DIV class="">
494<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 +0000495<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">
496 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000497 </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 +0000498 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000499 Nested/local/inner classes and functions are fine.
mmentovai9ec7bd62009-12-03 22:25:38 +0000500 </DIV>
501 <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 +0000502 <P class="">
503<SPAN class="stylepoint_section">Definition: </SPAN>
mmentovaif7facf92009-10-23 21:01:49 +0000504 A class can be defined inside of a method, function, or class. A
505 function can be defined inside a method or function. Nested functions
506 have read-only access to variables defined in enclosing scopes.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000507 </P>
508 <P class="">
509<SPAN class="stylepoint_section">Pros: </SPAN>
510 Allows definition of utility classes and functions that are only
511 used inside of a very limited scope. Very <a HREF="http://en.wikipedia.org/wiki/Abstract_data_type">ADT</a>-y.
512 </P>
513 <P class="">
514<SPAN class="stylepoint_section">Cons: </SPAN>
515 Instances of nested or local classes cannot be pickled.
516 </P>
517 <P class="">
518<SPAN class="stylepoint_section">Decision: </SPAN>
519 They are fine.
520 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000521 </DIV></DIV>
522 </DIV>
523 <DIV class="">
524<H3><A name="List_Comprehensions" id="List_Comprehensions">List Comprehensions</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000525<SPAN class="link_button" id="link-List_Comprehensions__button" name="link-List_Comprehensions__button"><A href="?showone=List_Comprehensions#List_Comprehensions">
526 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000527 </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 +0000528 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000529 Okay to use for simple cases.
mmentovai9ec7bd62009-12-03 22:25:38 +0000530 </DIV>
531 <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 +0000532 <P class="">
533<SPAN class="stylepoint_section">Definition: </SPAN>
534 List comprehensions and generator expressions provide a concise
535 and efficient way to create lists and iterators without
536 resorting to the use of <code>map()</code>,
537 <code>filter()</code>, or <code>lambda</code>.
538 </P>
539 <P class="">
540<SPAN class="stylepoint_section">Pros: </SPAN>
541 Simple list comprehensions can be clearer and simpler than
542 other list creation techniques. Generator expressions can be
543 very efficient, since they avoid the creation of a list
544 entirely.
545 </P>
546 <P class="">
547<SPAN class="stylepoint_section">Cons: </SPAN>
548 Complicated list comprehensions or generator expressions can be
549 hard to read.
550 </P>
551 <P class="">
552<SPAN class="stylepoint_section">Decision: </SPAN>
553 Okay to use for simple cases. Each portion must fit on one line:
554 mapping expression, <code>for</code> clause, filter expression.
555 Multiple <code>for</code> clauses or filter expressions are not
556 permitted. Use loops instead when things get more complicated.
557 </P>
558
mmentovai9ec7bd62009-12-03 22:25:38 +0000559<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>
apicard@google.com424ad342012-09-18 23:16:02 +0000581<DIV class=""><PRE class="badcode">No<span class="external"></span>:
582 <span class="external"></span>result = [(x, y) for x in range(10) for y in range(5) if x * y &gt; 10]
583
584 <span class="external"></span>return ((x, y, z)
585 <span class="external"></span> for x in xrange(5)
586 <span class="external"></span> for y in xrange(5)
587 <span class="external"></span> if x != y
588 <span class="external"></span> for z in xrange(5)
589 <span class="external"></span> if y != z)</PRE></DIV>
mmentovai9ec7bd62009-12-03 22:25:38 +0000590 </DIV></DIV>
591 </DIV>
592 <DIV class="">
593<H3><A name="Default_Iterators_and_Operators" id="Default_Iterators_and_Operators">Default Iterators and Operators</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000594<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">
595 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000596 </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 +0000597 <DIV style="display:inline;" class="">
apicard@google.com424ad342012-09-18 23:16:02 +0000598 Use default iterators and operators for types that support them,
apicard@google.comf900c2c2009-07-23 20:09:56 +0000599 like lists, dictionaries, and files.
mmentovai9ec7bd62009-12-03 22:25:38 +0000600 </DIV>
601 <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 +0000602 <P class="">
603<SPAN class="stylepoint_section">Definition: </SPAN>
604 Container types, like dictionaries and lists, define default
605 iterators and membership test operators ("in" and "not in").
606 </P>
607 <P class="">
608<SPAN class="stylepoint_section">Pros: </SPAN>
609 The default iterators and operators are simple and efficient.
610 They express the operation directly, without extra method calls.
611 A function that uses default operators is generic. It can be
612 used with any type that supports the operation.
613 </P>
614 <P class="">
615<SPAN class="stylepoint_section">Cons: </SPAN>
616 You can't tell the type of objects by reading the method names
617 (e.g. has_key() means a dictionary). This is also an advantage.
618 </P>
619 <P class="">
620<SPAN class="stylepoint_section">Decision: </SPAN> Use default iterators and operators for types
621 that support them, like lists, dictionaries, and files. The
622 built-in types define iterator methods, too. Prefer these
623 methods to methods that return lists, except that you should not
624 mutate a container while iterating over it.
625
mmentovai9ec7bd62009-12-03 22:25:38 +0000626<DIV class=""><PRE>Yes: <span class="external"></span>for key in adict: ...
apicard@google.comf900c2c2009-07-23 20:09:56 +0000627 <span class="external"></span>if key not in adict: ...
628 <span class="external"></span>if obj in alist: ...
629 <span class="external"></span>for line in afile: ...
mmentovai9ec7bd62009-12-03 22:25:38 +0000630 <span class="external"></span>for k, v in dict.iteritems(): ...</PRE></DIV>
631<DIV class=""><PRE class="badcode">No: <span class="external"></span>for key in adict.keys(): ...
apicard@google.comf900c2c2009-07-23 20:09:56 +0000632 <span class="external"></span>if not adict.has_key(key): ...
mmentovai9ec7bd62009-12-03 22:25:38 +0000633 <span class="external"></span>for line in afile.readlines(): ...</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000634 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000635 </DIV></DIV>
636 </DIV>
637 <DIV class="">
638<H3><A name="Generators" id="Generators">Generators</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000639<SPAN class="link_button" id="link-Generators__button" name="link-Generators__button"><A href="?showone=Generators#Generators">
640 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000641 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Generators')" name="Generators__button" id="Generators__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000642 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000643 Use generators as needed.
mmentovai9ec7bd62009-12-03 22:25:38 +0000644 </DIV>
645 <DIV class=""><DIV class="stylepoint_body" name="Generators__body" id="Generators__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000646 <P class="">
647<SPAN class="stylepoint_section">Definition: </SPAN>
648 A generator function returns an iterator that yields a value each
649 time it executes a yield statement. After it yields a value, the
650 runtime state of the generator function is suspended until the
651 next value is needed.
652 </P>
653 <P class="">
654<SPAN class="stylepoint_section">Pros: </SPAN>
655 Simpler code, because the state of local variables and control flow
656 are preserved for each call. A generator uses less memory than a
657 function that creates an entire list of values at once.
658 </P>
659 <P class="">
apicard@google.com424ad342012-09-18 23:16:02 +0000660<SPAN class="stylepoint_section">Cons: </SPAN>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000661 None.
662 </P>
663 <P class="">
664<SPAN class="stylepoint_section">Decision: </SPAN>
665 Fine. Use "Yields:" rather than "Returns:" in the
666 doc string for generator functions.
667 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000668 </DIV></DIV>
669 </DIV>
670 <DIV class="">
671<H3><A name="Lambda_Functions" id="Lambda_Functions">Lambda Functions</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000672<SPAN class="link_button" id="link-Lambda_Functions__button" name="link-Lambda_Functions__button"><A href="?showone=Lambda_Functions#Lambda_Functions">
673 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000674 </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 +0000675 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000676 Okay for one-liners.
mmentovai9ec7bd62009-12-03 22:25:38 +0000677 </DIV>
678 <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 +0000679 <P class="">
680<SPAN class="stylepoint_section">Definition: </SPAN>
681 Lambdas define anonymous functions in an expression, as
682 opposed to a statement. They are often used to define callbacks or
683 operators for higher-order functions like <code>map()</code> and
684 <code>filter()</code>.
685 </P>
686 <P class="">
687<SPAN class="stylepoint_section">Pros: </SPAN>
688 Convenient.
689 </P>
690 <P class="">
691<SPAN class="stylepoint_section">Cons: </SPAN> Harder to read and debug than local functions. The
692 lack of names means stack traces are more difficult to
693 understand. Expressiveness is limited because the function may
694 only contain an expression.
695 </P>
696 <P class="">
697<SPAN class="stylepoint_section">Decision: </SPAN>
698 Okay to use them for one-liners. If the code inside the lambda
699 function is any longer than 60–80 chars, it's probably better to
700 define it as a regular (nested) function.
701 <p>
702 For common operations like multiplication, use the functions from the
703 <code>operator</code> module instead of lambda functions. For
704 example, prefer <code>operator.mul</code> to <code>lambda
705 x, y: x * y</code>.
706 </p>
707 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000708 </DIV></DIV>
709 </DIV>
710 <DIV class="">
apicard@google.com424ad342012-09-18 23:16:02 +0000711<H3><A name="Conditional_Expressions" id="Conditional_Expressions">Conditional Expressions</A></H3>
712<SPAN class="link_button" id="link-Conditional_Expressions__button" name="link-Conditional_Expressions__button"><A href="?showone=Conditional_Expressions#Conditional_Expressions">
713 link
714 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Conditional_Expressions')" name="Conditional_Expressions__button" id="Conditional_Expressions__button"></SPAN>
715 <DIV style="display:inline;" class="">
716 Okay for one-liners.
717 </DIV>
718 <DIV class=""><DIV class="stylepoint_body" name="Conditional_Expressions__body" id="Conditional_Expressions__body" style="display: none">
719 <P class="">
720<SPAN class="stylepoint_section">Definition: </SPAN>
721 Conditional expressions are mechanisms that provide a shorter syntax
722 for if statements. For example:
723 <code>x = 1 if cond else 2</code>.
724 </P>
725 <P class="">
726<SPAN class="stylepoint_section">Pros: </SPAN>
727 Shorter and more convenient than an if statement.
728 </P>
729 <P class="">
730<SPAN class="stylepoint_section">Cons: </SPAN>
731 May be harder to read than an if statement. The condition may be difficult
732 to locate if the expression is long.
733 </P>
734 <P class="">
735<SPAN class="stylepoint_section">Decision: </SPAN>
736 Okay to use for one-liners. In other cases prefer to use a complete if
737 statement.
738 </P>
739 </DIV></DIV>
740 </DIV>
741 <DIV class="">
mmentovai9ec7bd62009-12-03 22:25:38 +0000742<H3><A name="Default_Argument_Values" id="Default_Argument_Values">Default Argument Values</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000743<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">
744 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000745 </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 +0000746 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000747 Okay in most cases.
mmentovai9ec7bd62009-12-03 22:25:38 +0000748 </DIV>
749 <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 +0000750 <P class="">
751<SPAN class="stylepoint_section">Definition: </SPAN>
752 You can specify values for variables at the end of a function's
753 parameter list, e.g., <code>def foo(a, b=0):</code>. If
754 <code>foo</code> is called with only one argument,
755 <code>b</code> is set to 0. If it is called with two arguments,
756 <code>b</code> has the value of the second argument.
757 </P>
758 <P class="">
759<SPAN class="stylepoint_section">Pros: </SPAN>
760 Often you have a function that uses lots of default values,
761 but—rarely—you want to override the
762 defaults. Default argument values provide an easy way to do this,
763 without having to define lots of functions for the rare
764 exceptions. Also, Python does not support overloaded
765 methods/functions and default arguments are an easy way of
766 "faking" the overloading behavior.
767 </P>
768 <P class="">
apicard@google.com424ad342012-09-18 23:16:02 +0000769<SPAN class="stylepoint_section">Cons: </SPAN>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000770 Default arguments are evaluated once at module load
771 time. This may cause problems if the argument is a mutable
772 object such as a list or a dictionary. If the function modifies
773 the object (e.g., by appending an item to a list), the default
774 value is modified.
775 </P>
776 <P class="">
777<SPAN class="stylepoint_section">Decision: </SPAN>
778 Okay to use with the following caveats:
779 <p>
780 Do not use mutable objects as default values in the function or method
781 definition.
782 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000783<DIV class=""><PRE>Yes: <span class="external"></span>def foo(a, b=None):
apicard@google.comf900c2c2009-07-23 20:09:56 +0000784 <span class="external"> </span>if b is None:
mmentovai9ec7bd62009-12-03 22:25:38 +0000785 <span class="external"> </span>b = []</PRE></DIV>
786<DIV class=""><PRE class="badcode">No: <span class="external"></span>def foo(a, b=[]):
787 <span class="external"> </span>...</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000788 <p>
mmentovaif7facf92009-10-23 21:01:49 +0000789 Calling code must use named values for arguments with a default value.
790 This helps document the code somewhat and helps prevent and detect
apicard@google.comf900c2c2009-07-23 20:09:56 +0000791 interface breakage when more arguments are added.
792 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000793<DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000794<span class="external"></span>def foo(a, b=1):
mmentovai9ec7bd62009-12-03 22:25:38 +0000795 <span class="external"> </span>...</PRE></DIV>
796<DIV class=""><PRE>Yes: <span class="external"></span>foo(1)
797 <span class="external"></span>foo(1, b=2)</PRE></DIV>
798<DIV class=""><PRE class="badcode">No: <span class="external"></span>foo(1, 2)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000799 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000800 </DIV></DIV>
801 </DIV>
802 <DIV class="">
803<H3><A name="Properties" id="Properties">Properties</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000804<SPAN class="link_button" id="link-Properties__button" name="link-Properties__button"><A href="?showone=Properties#Properties">
805 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000806 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Properties')" name="Properties__button" id="Properties__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000807 <DIV style="display:inline;" class="">
apicard@google.com424ad342012-09-18 23:16:02 +0000808 Use properties for accessing or setting data where you would
809 normally have used simple, lightweight accessor or setter methods.
mmentovai9ec7bd62009-12-03 22:25:38 +0000810 </DIV>
811 <DIV class=""><DIV class="stylepoint_body" name="Properties__body" id="Properties__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000812 <P class="">
813<SPAN class="stylepoint_section">Definition: </SPAN> A way to wrap method calls for getting and
814 setting an attribute as a standard attribute access when the
815 computation is lightweight.
816 </P>
817 <P class="">
818<SPAN class="stylepoint_section">Pros: </SPAN> Readability is increased by eliminating explicit
819 get and set method calls for simple attribute access. Allows
820 calculations to be lazy. Considered the Pythonic way to
821 maintain the interface of a class. In terms of performance,
822 allowing properties bypasses needing trivial accessor methods
823 when a direct variable access is reasonable. This also allows
824 accessor methods to be added in the future without breaking the
825 interface.
826 </P>
827 <P class="">
828<SPAN class="stylepoint_section">Cons: </SPAN> Properties are specified after the getter and
829 setter methods are declared, requiring one to notice they are
830 used for properties farther down in the code (except for readonly
831 properties created with the <code>@property</code> decorator - see
832 below). Must inherit from
833 <code>object</code>. Can hide side-effects much like operator
834 overloading. Can be confusing for subclasses.
835 </P>
836 <P class="">
837<SPAN class="stylepoint_section">Decision: </SPAN> Use properties in new code to access or
838 set data where you would normally have used simple, lightweight
839 accessor or setter methods. Read-only properties should be created
apicard@google.com424ad342012-09-18 23:16:02 +0000840 with the <code>@property</code>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000841 <a HREF="#Function_and_Method_Decorators">decorator</a>.
842
843 <p><a id="properties-template-dp">
844 Inheritance with properties can be non-obvious if the property itself is
845 not overridden. Thus one must make sure that accessor methods are
846 called indirectly to ensure methods overridden in subclasses are called
847 by the property (using the Template Method DP).
848 </a></p>
849
mmentovai9ec7bd62009-12-03 22:25:38 +0000850 <DIV class=""><PRE>Yes: <span class="external"></span>import math
apicard@google.comf900c2c2009-07-23 20:09:56 +0000851
852 <span class="external"></span>class Square(object):
853 <span class="external"> </span>"""A square with two properties: a writable area and a read-only perimeter.
854
855 <span class="external"> </span>To use:
856 <span class="external"> </span>&gt;&gt;&gt; sq = Square(3)
857 <span class="external"> </span>&gt;&gt;&gt; sq.area
858 <span class="external"> </span>9
859 <span class="external"> </span>&gt;&gt;&gt; sq.perimeter
860 <span class="external"> </span>12
861 <span class="external"> </span>&gt;&gt;&gt; sq.area = 16
862 <span class="external"> </span>&gt;&gt;&gt; sq.side
863 <span class="external"> </span>4
864 <span class="external"> </span>&gt;&gt;&gt; sq.perimeter
865 <span class="external"> </span>16
866 <span class="external"> </span>"""
867
868 <span class="external"> </span>def __init__(self, side):
869 <span class="external"> </span>self.side = side
870
871 <span class="external"> </span>def __get_area(self):
872 <span class="external"> </span>"""Calculates the 'area' property."""
873 <span class="external"> </span>return self.side ** 2
874
875 <span class="external"> </span>def ___get_area(self):
876 <span class="external"> </span>"""Indirect accessor for 'area' property."""
877 <span class="external"> </span>return self.__get_area()
878
879 <span class="external"> </span>def __set_area(self, area):
880 <span class="external"> </span>"""Sets the 'area' property."""
881 <span class="external"> </span>self.side = math.sqrt(area)
882
883 <span class="external"> </span>def ___set_area(self, area):
884 <span class="external"> </span>"""Indirect setter for 'area' property."""
mark@chromium.org7f891932011-11-04 21:13:33 +0000885 <span class="external"> </span>self.__set_area(area)
apicard@google.comf900c2c2009-07-23 20:09:56 +0000886
887 <span class="external"> </span>area = property(___get_area, ___set_area,
888 <span class="external"> </span> doc="""Gets or sets the area of the square.""")
889
890 <span class="external"> </span>@property
891 <span class="external"> </span>def perimeter(self):
892 <span class="external"> </span>return self.side * 4
893<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000894</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000895 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000896 </DIV></DIV>
897 </DIV>
898 <DIV class="">
899<H3><A name="True/False_evaluations" id="True/False_evaluations">True/False evaluations</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000900<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">
901 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000902 </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 +0000903 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000904 Use the "implicit" false if at all possible.
mmentovai9ec7bd62009-12-03 22:25:38 +0000905 </DIV>
906 <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 +0000907 <P class="">
908<SPAN class="stylepoint_section">Definition: </SPAN> Python evaluates certain values as <code>false</code>
909 when in a boolean context. A quick "rule of thumb" is that all
910 "empty" values are considered <code>false</code> so <code>0, None, [], {},
apicard@google.com424ad342012-09-18 23:16:02 +0000911 ''</code> all evaluate as <code>false</code> in a boolean context.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000912 </P>
913 <P class="">
914<SPAN class="stylepoint_section">Pros: </SPAN> Conditions using Python booleans are easier to read
915 and less error-prone. In most cases, they're also faster.
916 </P>
917 <P class="">
918<SPAN class="stylepoint_section">Cons: </SPAN>
919 May look strange to C/C++ developers.
920 </P>
921 <P class="">
922<SPAN class="stylepoint_section">Decision: </SPAN>
923 Use the "implicit" false if at all possible, e.g., <code>if
924 foo:</code> rather than <code>if foo != []:</code>. There are a
925 few caveats that you should keep in mind though:
926 <ul>
927 <li>
928 Never use <code>==</code> or <code>!=</code> to compare
929 singletons like <code>None</code>. Use <code>is</code>
930 or <code>is not</code>.</li>
931
932 <li>Beware of writing <code>if x:</code> when you really mean
933 <code>if x is not None:</code>—e.g., when testing whether
934 a variable or argument that defaults to <code>None</code> was
935 set to some other value. The other value might be a value
936 that's false in a boolean context!</li>
937
938 <li>
939 Never compare a boolean variable to <code>False</code> using
940 <code>==</code>. Use <code>if not x:</code> instead. If
941 you need to distinguish <code>False</code> from
942 <code>None</code> then chain the expressions,
943 such as <code>if not x and x is not None:</code>.
944 </li>
945
946 <li>
947 For sequences (strings, lists, tuples), use the fact that
948 empty sequences are false, so <code>if not seq:</code> or
949 <code>if seq:</code> is preferable to <code>if
950 len(seq):</code> or <code>if not
951 len(seq):</code>.</li>
952
953 <li>
954 When handling integers, implicit false may involve more risk than
955 benefit (i.e., accidentally handling <code>None</code> as 0). You may
956 compare a value which is known to be an integer (and is not the
957 result of <code>len()</code>) against the integer 0.
mmentovai9ec7bd62009-12-03 22:25:38 +0000958<DIV class=""><PRE>Yes: <span class="external"></span>if not users:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000959 <span class="external"> </span>print 'no users'
960
961 <span class="external"></span>if foo == 0:
962 <span class="external"> </span>self.handle_zero()
963
964 <span class="external"></span>if i % 10 == 0:
mmentovai9ec7bd62009-12-03 22:25:38 +0000965 <span class="external"> </span>self.handle_multiple_of_ten()</PRE></DIV>
966<DIV class=""><PRE class="badcode">No: <span class="external"></span>if len(users) == 0:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000967 <span class="external"> </span>print 'no users'
968
969 <span class="external"></span>if foo is not None and not foo:
970 <span class="external"> </span>self.handle_zero()
971
972 <span class="external"></span>if not i % 10:
mmentovai9ec7bd62009-12-03 22:25:38 +0000973 <span class="external"> </span>self.handle_multiple_of_ten()</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000974</li>
975
976 <li>
977 Note that <code>'0'</code> (i.e., <code>0</code> as string)
978 evaluates to true.</li>
979 </ul>
980 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000981 </DIV></DIV>
982 </DIV>
983 <DIV class="">
984<H3><A name="Deprecated_Language_Features" id="Deprecated_Language_Features">Deprecated Language Features</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000985<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">
986 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000987 </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 +0000988 <DIV style="display:inline;" class="">
mmentovaif7facf92009-10-23 21:01:49 +0000989 Use string methods instead of the <code>string</code> module
990 where possible. Use function call syntax instead
991 of <code>apply</code>. Use list comprehensions
mark@chromium.orgc8c76a22012-11-28 20:26:27 +0000992 and <code>for</code> loops instead of <code>filter</code> and
993 <code>map</code> when the function argument would have been an
994 inlined lambda anyway. Use <code>for</code> loops instead of
995 <code>reduce</code>.
mmentovai9ec7bd62009-12-03 22:25:38 +0000996 </DIV>
997 <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 +0000998 <P class="">
mmentovaif7facf92009-10-23 21:01:49 +0000999<SPAN class="stylepoint_section">Definition: </SPAN>
1000 Current versions of Python provide alternative constructs
1001 that people find generally preferable.
apicard@google.comf900c2c2009-07-23 20:09:56 +00001002 </P>
1003 <P class="">
mmentovaif7facf92009-10-23 21:01:49 +00001004<SPAN class="stylepoint_section">Decision: </SPAN>
1005 We do not use any Python version which does not support
1006 these features, so there is no reason not to use the new
1007 styles.
mmentovai9ec7bd62009-12-03 22:25:38 +00001008<DIV class=""><PRE>Yes: <span class="external"></span>words = foo.split(':')
mmentovaif7facf92009-10-23 21:01:49 +00001009
1010 <span class="external"></span>[x[1] for x in my_list if x[2] == 5]
1011
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001012 <span class="external"></span>map(math.sqrt, data) # Ok. No inlined lambda expression.
1013
mmentovai9ec7bd62009-12-03 22:25:38 +00001014 <span class="external"></span>fn(*args, **kwargs)</PRE></DIV>
apicard@google.com424ad342012-09-18 23:16:02 +00001015<DIV class=""><PRE class="badcode">No: <span class="external"></span>words = string.split(foo, ':')
1016
1017 <span class="external"></span>map(lambda x: x[1], filter(lambda x: x[2] == 5, my_list))
1018
1019 <span class="external"></span>apply(fn, args, kwargs)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001020 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001021 </DIV></DIV>
1022 </DIV>
1023 <DIV class="">
1024<H3><A name="Lexical_Scoping" id="Lexical_Scoping">Lexical Scoping</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001025<SPAN class="link_button" id="link-Lexical_Scoping__button" name="link-Lexical_Scoping__button"><A href="?showone=Lexical_Scoping#Lexical_Scoping">
1026 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001027 </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 +00001028 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001029 Okay to use.
mmentovai9ec7bd62009-12-03 22:25:38 +00001030 </DIV>
1031 <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 +00001032 <P class="">
1033<SPAN class="stylepoint_section">Definition: </SPAN>
1034 A nested Python function can refer to variables defined in
1035 enclosing functions, but can not assign to them. Variable
1036 bindings are resolved using lexical scoping, that is, based on
1037 the static program text. Any assignment to a name in a block
1038 will cause Python to treat all references to that name as a
1039 local variable, even if the use precedes the assignment. If a
1040 global declaration occurs, the name is treated as a global
1041 variable.
apicard@google.com424ad342012-09-18 23:16:02 +00001042
apicard@google.comf900c2c2009-07-23 20:09:56 +00001043 <p>
1044 An example of the use of this feature is:
1045 </p>
1046
mmentovai9ec7bd62009-12-03 22:25:38 +00001047 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001048<span class="external"></span>def get_adder(summand1):
1049 <span class="external"> </span>"""Returns a function that adds numbers to a given number."""
1050 <span class="external"> </span>def adder(summand2):
1051 <span class="external"> </span>return summand1 + summand2
1052
1053 <span class="external"> </span>return adder
1054<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001055</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001056 </P>
1057 <P class="">
1058<SPAN class="stylepoint_section">Pros: </SPAN>
1059 Often results in clearer, more elegant code. Especially comforting
1060 to experienced Lisp and Scheme (and Haskell and ML and …)
1061 programmers.
1062 </P>
1063 <P class="">
1064<SPAN class="stylepoint_section">Cons: </SPAN>
apicard@google.com424ad342012-09-18 23:16:02 +00001065 Can lead to confusing bugs. Such as this example based on
apicard@google.comf900c2c2009-07-23 20:09:56 +00001066 <a HREF="http://www.python.org/dev/peps/pep-0227/">PEP-0227</a>:
mmentovai9ec7bd62009-12-03 22:25:38 +00001067<DIV class=""><PRE class="badcode">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001068<span class="external"></span>i = 4
1069<span class="external"></span>def foo(x):
1070 <span class="external"> </span>def bar():
1071 <span class="external"> </span>print i,
1072 <span class="external"> </span># ...
1073 <span class="external"> </span># A bunch of code here
1074 <span class="external"> </span># ...
1075 <span class="external"> </span>for i in x: # Ah, i *is* local to Foo, so this is what Bar sees
1076 <span class="external"> </span>print i,
mmentovai9ec7bd62009-12-03 22:25:38 +00001077 <span class="external"> </span>bar()</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001078 <p>
1079 So <code>foo([1, 2, 3])</code> will print <code>1 2 3 3</code>, not
1080 <code>1 2 3 4</code>.
apicard@google.com424ad342012-09-18 23:16:02 +00001081 </p>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001082 </P>
1083 <P class="">
1084<SPAN class="stylepoint_section">Decision: </SPAN>
1085 Okay to use.
1086 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001087 </DIV></DIV>
1088 </DIV>
1089 <DIV class="">
1090<H3><A name="Function_and_Method_Decorators" id="Function_and_Method_Decorators">Function and Method Decorators</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001091<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">
1092 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001093 </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 +00001094 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001095 Use decorators judiciously when there is a clear advantage.
mmentovai9ec7bd62009-12-03 22:25:38 +00001096 </DIV>
1097 <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 +00001098 <P class="">
1099<SPAN class="stylepoint_section">Definition: </SPAN>
1100
1101 <a HREF="http://www.python.org/doc/2.4.3/whatsnew/node6.html">Decorators
1102 for Functions and Methods</a>
1103 (a.k.a "the <code>@</code> notation").
1104 The most common decorators are <code>@classmethod</code> and
1105 <code>@staticmethod</code>, for converting ordinary methods to class or
1106 static methods. However, the decorator syntax allows for
1107 user-defined decorators as well. Specifically, for some function
1108 <code>my_decorator</code>, this:
mmentovai9ec7bd62009-12-03 22:25:38 +00001109 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001110<span class="external"></span>class C(object):
1111 <span class="external"> </span>@my_decorator
1112 <span class="external"> </span>def method(self):
1113 <span class="external"> </span># method body ...
1114<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001115</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001116
1117 is equivalent to:
mmentovai9ec7bd62009-12-03 22:25:38 +00001118 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001119<span class="external"></span>class C(object):
1120 <span class="external"> </span>def method(self):
1121 <span class="external"> </span># method body ...
1122 <span class="external"> </span>method = my_decorator(method)
1123<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001124</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001125 </P>
1126 <P class="">
1127<SPAN class="stylepoint_section">Pros: </SPAN> Elegantly specifies some transformation on a method; the
1128 transformation might eliminate some repetitive code, enforce invariants,
1129 etc.
1130 </P>
1131 <P class="">
1132<SPAN class="stylepoint_section">Cons: </SPAN> Decorators can perform arbitrary operations on a
1133 function's arguments or return values, resulting in surprising
1134 implicit behavior.
1135 Additionally, decorators execute at import time. Failures in decorator
1136 code are pretty much impossible to recover from.
1137 </P>
1138 <P class="">
1139<SPAN class="stylepoint_section">Decision: </SPAN> Use decorators judiciously when there is a clear
1140 advantage. Decorators should follow the same import and naming
1141 guidelines as functions. Decorator pydoc should clearly state that the
1142 function is a decorator. Write unit tests for decorators.
1143
1144 <p>
1145 Avoid external dependencies in the decorator itself (e.g. don't rely on
1146 files, sockets, database connections, etc.), since they might not be
1147 available when the decorator runs (at import time, perhaps from
1148 <code>pychecker</code> or other tools). A decorator that is
1149 called with valid parameters should (as much as possible) be guaranteed
1150 to succeed in all cases.
1151 </p>
1152 <p>
1153 Decorators are a special case of "top level code" - see
1154 <a HREF="#Main">main</a> for more discussion.
1155 </p>
1156 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001157 </DIV></DIV>
1158 </DIV>
1159 <DIV class="">
1160<H3><A name="Threading" id="Threading">Threading</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001161<SPAN class="link_button" id="link-Threading__button" name="link-Threading__button"><A href="?showone=Threading#Threading">
1162 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001163 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Threading')" name="Threading__button" id="Threading__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001164 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001165 Do not rely on the atomicity of built-in types.
mmentovai9ec7bd62009-12-03 22:25:38 +00001166 </DIV>
1167 <DIV class=""><DIV class="stylepoint_body" name="Threading__body" id="Threading__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001168 <p>
1169 While Python's built-in data types such as dictionaries appear
1170 to have atomic operations, there are corner cases where they
1171 aren't atomic (e.g. if <code>__hash__</code> or
1172 <code>__eq__</code> are implemented as Python methods) and their
1173 atomicity should not be relied upon. Neither should you rely on
1174 atomic variable assignment (since this in turn depends on
1175 dictionaries).
1176 </p>
1177
1178 <p>
apicard@google.com424ad342012-09-18 23:16:02 +00001179 Use the Queue module's <code>Queue</code> data type as the preferred
apicard@google.comf900c2c2009-07-23 20:09:56 +00001180 way to
1181 communicate data between threads. Otherwise, use the threading
1182 module and its locking primitives. Learn about the proper use
1183 of condition variables so you can use
1184 <code>threading.Condition</code> instead of using lower-level
1185 locks.
1186 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001187 </DIV></DIV>
1188 </DIV>
1189 <DIV class="">
1190<H3><A name="Power_Features" id="Power_Features">Power Features</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001191<SPAN class="link_button" id="link-Power_Features__button" name="link-Power_Features__button"><A href="?showone=Power_Features#Power_Features">
1192 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001193 </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 +00001194 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001195 Avoid these features.
mmentovai9ec7bd62009-12-03 22:25:38 +00001196 </DIV>
1197 <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 +00001198 <P class="">
1199<SPAN class="stylepoint_section">Definition: </SPAN> Python is an extremely flexible language and
1200 gives you many fancy features such as metaclasses, access to bytecode,
1201 on-the-fly compilation, dynamic inheritance, object reparenting,
1202 import hacks, reflection, modification of system internals,
1203 etc.
1204 </P>
1205 <P class="">
1206<SPAN class="stylepoint_section">Pros: </SPAN> These are powerful language features. They can
1207 make your code more compact.
1208 </P>
1209 <P class="">
1210<SPAN class="stylepoint_section">Cons: </SPAN> It's very tempting to use these "cool" features
1211 when they're not absolutely necessary. It's harder to read,
1212 understand, and debug code that's using unusual features
1213 underneath. It doesn't seem that way at first (to the original
1214 author), but when revisiting the code, it tends to be more
1215 difficult than code that is longer but is straightforward.
1216 </P>
1217 <P class="">
apicard@google.com424ad342012-09-18 23:16:02 +00001218<SPAN class="stylepoint_section">Decision: </SPAN>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001219 Avoid these features in
1220 your code.
1221 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001222 </DIV></DIV>
1223 </DIV>
1224 </DIV>
1225 <DIV class="">
1226<H2 name="Python_Style_Rules" id="Python_Style_Rules">Python Style Rules</H2>
1227 <DIV class="">
1228<H3><A name="Semicolons" id="Semicolons">Semicolons</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001229<SPAN class="link_button" id="link-Semicolons__button" name="link-Semicolons__button"><A href="?showone=Semicolons#Semicolons">
1230 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001231 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Semicolons')" name="Semicolons__button" id="Semicolons__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001232 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001233 Do not terminate your lines with semi-colons and do not use
1234 semi-colons to put two commands on the same line.
mmentovai9ec7bd62009-12-03 22:25:38 +00001235 </DIV>
1236 <DIV class=""><DIV class="stylepoint_body" name="Semicolons__body" id="Semicolons__body" style="display: none">
mmentovai9ec7bd62009-12-03 22:25:38 +00001237 </DIV></DIV>
1238 </DIV>
1239 <DIV class="">
1240<H3><A name="Line_length" id="Line_length">Line length</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001241<SPAN class="link_button" id="link-Line_length__button" name="link-Line_length__button"><A href="?showone=Line_length#Line_length">
1242 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001243 </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 +00001244 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001245 Maximum line length is <em>80 characters</em>.
mmentovai9ec7bd62009-12-03 22:25:38 +00001246 </DIV>
1247 <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 +00001248 <p>
apicard@google.com424ad342012-09-18 23:16:02 +00001249 Exception: lines importing modules may end up longer than 80
1250 characters only if using Python 2.4 or
apicard@google.comf900c2c2009-07-23 20:09:56 +00001251 earlier.
1252 </p>
1253
1254 <p>
mark@chromium.orge33361f2011-11-04 16:55:22 +00001255 Do not use backslash line continuation.
1256 </p>
1257
1258 <p>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001259 Make use of Python's
1260
1261 <a HREF="http://www.python.org/doc/ref/implicit-joining.html">implicit
1262 line joining inside parentheses, brackets and braces</a>.
1263 If necessary, you can add an extra pair of parentheses around an
1264 expression.
1265 </p>
1266
1267
mmentovai9ec7bd62009-12-03 22:25:38 +00001268 <DIV class=""><PRE>Yes: foo_bar(self, width, height, color='black', design=None, x='foo',
apicard@google.comf900c2c2009-07-23 20:09:56 +00001269 emphasis=None, highlight=0)
1270
1271 if (width == 0 and height == 0 and
mmentovai9ec7bd62009-12-03 22:25:38 +00001272 color == 'red' and emphasis == 'strong'):</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001273
1274
1275 <p>
1276 When a literal string won't fit on a single line, use parentheses for
1277 implicit line joining.
1278 </p>
1279
mmentovai9ec7bd62009-12-03 22:25:38 +00001280 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001281<span class="external"></span>x = ('This will build a very long long '
mmentovai9ec7bd62009-12-03 22:25:38 +00001282<span class="external"></span> 'long long long long long long string')</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001283
1284 <p>
1285 Make note of the indentation of the elements in the line
apicard@google.com424ad342012-09-18 23:16:02 +00001286 continuation examples above; see the
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001287 <a HREF="#Indentation">indentation</a>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001288 section for explanation.
1289 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001290 </DIV></DIV>
1291 </DIV>
1292 <DIV class="">
1293<H3><A name="Parentheses" id="Parentheses">Parentheses</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001294<SPAN class="link_button" id="link-Parentheses__button" name="link-Parentheses__button"><A href="?showone=Parentheses#Parentheses">
1295 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001296 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Parentheses')" name="Parentheses__button" id="Parentheses__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001297 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001298 Use parentheses sparingly.
mmentovai9ec7bd62009-12-03 22:25:38 +00001299 </DIV>
1300 <DIV class=""><DIV class="stylepoint_body" name="Parentheses__body" id="Parentheses__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001301 <p>
apicard@google.com424ad342012-09-18 23:16:02 +00001302 Do not use them in return statements or conditional statements unless
1303 using parentheses for implied line continuation. (See above.)
apicard@google.comf900c2c2009-07-23 20:09:56 +00001304 It is however fine to use parentheses around tuples.
1305 </p>
1306
mmentovai9ec7bd62009-12-03 22:25:38 +00001307<DIV class=""><PRE>Yes: <span class="external"></span>if foo:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001308 <span class="external"> </span>bar()
1309 <span class="external"></span>while x:
1310 <span class="external"> </span>x = bar()
1311 <span class="external"></span>if x and y:
1312 <span class="external"> </span>bar()
1313 <span class="external"></span>if not x:
1314 <span class="external"> </span>bar()
1315 <span class="external"></span>return foo
mmentovai9ec7bd62009-12-03 22:25:38 +00001316 <span class="external"></span>for (x, y) in dict.items(): ...</PRE></DIV>
1317<DIV class=""><PRE class="badcode">No: <span class="external"></span>if (x):
apicard@google.comf900c2c2009-07-23 20:09:56 +00001318 <span class="external"> </span>bar()
1319 <span class="external"></span>if not(x):
1320 <span class="external"> </span>bar()
mmentovai9ec7bd62009-12-03 22:25:38 +00001321 <span class="external"></span>return (foo)</PRE></DIV>
1322 </DIV></DIV>
1323 </DIV>
1324 <DIV class="">
1325<H3><A name="Indentation" id="Indentation">Indentation</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001326<SPAN class="link_button" id="link-Indentation__button" name="link-Indentation__button"><A href="?showone=Indentation#Indentation">
1327 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001328 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Indentation')" name="Indentation__button" id="Indentation__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001329 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001330 Indent your code blocks with <em>4 spaces</em>.
mmentovai9ec7bd62009-12-03 22:25:38 +00001331 </DIV>
1332 <DIV class=""><DIV class="stylepoint_body" name="Indentation__body" id="Indentation__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001333 <p>
1334 Never use tabs or mix tabs and spaces.
1335 In cases of implied line continuation, you should align wrapped elements
1336 either vertically, as per the examples in the
1337 <a HREF="#Line_length">line length</a> section; or using a hanging
1338 indent of 4 spaces, in which case there should be no argument on
1339 the first line.
1340 </p>
1341
1342
mmentovai9ec7bd62009-12-03 22:25:38 +00001343<DIV class=""><PRE>Yes: # Aligned with opening delimiter
apicard@google.comf900c2c2009-07-23 20:09:56 +00001344 foo = long_function_name(var_one, var_two,
1345 var_three, var_four)
1346
1347 # 4-space hanging indent; nothing on first line
1348 foo = long_function_name(
1349 var_one, var_two, var_three,
mmentovai9ec7bd62009-12-03 22:25:38 +00001350 var_four)</PRE></DIV>
1351<DIV class=""><PRE class="badcode">No: <span class="external"></span># Stuff on first line forbidden
apicard@google.comf900c2c2009-07-23 20:09:56 +00001352 <span class="external"></span>foo = long_function_name(var_one, var_two,
1353 <span class="external"></span> var_three, var_four)
1354
1355 <span class="external"></span># 2-space hanging indent forbidden
1356 <span class="external"></span>foo = long_function_name(
1357 <span class="external"></span> var_one, var_two, var_three,
mmentovai9ec7bd62009-12-03 22:25:38 +00001358 <span class="external"></span> var_four)</PRE></DIV>
1359 </DIV></DIV>
1360 </DIV>
1361 <DIV class="">
1362<H3><A name="Blank_Lines" id="Blank_Lines">Blank Lines</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001363<SPAN class="link_button" id="link-Blank_Lines__button" name="link-Blank_Lines__button"><A href="?showone=Blank_Lines#Blank_Lines">
1364 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001365 </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 +00001366 <DIV style="display:inline;" class="">
apicard@google.com424ad342012-09-18 23:16:02 +00001367 Two blank lines between top-level definitions, one blank line
apicard@google.comf900c2c2009-07-23 20:09:56 +00001368 between method definitions.
mmentovai9ec7bd62009-12-03 22:25:38 +00001369 </DIV>
1370 <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 +00001371 <p>
1372 Two blank lines between top-level definitions, be they function
1373 or class definitions. One blank line between method definitions
1374 and between the <code>class</code> line and the first method.
1375 Use single blank lines as you judge appropriate within functions or
1376 methods.
1377 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001378 </DIV></DIV>
1379 </DIV>
1380 <DIV class="">
1381<H3><A name="Whitespace" id="Whitespace">Whitespace</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001382<SPAN class="link_button" id="link-Whitespace__button" name="link-Whitespace__button"><A href="?showone=Whitespace#Whitespace">
1383 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001384 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Whitespace')" name="Whitespace__button" id="Whitespace__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001385 <DIV style="display:inline;" class="">
apicard@google.com424ad342012-09-18 23:16:02 +00001386 Follow standard typographic rules for the use of spaces around
apicard@google.comf900c2c2009-07-23 20:09:56 +00001387 punctuation.
mmentovai9ec7bd62009-12-03 22:25:38 +00001388 </DIV>
1389 <DIV class=""><DIV class="stylepoint_body" name="Whitespace__body" id="Whitespace__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001390 <p>
1391 No whitespace inside parentheses, brackets or braces.
1392 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001393<DIV class=""><PRE>Yes: <span class="external"></span>spam(ham[1], {eggs: 2}, [])</PRE></DIV>
1394<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 +00001395 <p>
1396 No whitespace before a comma, semicolon, or colon. Do use
1397 whitespace after a comma, semicolon, or colon except at the end
1398 of the line.
1399 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001400<DIV class=""><PRE>Yes: <span class="external"></span>if x == 4:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001401 <span class="external"> </span>print x, y
mmentovai9ec7bd62009-12-03 22:25:38 +00001402 <span class="external"></span>x, y = y, x</PRE></DIV>
1403<DIV class=""><PRE class="badcode">No: <span class="external"></span>if x == 4 :
apicard@google.comf900c2c2009-07-23 20:09:56 +00001404 <span class="external"> </span>print x , y
mmentovai9ec7bd62009-12-03 22:25:38 +00001405 <span class="external"></span>x , y = y , x</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001406 <p>
1407 No whitespace before the open paren/bracket that starts an argument list,
1408 indexing or slicing.
1409 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001410 <DIV class=""><PRE>Yes: <span class="external"></span>spam(1)</PRE></DIV>
1411<DIV class=""><PRE class="badcode">No: <span class="external"></span>spam (1)</PRE></DIV>
1412<DIV class=""><PRE>Yes: <span class="external"></span>dict['key'] = list[index]</PRE></DIV>
1413<DIV class=""><PRE class="badcode">No: <span class="external"></span>dict ['key'] = list [index]</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001414
1415 <p>
1416 Surround binary operators with a single space on either side for
1417 assignment (<code>=</code>), comparisons (<code>==, &lt;, &gt;, !=,
1418 &lt;&gt;, &lt;=, &gt;=, in, not in, is, is not</code>), and Booleans
1419 (<code>and, or, not</code>). Use your better judgment for the
1420 insertion of spaces around arithmetic operators but always be
1421 consistent about whitespace on either side of a binary operator.
1422 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001423<DIV class=""><PRE>Yes: <span class="external"></span>x == 1</PRE></DIV>
1424<DIV class=""><PRE class="badcode">No: <span class="external"></span>x&lt;1</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001425 <p>
1426 Don't use spaces around the '=' sign when used to indicate a
1427 keyword argument or a default parameter value.
1428 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001429<DIV class=""><PRE>Yes: <span class="external"></span>def complex(real, imag=0.0): return magic(r=real, i=imag)</PRE></DIV>
1430<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 +00001431
1432 <p>
1433 Don't use spaces to vertically align tokens on consecutive lines, since it
1434 becomes a maintenance burden (applies to <code>:</code>, <code>#</code>,
1435 <code>=</code>, etc.):
1436 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001437<DIV class=""><PRE>Yes:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001438 foo = 1000 # comment
1439 long_name = 2 # comment that should not be aligned
1440
1441 dictionary = {
apicard@google.com424ad342012-09-18 23:16:02 +00001442 'foo': 1,
1443 'long_name': 2,
mmentovai9ec7bd62009-12-03 22:25:38 +00001444 }</PRE></DIV>
1445<DIV class=""><PRE class="badcode">No:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001446 foo = 1000 # comment
1447 long_name = 2 # comment that should not be aligned
1448
1449 dictionary = {
apicard@google.com424ad342012-09-18 23:16:02 +00001450 'foo' : 1,
1451 'long_name': 2,
mmentovai9ec7bd62009-12-03 22:25:38 +00001452 }</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001453
1454
mmentovai9ec7bd62009-12-03 22:25:38 +00001455 </DIV></DIV>
1456 </DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001457
mmentovaicd4ce0f2011-03-29 20:30:47 +00001458 <a name="Python_Interpreter"></a>
1459 <DIV class="">
1460<H3><A name="Shebang_Line" id="Shebang_Line">Shebang Line</A></H3>
1461<SPAN class="link_button" id="link-Shebang_Line__button" name="link-Shebang_Line__button"><A href="?showone=Shebang_Line#Shebang_Line">
1462 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001463 </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 +00001464 <DIV style="display:inline;" class="">
mark@chromium.orge33361f2011-11-04 16:55:22 +00001465 Most <code>.py</code> files do not need to start with a
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001466 <code>#!</code> line. Start the main file of a program with
mark@chromium.orge33361f2011-11-04 16:55:22 +00001467 <code>#!/usr/bin/python</code>.
mmentovaicd4ce0f2011-03-29 20:30:47 +00001468 </DIV>
1469 <DIV class=""><DIV class="stylepoint_body" name="Shebang_Line__body" id="Shebang_Line__body" style="display: none">
1470
1471 <p>
mark@chromium.orge33361f2011-11-04 16:55:22 +00001472 This line is used by the kernel to find the Python interpreter, but is
1473 ignored by Python when importing modules. It is only necessary on a
1474 file that will be executed directly.
mmentovaicd4ce0f2011-03-29 20:30:47 +00001475 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001476 </DIV></DIV>
1477 </DIV>
mmentovaicd4ce0f2011-03-29 20:30:47 +00001478
mmentovai9ec7bd62009-12-03 22:25:38 +00001479 <DIV class="">
1480<H3><A name="Comments" id="Comments">Comments</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001481<SPAN class="link_button" id="link-Comments__button" name="link-Comments__button"><A href="?showone=Comments#Comments">
1482 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001483 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Comments')" name="Comments__button" id="Comments__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001484 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001485 Be sure to use the right style for module, function, method and in-line
1486 comments.
mmentovai9ec7bd62009-12-03 22:25:38 +00001487 </DIV>
1488 <DIV class=""><DIV class="stylepoint_body" name="Comments__body" id="Comments__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001489
1490 <P class="">
1491<SPAN class="stylepoint_subsection">Doc Strings</SPAN>
1492
1493 <p>
1494 Python has a unique commenting style using doc strings. A doc
1495 string is a string that is the first statement in a package,
1496 module, class or function. These strings can be extracted
1497 automatically through the <code>__doc__</code> member of the
1498 object and are used by <code>pydoc</code>. (Try running
1499 <code>pydoc</code> on your module to see how it looks.) Our
1500 convention for doc strings is to use the three double-quote
1501 format for strings. A doc string should be organized as a
1502 summary line (one physical line) terminated by a period,
1503 question mark, or exclamation point, followed by a blank line,
1504 followed by the rest of the doc string starting at the same
1505 cursor position as the first quote of the first line. There are
1506 more formatting guidelines for doc strings below.
1507 </p>
1508
1509 </P>
1510 <P class="">
1511<SPAN class="stylepoint_subsection">Modules</SPAN>
1512
1513
1514
1515 <p>
apicard@google.com424ad342012-09-18 23:16:02 +00001516 Every file should contain license boilerplate.
1517 Choose the appropriate boilerplate for the license used by the project
1518 (for example, Apache 2.0, BSD, LGPL, GPL)
apicard@google.comf900c2c2009-07-23 20:09:56 +00001519 </p>
1520 </P>
1521 <P class="">
1522<SPAN class="stylepoint_subsection">Functions and Methods</SPAN>
1523
1524 <p>
mark@chromium.orge33361f2011-11-04 16:55:22 +00001525 As used in this section "function" applies to methods, function, and
1526 generators.
apicard@google.comf900c2c2009-07-23 20:09:56 +00001527 </p>
1528
mark@chromium.orge33361f2011-11-04 16:55:22 +00001529 <p>
1530 A function must have a docstring, unless it meets all of the following
1531 criteria:
1532 <ul>
1533 <li>not externally visible</li>
1534 <li>very short</li>
1535 <li>obvious</li>
1536 </ul>
1537 </p>
1538
1539 <p>
1540 A docstring should give enough information to write a call to the function
1541 without reading the function's code. A docstring should describe the
1542 function's calling syntax and its semantics, not its implementation. For
1543 tricky code, comments alongside the code are more appropriate than using
1544 docstrings.
1545 </p>
1546
1547 <p>
1548 Certain aspects of a function should be documented in special sections,
1549 listed below. Each section begins with a heading line, which ends with a
1550 colon. Sections should be indented two spaces, except for the heading.
1551 </p>
1552
1553 <dl>
1554 <dt>Args:</dt>
1555 <dd>
1556 List each parameter by name. A description should follow the name, and
1557 be separated by a colon and a space. If the description is too long to
1558 fit on a single 80-character line, use a hanging indent of 2 or 4 spaces
1559 (be consistent with the rest of the file).
1560
1561 <p>
1562 The description should mention required type(s) and the meaning of
1563 the argument.
1564 </p>
1565
1566 <p>
1567 If a function accepts *foo (variable length argument lists) and/or
1568 **bar (arbitrary keyword arguments), they should be listed as *foo and
1569 **bar.
1570 </p>
1571 </dd>
1572
1573 <dt>Returns: (or Yields: for generators)</dt>
1574 <dd>
1575 Describe the type and semantics of the return value. If the function
1576 only returns None, this section is not required.
1577 </dd>
1578
1579 <dt>Raises:</dt>
1580 <dd>
1581 List all exceptions that are relevant to the interface.
1582 </dd>
1583 </dl>
1584
mmentovai9ec7bd62009-12-03 22:25:38 +00001585 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001586<span class="external"></span>def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
1587 <span class="external"> </span>"""Fetches rows from a Bigtable.
1588
1589 <span class="external"> </span>Retrieves rows pertaining to the given keys from the Table instance
1590 <span class="external"> </span>represented by big_table. Silly things may happen if
1591 <span class="external"> </span>other_silly_variable is not None.
1592
1593 <span class="external"> </span>Args:
1594 <span class="external"> </span>big_table: An open Bigtable Table instance.
1595 <span class="external"> </span>keys: A sequence of strings representing the key of each table row
1596 <span class="external"> </span> to fetch.
1597 <span class="external"> </span>other_silly_variable: Another optional variable, that has a much
1598 <span class="external"> </span> longer name than the other args, and which does nothing.
1599
1600 <span class="external"> </span>Returns:
1601 <span class="external"> </span>A dict mapping keys to the corresponding table row data
1602 <span class="external"> </span>fetched. Each row is represented as a tuple of strings. For
1603 <span class="external"> </span>example:
1604
1605 <span class="external"> </span>{'Serak': ('Rigel VII', 'Preparer'),
1606 <span class="external"> </span> 'Zim': ('Irk', 'Invader'),
1607 <span class="external"> </span> 'Lrrr': ('Omicron Persei 8', 'Emperor')}
1608
1609 <span class="external"> </span>If a key from the keys argument is missing from the dictionary,
1610 <span class="external"> </span>then that row was not found in the table.
1611
1612 <span class="external"> </span>Raises:
1613 <span class="external"> </span>IOError: An error occurred accessing the bigtable.Table object.
1614 <span class="external"> </span>"""
1615 <span class="external"> </span>pass
1616<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001617</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001618 </P>
1619 <P class="">
1620<SPAN class="stylepoint_subsection">Classes</SPAN>
1621
1622 <p>
1623 Classes should have a doc string below the class definition describing
1624 the class. If your class has public attributes, they should be documented
1625 here in an Attributes section and follow the same formatting as a
1626 function's Args section.
1627 </p>
1628
mmentovai9ec7bd62009-12-03 22:25:38 +00001629 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001630<span class="external"></span>class SampleClass(object):
1631 <span class="external"> </span>"""Summary of class here.
1632
1633 <span class="external"> </span>Longer class information....
1634 <span class="external"> </span>Longer class information....
1635
1636 <span class="external"> </span>Attributes:
1637 <span class="external"> </span>likes_spam: A boolean indicating if we like SPAM or not.
1638 <span class="external"> </span>eggs: An integer count of the eggs we have laid.
1639 <span class="external"> </span>"""
1640
1641 <span class="external"> </span>def __init__(self, likes_spam=False):
1642 <span class="external"> </span>"""Inits SampleClass with blah."""
1643 <span class="external"> </span>self.likes_spam = likes_spam
1644 <span class="external"> </span>self.eggs = 0
1645
1646 <span class="external"> </span>def public_method(self):
1647 <span class="external"> </span>"""Performs operation blah."""
1648<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001649</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001650
1651 </P>
1652 <P class="">
1653<SPAN class="stylepoint_subsection">Block and Inline Comments</SPAN>
1654
1655 <p>
1656 The final place to have comments is in tricky parts of the
apicard@google.com424ad342012-09-18 23:16:02 +00001657 code. If you're going to have to explain it at the next
1658 <a HREF="http://en.wikipedia.org/wiki/Code_review">code review</a>,
1659 you should comment it now. Complicated operations get a few lines of
apicard@google.comf900c2c2009-07-23 20:09:56 +00001660 comments before the operations
1661 commence. Non-obvious ones get comments at the end of the line.
1662 </p>
1663
mmentovai9ec7bd62009-12-03 22:25:38 +00001664 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001665<span class="external"></span># We use a weighted dictionary search to find out where i is in
1666<span class="external"></span># the array. We extrapolate position based on the largest num
1667<span class="external"></span># in the array and the array size and then do binary search to
1668<span class="external"></span># get the exact number.
1669
1670<span class="external"></span>if i &amp; (i-1) == 0: # true iff i is a power of 2
1671<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001672</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001673
1674 <p>
1675 To improve legibility, these comments should be at least 2 spaces away
1676 from the code.
1677 </p>
1678
1679 <p>
1680 On the other hand, never describe the code. Assume the person
1681 reading the code knows Python (though not what you're trying to
1682 do) better than you do.
1683 </p>
1684
mmentovai9ec7bd62009-12-03 22:25:38 +00001685 <DIV class=""><PRE class="badcode">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001686<span class="external"></span># BAD COMMENT: Now go through the b array and make sure whenever i occurs
1687<span class="external"></span># the next element is i+1
1688<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001689</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001690
1691 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001692 </DIV></DIV>
1693 </DIV>
1694 <DIV class="">
1695<H3><A name="Classes" id="Classes">Classes</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001696<SPAN class="link_button" id="link-Classes__button" name="link-Classes__button"><A href="?showone=Classes#Classes">
1697 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001698 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Classes')" name="Classes__button" id="Classes__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001699 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001700 If a class inherits from no other base classes, explicitly inherit
1701 from <code>object</code>. This also applies to nested classes.
mmentovai9ec7bd62009-12-03 22:25:38 +00001702 </DIV>
1703 <DIV class=""><DIV class="stylepoint_body" name="Classes__body" id="Classes__body" style="display: none">
mmentovai9ec7bd62009-12-03 22:25:38 +00001704 <DIV class=""><PRE>Yes: <span class="external"></span>class SampleClass(object):
apicard@google.comf900c2c2009-07-23 20:09:56 +00001705 <span class="external"> </span>pass
1706
1707
1708 <span class="external"></span>class OuterClass(object):
1709
1710 <span class="external"> </span>class InnerClass(object):
1711 <span class="external"> </span>pass
1712
1713
1714 <span class="external"></span>class ChildClass(ParentClass):
1715 <span class="external"> </span>"""Explicitly inherits from another class already."""
1716<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001717</PRE></DIV>
apicard@google.com424ad342012-09-18 23:16:02 +00001718 <DIV class=""><PRE class="badcode">No: <span class="external"></span>class SampleClass:
1719 <span class="external"> </span>pass
apicard@google.comf900c2c2009-07-23 20:09:56 +00001720
apicard@google.com424ad342012-09-18 23:16:02 +00001721
1722 <span class="external"></span>class OuterClass:
1723
1724 <span class="external"> </span>class InnerClass:
1725 <span class="external"> </span>pass
1726<span class="external"></span>
1727</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001728 <p>Inheriting from <code>object</code> is needed to make properties work
apicard@google.com424ad342012-09-18 23:16:02 +00001729 properly, and it will protect your code from one particular potential
apicard@google.comf900c2c2009-07-23 20:09:56 +00001730 incompatibility with Python 3000. It also defines
1731 special methods that implement the default semantics of objects including
1732 <code>__new__</code>, <code>__init__</code>, <code>__delattr__</code>,
1733 <code>__getattribute__</code>, <code>__setattr__</code>,
1734 <code>__hash__</code>, <code>__repr__</code>, and <code>__str__</code>.
1735 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001736 </DIV></DIV>
1737 </DIV>
1738 <DIV class="">
1739<H3><A name="Strings" id="Strings">Strings</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001740<SPAN class="link_button" id="link-Strings__button" name="link-Strings__button"><A href="?showone=Strings#Strings">
1741 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001742 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Strings')" name="Strings__button" id="Strings__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001743 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001744 Use the <code>%</code> operator for formatting strings,
1745 even when the parameters are all strings. Use your best judgement
1746 to decide between <code>+</code> and <code>%</code> though.
mmentovai9ec7bd62009-12-03 22:25:38 +00001747 </DIV>
1748 <DIV class=""><DIV class="stylepoint_body" name="Strings__body" id="Strings__body" style="display: none">
apicard@google.com424ad342012-09-18 23:16:02 +00001749
mmentovai9ec7bd62009-12-03 22:25:38 +00001750<DIV class=""><PRE>Yes: <span class="external"></span>x = a + b
apicard@google.comf900c2c2009-07-23 20:09:56 +00001751 <span class="external"></span>x = '%s, %s!' % (imperative, expletive)
mmentovai9ec7bd62009-12-03 22:25:38 +00001752 <span class="external"></span>x = 'name: %s; score: %d' % (name, n)</PRE></DIV>
apicard@google.com424ad342012-09-18 23:16:02 +00001753<DIV class=""><PRE class="badcode">No: <span class="external"></span>x = '%s%s' % (a, b) # use + in this case
1754 <span class="external"></span>x = imperative + ', ' + expletive + '!'
1755 <span class="external"></span>x = 'name: ' + name + '; score: ' + str(n)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001756
1757 <p>
1758 Avoid using the <code>+</code> and <code>+=</code> operators to
1759 accumulate a string within a loop. Since strings are immutable, this
1760 creates unnecessary temporary objects and results in quadratic rather
1761 than linear running time. Instead, add each substring to a list and
1762 <code>''.join</code> the list after the loop terminates (or, write each
1763 substring to a <code>cStringIO.StringIO</code> buffer).
1764 </p>
1765
mmentovai9ec7bd62009-12-03 22:25:38 +00001766<DIV class=""><PRE>Yes: <span class="external"></span>items = ['&lt;table&gt;']
apicard@google.comf900c2c2009-07-23 20:09:56 +00001767 <span class="external"></span>for last_name, first_name in employee_list:
1768 <span class="external"> </span>items.append('&lt;tr&gt;&lt;td&gt;%s, %s&lt;/td&gt;&lt;/tr&gt;' % (last_name, first_name))
1769 <span class="external"></span>items.append('&lt;/table&gt;')
mmentovai9ec7bd62009-12-03 22:25:38 +00001770 <span class="external"></span>employee_table = ''.join(items)</PRE></DIV>
apicard@google.com424ad342012-09-18 23:16:02 +00001771<DIV class=""><PRE class="badcode">No: <span class="external"></span>employee_table = '&lt;table&gt;'
1772 <span class="external"></span>for last_name, first_name in employee_list:
1773 <span class="external"> </span>employee_table += '&lt;tr&gt;&lt;td&gt;%s, %s&lt;/td&gt;&lt;/tr&gt;' % (last_name, first_name)
1774 <span class="external"></span>employee_table += '&lt;/table&gt;'</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001775
1776 <p>
1777 Use <code>"""</code> for multi-line strings rather than
1778 <code>'''</code>. Note, however, that it is often cleaner to
1779 use implicit line joining since multi-line strings do
1780 not flow with the indentation of the rest of the program:
1781 </p>
1782
apicard@google.com424ad342012-09-18 23:16:02 +00001783<DIV class=""><PRE>Ye<span class="external"></span>s:
1784 <span class="external"></span>print ("This is much nicer.\n"
1785 <span class="external"></span> "Do it this way.\n")</PRE></DIV>
1786<DIV class=""><PRE class="badcode"> No<span class="external"></span>:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001787 <span class="external"></span>print """This is pretty ugly.
1788Don'<span class="external"></span>t do this.
1789"""<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001790</PRE></DIV>
apicard@google.com424ad342012-09-18 23:16:02 +00001791
1792 </DIV></DIV>
1793 </DIV>
1794 <DIV class="">
1795<H3><A name="Files_and_Sockets" id="Files_and_Sockets">Files and Sockets</A></H3>
1796<SPAN class="link_button" id="link-Files_and_Sockets__button" name="link-Files_and_Sockets__button"><A href="?showone=Files_and_Sockets#Files_and_Sockets">
1797 link
1798 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Files_and_Sockets')" name="Files_and_Sockets__button" id="Files_and_Sockets__button"></SPAN>
1799 <DIV style="display:inline;" class="">
1800 Explicitly close files and sockets when done with them.
1801 </DIV>
1802 <DIV class=""><DIV class="stylepoint_body" name="Files_and_Sockets__body" id="Files_and_Sockets__body" style="display: none">
1803 <p>
1804 Leaving files, sockets or other file-like objects open unnecessarily
1805 has many downsides, including:
1806
1807 <ul>
1808 <li>They may consume limited system resources, such as file
1809 descriptors. Code that deals with many such objects may exhaust
1810 those resources unnecessarily if they're not returned to the
1811 system promptly after use.</li>
1812 <li>Holding files open may prevent other actions being performed on
1813 them, such as moves or deletion.</li>
1814 <li>Files and sockets that are shared throughout a program may
1815 inadvertantly be read from or written to after logically being
1816 closed. If they are actually closed, attempts to read or write
1817 from them will throw exceptions, making the problem known
1818 sooner.</li>
1819 </ul>
1820 </p>
1821
1822 <p>
1823 Furthermore, while files and sockets are automatically closed when the
1824 file object is destructed, tying the life-time of the file object to
1825 the state of the file is poor practice, for several reasons:
1826
1827 <ul>
1828 <li>There are no guarantees as to when the runtime will actually run
1829 the file's destructor. Different Python implementations use
1830 different memory management techniques, such as delayed Garbage
1831 Collection, which may increase the object's lifetime arbitrarily
1832 and indefinitely.</li>
1833 <li>Unexpected references to the file may keep it around longer than
1834 intended (e.g. in tracebacks of exceptions, inside globals,
1835 etc).</li>
1836 </ul>
1837 </p>
1838
1839 <p>
1840 The preferred way to manage files is using the <a HREF="http://docs.python.org/reference/compound_stmts.html#the-with-statement">
1841 "with" statement</a>:
1842 </p>
1843
1844<DIV class=""><PRE>
1845<span class="external"></span>with open("hello.txt") as hello_file:
1846 <span class="external"> </span>for line in hello_file:
1847 <span class="external"> </span>print line</PRE></DIV>
1848
1849 <p>
1850 For file-like objects that do not support the "with" statement, use
1851 contextlib.closing():
1852 </p>
1853
1854<DIV class=""><PRE>
1855<span class="external"></span>import contextlib
1856
1857<span class="external"></span>with contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page:
1858 <span class="external"> </span>for line in front_page:
1859 <span class="external"> </span>print line</PRE></DIV>
1860
1861 <p>
1862 Legacy AppEngine code using Python 2.5 may enable the "with" statement
1863 using "from __future__ import with_statement".
1864 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001865 </DIV></DIV>
1866 </DIV>
1867 <DIV class="">
1868<H3><A name="TODO_Comments" id="TODO_Comments">TODO Comments</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001869<SPAN class="link_button" id="link-TODO_Comments__button" name="link-TODO_Comments__button"><A href="?showone=TODO_Comments#TODO_Comments">
1870 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001871 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('TODO_Comments')" name="TODO_Comments__button" id="TODO_Comments__button"></SPAN>
1872 <DIV style="display:inline;" class="">
1873 Use <code>TODO</code> comments for code that is temporary, a
1874 short-term solution, or good-enough but not perfect.
1875 </DIV>
1876 <DIV class=""><DIV class="stylepoint_body" name="TODO_Comments__body" id="TODO_Comments__body" style="display: none">
1877 <p>
1878 <code>TODO</code>s should include the string <code>TODO</code> in
1879 all caps, followed by the
1880
1881 name, e-mail address, or other
1882 identifier
1883 of the person who can best provide context about the problem
1884 referenced by the <code>TODO</code>,
1885 in parentheses. A colon is optional. A comment explaining what there
1886 is to do is required. The main purpose is to have
1887 a consistent <code>TODO</code> format that can be searched to find the
1888 person who can provide more details upon request. A
1889 <code>TODO</code> is not a commitment that the person referenced
1890 will fix the problem. Thus when you create a <code>TODO</code>, it is
1891 almost always your
1892
1893 name
1894 that is given.
1895 </p>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001896
mark@chromium.orge33361f2011-11-04 16:55:22 +00001897 <DIV class=""><PRE># TODO(kl@gmail.com): Use a "*" here for string repetition.
1898# TODO(Zeke) Change this to use relations.</PRE></DIV>
1899 <p>
1900 If your <code>TODO</code> is of the form "At a future date do
1901 something" make sure that you either include a very specific
1902 date ("Fix by November 2009") or a very specific event
1903 ("Remove this code when all clients can handle XML responses.").
1904 </p>
1905 </DIV></DIV>
1906 </DIV>
mmentovai9ec7bd62009-12-03 22:25:38 +00001907 <DIV class="">
1908<H3><A name="Imports_formatting" id="Imports_formatting">Imports formatting</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001909<SPAN class="link_button" id="link-Imports_formatting__button" name="link-Imports_formatting__button"><A href="?showone=Imports_formatting#Imports_formatting">
1910 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001911 </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 +00001912 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001913 Imports should be on separate lines.
mmentovai9ec7bd62009-12-03 22:25:38 +00001914 </DIV>
1915 <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 +00001916 <p>
1917 E.g.:
1918 </p>
1919
mmentovai9ec7bd62009-12-03 22:25:38 +00001920<DIV class=""><PRE>Yes: <span class="external"></span>import os
1921 <span class="external"></span>import sys</PRE></DIV>
1922<DIV class=""><PRE class="badcode">No: <span class="external"></span>import os, sys</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001923 <p>
1924 Imports are always put at the top of the file, just after any
1925 module comments and doc strings and before module globals and
1926 constants. Imports should be grouped with the order being most generic
1927 to least generic:
1928 </p>
1929 <ul>
1930 <li>standard library imports</li>
1931 <li>third-party imports</li>
1932
1933 <li>application-specific imports</li>
1934 </ul>
1935 <p>
1936 Within each grouping, imports should be sorted lexicographically,
1937 ignoring case, according to each module's full package path.
1938 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001939 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001940<span class="external"></span>import foo
1941<span class="external"></span>from foo import bar
1942<span class="external"></span>from foo.bar import baz
1943<span class="external"></span>from foo.bar import Quux
mmentovai9ec7bd62009-12-03 22:25:38 +00001944<span class="external"></span>from Foob import ar</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001945
1946
mmentovai9ec7bd62009-12-03 22:25:38 +00001947
1948 </DIV></DIV>
1949 </DIV>
1950 <DIV class="">
1951<H3><A name="Statements" id="Statements">Statements</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001952<SPAN class="link_button" id="link-Statements__button" name="link-Statements__button"><A href="?showone=Statements#Statements">
1953 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001954 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Statements')" name="Statements__button" id="Statements__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001955 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001956 Generally only one statement per line.
mmentovai9ec7bd62009-12-03 22:25:38 +00001957 </DIV>
1958 <DIV class=""><DIV class="stylepoint_body" name="Statements__body" id="Statements__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001959 <p>
1960 However, you may put the
1961 result of a test on the same line as the test only if the entire
1962 statement fits on one line. In particular, you can never do so
1963 with <code>try</code>/<code>except</code> since the
1964 <code>try</code> and <code>except</code> can't both fit on the
1965 same line, and you can only do so with an <code>if</code> if
1966 there is no <code>else</code>.
1967 </p>
1968
mmentovai9ec7bd62009-12-03 22:25:38 +00001969 <DIV class=""><PRE>Ye<span class="external"></span>s:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001970
mmentovai9ec7bd62009-12-03 22:25:38 +00001971 <span class="external"></span>if foo: bar(foo)</PRE></DIV>
1972<DIV class=""><PRE class="badcode">No<span class="external"></span>:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001973
1974 <span class="external"></span>if foo: bar(foo)
1975 <span class="external"></span>else: baz(foo)
1976
1977 <span class="external"></span>try: bar(foo)
1978 <span class="external"></span>except ValueError: baz(foo)
1979
1980 <span class="external"></span>try:
1981 <span class="external"> </span>bar(foo)
1982 <span class="external"></span>except ValueError: baz(foo)
1983<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001984</PRE></DIV>
1985 </DIV></DIV>
1986 </DIV>
1987 <DIV class="">
1988<H3><A name="Access_Control" id="Access_Control">Access Control</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001989<SPAN class="link_button" id="link-Access_Control__button" name="link-Access_Control__button"><A href="?showone=Access_Control#Access_Control">
1990 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001991 </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 +00001992 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001993 If an accessor function would be trivial you should use public variables
apicard@google.com424ad342012-09-18 23:16:02 +00001994 instead of accessor functions to avoid the extra cost of function
1995 calls in Python. When more functionality is added you can use
apicard@google.comf900c2c2009-07-23 20:09:56 +00001996 <code>property</code> to keep the syntax consistent.
mmentovai9ec7bd62009-12-03 22:25:38 +00001997 </DIV>
1998 <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 +00001999 <p>
2000 On the other hand, if access is more complex, or the cost of accessing
2001 the variable is significant, you should use function calls (following the
2002 <a HREF="#naming">Naming</a> guidelines) such as <code>get_foo()</code>
2003 and <code>set_foo()</code>. If the past behavior allowed access through a
2004 property, do not bind the new accessor functions to the property. Any
2005 code still attempting to access the variable by the old method should
2006 break visibly so they are made aware of the change in complexity.
2007 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00002008 </DIV></DIV>
2009 </DIV>
2010 <DIV class="">
2011<H3><A name="Naming" id="Naming">Naming</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00002012<SPAN class="link_button" id="link-Naming__button" name="link-Naming__button"><A href="?showone=Naming#Naming">
2013 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00002014 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Naming')" name="Naming__button" id="Naming__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00002015 <DIV style="display:inline;" class="">
mark@chromium.orge33361f2011-11-04 16:55:22 +00002016 <code>module_name, package_name, ClassName,
2017 method_name, ExceptionName,
2018 function_name, GLOBAL_CONSTANT_NAME,
2019 global_var_name, instance_var_name, function_parameter_name,
2020 local_var_name.</code>
mmentovai9ec7bd62009-12-03 22:25:38 +00002021 </DIV>
2022 <DIV class=""><DIV class="stylepoint_body" name="Naming__body" id="Naming__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00002023 <P class="">
2024<SPAN class="stylepoint_subsection">Names to Avoid</SPAN>
2025
2026 <ul>
2027 <li>single character names except for counters or iterators</li>
2028 <li>dashes (<code>-</code>) in any package/module name</li>
2029 <li>
apicard@google.com424ad342012-09-18 23:16:02 +00002030<code>__double_leading_and_trailing_underscore__</code> names
apicard@google.comf900c2c2009-07-23 20:09:56 +00002031 (reserved by Python)</li>
2032 </ul>
2033
2034 </P>
2035 <P class="">
2036<SPAN class="stylepoint_subsection">Naming Convention</SPAN>
2037
2038 <ul>
2039 <li>
2040 "Internal" means internal to a module or protected
2041 or private within a class.</li>
2042 <li>
2043 Prepending a single underscore (<code>_</code>) has some
2044 support for protecting module variables and functions (not included
2045 with <code>import * from</code>). Prepending a double underscore
2046 (<code>__</code>) to an instance variable or method
2047 effectively serves to make the variable or method private to its class
2048 (using name mangling).</li>
2049 <li>
apicard@google.com424ad342012-09-18 23:16:02 +00002050 Place related classes and top-level functions together in a
apicard@google.comf900c2c2009-07-23 20:09:56 +00002051 module. Unlike Java,
2052 there is no need to limit yourself to one class per module.</li>
2053 <li>
2054 Use CapWords for class names, but lower_with_under.py for module names.
2055 Although there are many existing modules named CapWords.py, this is now
apicard@google.com424ad342012-09-18 23:16:02 +00002056 discouraged because it's confusing when the module happens to be
2057 named after a class. ("wait -- did I write
apicard@google.comf900c2c2009-07-23 20:09:56 +00002058 <code>import StringIO</code> or <code>from StringIO import
2059 StringIO</code>?")</li>
2060 </ul>
2061
2062 </P>
2063 <P class="">
2064<SPAN class="stylepoint_subsection">Guidelines derived from Guido's Recommendations</SPAN>
2065
2066 <table rules="all" border="1" cellspacing="2" cellpadding="2">
2067
2068 <tr>
2069 <th>Type</th>
2070 <th>Public</th>
2071 <th>Internal</th>
2072 </tr>
2073
2074
2075
2076 <tr>
2077 <td>Packages</td>
2078 <td><code>lower_with_under</code></td>
2079 <td></td>
2080 </tr>
2081
2082 <tr>
2083 <td>Modules</td>
2084 <td><code>lower_with_under</code></td>
2085 <td><code>_lower_with_under</code></td>
2086 </tr>
2087
2088 <tr>
2089 <td>Classes</td>
2090 <td><code>CapWords</code></td>
2091 <td><code>_CapWords</code></td>
2092 </tr>
2093
2094 <tr>
2095 <td>Exceptions</td>
2096 <td><code>CapWords</code></td>
2097 <td></td>
2098 </tr>
2099
2100
2101
2102 <tr>
2103 <td>Functions</td>
2104 <td><code>lower_with_under()</code></td>
2105 <td><code>_lower_with_under()</code></td>
2106 </tr>
2107
2108 <tr>
2109 <td>Global/Class Constants</td>
2110 <td><code>CAPS_WITH_UNDER</code></td>
2111 <td><code>_CAPS_WITH_UNDER</code></td>
2112 </tr>
2113
2114 <tr>
2115 <td>Global/Class Variables</td>
2116 <td><code>lower_with_under</code></td>
2117 <td><code>_lower_with_under</code></td>
2118 </tr>
2119
2120 <tr>
2121 <td>Instance Variables</td>
2122 <td><code>lower_with_under</code></td>
2123 <td><code>_lower_with_under (protected) or __lower_with_under (private)</code></td>
2124 </tr>
2125
2126
2127
2128 <tr>
2129 <td>Method Names</td>
2130 <td><code>lower_with_under()</code></td>
2131 <td><code>_lower_with_under() (protected) or __lower_with_under() (private)</code></td>
2132 </tr>
2133
2134 <tr>
2135 <td>Function/Method Parameters</td>
2136 <td><code>lower_with_under</code></td>
2137 <td></td>
2138 </tr>
2139
2140 <tr>
2141 <td>Local Variables</td>
2142 <td><code>lower_with_under</code></td>
2143 <td></td>
2144 </tr>
2145
2146
2147 </table>
2148
2149
2150 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00002151 </DIV></DIV>
2152 </DIV>
2153 <DIV class="">
2154<H3><A name="Main" id="Main">Main</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00002155<SPAN class="link_button" id="link-Main__button" name="link-Main__button"><A href="?showone=Main#Main">
2156 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00002157 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Main')" name="Main__button" id="Main__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00002158 <DIV style="display:inline;" class="">
apicard@google.com424ad342012-09-18 23:16:02 +00002159 Even a file meant to be used as a script should be importable and a
2160 mere import should not have the side effect of executing the script's
2161 main functionality. The main functionality should be in a main()
apicard@google.comf900c2c2009-07-23 20:09:56 +00002162 function.
mmentovai9ec7bd62009-12-03 22:25:38 +00002163 </DIV>
2164 <DIV class=""><DIV class="stylepoint_body" name="Main__body" id="Main__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00002165 <p>
2166 In Python,
2167 <code>pychecker</code>, <code>pydoc</code>, and unit tests
2168 require modules to be importable. Your code should always check
2169 <code>if __name__ == '__main__'</code> before executing your
2170 main program so that the main program is not executed when the
apicard@google.com424ad342012-09-18 23:16:02 +00002171 module is imported.
apicard@google.comf900c2c2009-07-23 20:09:56 +00002172
2173 </p>
2174
2175
2176
2177
2178
2179
2180
mmentovai9ec7bd62009-12-03 22:25:38 +00002181 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002182<span class="external"></span>def main():
2183 <span class="external"> </span>...
2184
2185<span class="external"></span>if __name__ == '__main__':
2186 <span class="external"> </span>main()
2187<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00002188</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002189
2190 <p>
2191 All code at the top level will be executed when the module is
2192 imported. Be careful not to call functions, create objects, or
2193 perform other operations that should not be executed when the
2194 file is being <code>pycheck</code>ed or <code>pydoc</code>ed.
2195 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00002196 </DIV></DIV>
2197 </DIV>
2198 </DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002199
2200<H2>Parting Words</H2>
2201 <p>
2202 <em>BE CONSISTENT</em>.
2203 </p>
2204
2205 <p>
2206 If you're editing code, take a few minutes to look at the code
2207 around you and determine its style. If they use spaces around
2208 all their arithmetic operators, you should too. If their
2209 comments have little boxes of hash marks around them, make your
2210 comments have little boxes of hash marks around them too.
2211 </p>
2212
2213 <p>
2214 The point of having style guidelines is to have a common vocabulary
2215 of coding so people can concentrate on what you're saying rather
2216 than on how you're saying it. We present global style rules here so
2217 people know the vocabulary, but local style is also important. If
2218 code you add to a file looks drastically different from the existing
2219 code around it, it throws readers out of their rhythm when they go to
2220 read it. Avoid this.
2221 </p>
2222
2223
2224
2225<p align="right">
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00002226Revision 2.45
apicard@google.comf900c2c2009-07-23 20:09:56 +00002227</p>
2228
2229
2230<address>
2231 Amit Patel<br>
2232 Antoine Picard<br>
2233 Eugene Jhong<br>
2234 Jeremy Hylton<br>
2235 Matt Smart<br>
2236 Mike Shields<br>
2237</address>
2238</BODY>
2239</HTML>