blob: 7213d7a01cd877bf47cc3fc5609780bb7e8a7d57 [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.org8190c132013-03-21 16:03:26 +0000139 Revision 2.48
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>
mark@chromium.org8190c132013-03-21 16:03:26 +00001249 Exceptions:
1250 <ul>
1251 <li>Long import statements.</li>
1252 <li>URLs in comments.</li>
1253 </ul>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001254 </p>
1255
1256 <p>
mark@chromium.orge33361f2011-11-04 16:55:22 +00001257 Do not use backslash line continuation.
1258 </p>
1259
1260 <p>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001261 Make use of Python's
1262
mark@chromium.org8190c132013-03-21 16:03:26 +00001263 <a HREF="http://docs.python.org/reference/lexical_analysis.html#implicit-line-joining">implicit
apicard@google.comf900c2c2009-07-23 20:09:56 +00001264 line joining inside parentheses, brackets and braces</a>.
1265 If necessary, you can add an extra pair of parentheses around an
1266 expression.
1267 </p>
1268
1269
mmentovai9ec7bd62009-12-03 22:25:38 +00001270 <DIV class=""><PRE>Yes: foo_bar(self, width, height, color='black', design=None, x='foo',
apicard@google.comf900c2c2009-07-23 20:09:56 +00001271 emphasis=None, highlight=0)
1272
1273 if (width == 0 and height == 0 and
mmentovai9ec7bd62009-12-03 22:25:38 +00001274 color == 'red' and emphasis == 'strong'):</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001275
1276
1277 <p>
1278 When a literal string won't fit on a single line, use parentheses for
1279 implicit line joining.
1280 </p>
1281
mmentovai9ec7bd62009-12-03 22:25:38 +00001282 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001283<span class="external"></span>x = ('This will build a very long long '
mmentovai9ec7bd62009-12-03 22:25:38 +00001284<span class="external"></span> 'long long long long long long string')</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001285
1286 <p>
mark@chromium.org8190c132013-03-21 16:03:26 +00001287 Within comments, put long URLs on their own line if necessary.
1288 </p>
1289
1290 <DIV class=""><PRE>Yes: <span class="external"></span># See details at
1291 <span class="external"></span># http://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.html</PRE></DIV>
1292
1293 <DIV class=""><PRE class="badcode">No: <span class="external"></span># See details at
1294 <span class="external"></span># http://www.example.com/us/developer/documentation/api/content/\
1295 <span class="external"></span># v2.0/csv_file_name_extension_full_specification.html</PRE></DIV>
1296
1297 <p>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001298 Make note of the indentation of the elements in the line
apicard@google.com424ad342012-09-18 23:16:02 +00001299 continuation examples above; see the
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001300 <a HREF="#Indentation">indentation</a>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001301 section for explanation.
1302 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001303 </DIV></DIV>
1304 </DIV>
1305 <DIV class="">
1306<H3><A name="Parentheses" id="Parentheses">Parentheses</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001307<SPAN class="link_button" id="link-Parentheses__button" name="link-Parentheses__button"><A href="?showone=Parentheses#Parentheses">
1308 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001309 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Parentheses')" name="Parentheses__button" id="Parentheses__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001310 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001311 Use parentheses sparingly.
mmentovai9ec7bd62009-12-03 22:25:38 +00001312 </DIV>
1313 <DIV class=""><DIV class="stylepoint_body" name="Parentheses__body" id="Parentheses__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001314 <p>
apicard@google.com424ad342012-09-18 23:16:02 +00001315 Do not use them in return statements or conditional statements unless
1316 using parentheses for implied line continuation. (See above.)
apicard@google.comf900c2c2009-07-23 20:09:56 +00001317 It is however fine to use parentheses around tuples.
1318 </p>
1319
mmentovai9ec7bd62009-12-03 22:25:38 +00001320<DIV class=""><PRE>Yes: <span class="external"></span>if foo:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001321 <span class="external"> </span>bar()
1322 <span class="external"></span>while x:
1323 <span class="external"> </span>x = bar()
1324 <span class="external"></span>if x and y:
1325 <span class="external"> </span>bar()
1326 <span class="external"></span>if not x:
1327 <span class="external"> </span>bar()
1328 <span class="external"></span>return foo
mmentovai9ec7bd62009-12-03 22:25:38 +00001329 <span class="external"></span>for (x, y) in dict.items(): ...</PRE></DIV>
1330<DIV class=""><PRE class="badcode">No: <span class="external"></span>if (x):
apicard@google.comf900c2c2009-07-23 20:09:56 +00001331 <span class="external"> </span>bar()
1332 <span class="external"></span>if not(x):
1333 <span class="external"> </span>bar()
mmentovai9ec7bd62009-12-03 22:25:38 +00001334 <span class="external"></span>return (foo)</PRE></DIV>
1335 </DIV></DIV>
1336 </DIV>
1337 <DIV class="">
1338<H3><A name="Indentation" id="Indentation">Indentation</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001339<SPAN class="link_button" id="link-Indentation__button" name="link-Indentation__button"><A href="?showone=Indentation#Indentation">
1340 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001341 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Indentation')" name="Indentation__button" id="Indentation__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001342 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001343 Indent your code blocks with <em>4 spaces</em>.
mmentovai9ec7bd62009-12-03 22:25:38 +00001344 </DIV>
1345 <DIV class=""><DIV class="stylepoint_body" name="Indentation__body" id="Indentation__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001346 <p>
1347 Never use tabs or mix tabs and spaces.
1348 In cases of implied line continuation, you should align wrapped elements
1349 either vertically, as per the examples in the
1350 <a HREF="#Line_length">line length</a> section; or using a hanging
1351 indent of 4 spaces, in which case there should be no argument on
1352 the first line.
1353 </p>
1354
1355
mmentovai9ec7bd62009-12-03 22:25:38 +00001356<DIV class=""><PRE>Yes: # Aligned with opening delimiter
apicard@google.comf900c2c2009-07-23 20:09:56 +00001357 foo = long_function_name(var_one, var_two,
1358 var_three, var_four)
1359
1360 # 4-space hanging indent; nothing on first line
1361 foo = long_function_name(
1362 var_one, var_two, var_three,
mmentovai9ec7bd62009-12-03 22:25:38 +00001363 var_four)</PRE></DIV>
1364<DIV class=""><PRE class="badcode">No: <span class="external"></span># Stuff on first line forbidden
apicard@google.comf900c2c2009-07-23 20:09:56 +00001365 <span class="external"></span>foo = long_function_name(var_one, var_two,
1366 <span class="external"></span> var_three, var_four)
1367
1368 <span class="external"></span># 2-space hanging indent forbidden
1369 <span class="external"></span>foo = long_function_name(
1370 <span class="external"></span> var_one, var_two, var_three,
mmentovai9ec7bd62009-12-03 22:25:38 +00001371 <span class="external"></span> var_four)</PRE></DIV>
1372 </DIV></DIV>
1373 </DIV>
1374 <DIV class="">
1375<H3><A name="Blank_Lines" id="Blank_Lines">Blank Lines</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001376<SPAN class="link_button" id="link-Blank_Lines__button" name="link-Blank_Lines__button"><A href="?showone=Blank_Lines#Blank_Lines">
1377 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001378 </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 +00001379 <DIV style="display:inline;" class="">
apicard@google.com424ad342012-09-18 23:16:02 +00001380 Two blank lines between top-level definitions, one blank line
apicard@google.comf900c2c2009-07-23 20:09:56 +00001381 between method definitions.
mmentovai9ec7bd62009-12-03 22:25:38 +00001382 </DIV>
1383 <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 +00001384 <p>
1385 Two blank lines between top-level definitions, be they function
1386 or class definitions. One blank line between method definitions
1387 and between the <code>class</code> line and the first method.
1388 Use single blank lines as you judge appropriate within functions or
1389 methods.
1390 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001391 </DIV></DIV>
1392 </DIV>
1393 <DIV class="">
1394<H3><A name="Whitespace" id="Whitespace">Whitespace</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001395<SPAN class="link_button" id="link-Whitespace__button" name="link-Whitespace__button"><A href="?showone=Whitespace#Whitespace">
1396 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001397 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Whitespace')" name="Whitespace__button" id="Whitespace__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001398 <DIV style="display:inline;" class="">
apicard@google.com424ad342012-09-18 23:16:02 +00001399 Follow standard typographic rules for the use of spaces around
apicard@google.comf900c2c2009-07-23 20:09:56 +00001400 punctuation.
mmentovai9ec7bd62009-12-03 22:25:38 +00001401 </DIV>
1402 <DIV class=""><DIV class="stylepoint_body" name="Whitespace__body" id="Whitespace__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001403 <p>
1404 No whitespace inside parentheses, brackets or braces.
1405 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001406<DIV class=""><PRE>Yes: <span class="external"></span>spam(ham[1], {eggs: 2}, [])</PRE></DIV>
1407<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 +00001408 <p>
1409 No whitespace before a comma, semicolon, or colon. Do use
1410 whitespace after a comma, semicolon, or colon except at the end
1411 of the line.
1412 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001413<DIV class=""><PRE>Yes: <span class="external"></span>if x == 4:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001414 <span class="external"> </span>print x, y
mmentovai9ec7bd62009-12-03 22:25:38 +00001415 <span class="external"></span>x, y = y, x</PRE></DIV>
1416<DIV class=""><PRE class="badcode">No: <span class="external"></span>if x == 4 :
apicard@google.comf900c2c2009-07-23 20:09:56 +00001417 <span class="external"> </span>print x , y
mmentovai9ec7bd62009-12-03 22:25:38 +00001418 <span class="external"></span>x , y = y , x</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001419 <p>
1420 No whitespace before the open paren/bracket that starts an argument list,
1421 indexing or slicing.
1422 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001423 <DIV class=""><PRE>Yes: <span class="external"></span>spam(1)</PRE></DIV>
1424<DIV class=""><PRE class="badcode">No: <span class="external"></span>spam (1)</PRE></DIV>
1425<DIV class=""><PRE>Yes: <span class="external"></span>dict['key'] = list[index]</PRE></DIV>
1426<DIV class=""><PRE class="badcode">No: <span class="external"></span>dict ['key'] = list [index]</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001427
1428 <p>
1429 Surround binary operators with a single space on either side for
1430 assignment (<code>=</code>), comparisons (<code>==, &lt;, &gt;, !=,
1431 &lt;&gt;, &lt;=, &gt;=, in, not in, is, is not</code>), and Booleans
1432 (<code>and, or, not</code>). Use your better judgment for the
1433 insertion of spaces around arithmetic operators but always be
1434 consistent about whitespace on either side of a binary operator.
1435 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001436<DIV class=""><PRE>Yes: <span class="external"></span>x == 1</PRE></DIV>
1437<DIV class=""><PRE class="badcode">No: <span class="external"></span>x&lt;1</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001438 <p>
1439 Don't use spaces around the '=' sign when used to indicate a
1440 keyword argument or a default parameter value.
1441 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001442<DIV class=""><PRE>Yes: <span class="external"></span>def complex(real, imag=0.0): return magic(r=real, i=imag)</PRE></DIV>
1443<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 +00001444
1445 <p>
1446 Don't use spaces to vertically align tokens on consecutive lines, since it
1447 becomes a maintenance burden (applies to <code>:</code>, <code>#</code>,
1448 <code>=</code>, etc.):
1449 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001450<DIV class=""><PRE>Yes:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001451 foo = 1000 # comment
1452 long_name = 2 # comment that should not be aligned
1453
1454 dictionary = {
apicard@google.com424ad342012-09-18 23:16:02 +00001455 'foo': 1,
1456 'long_name': 2,
mmentovai9ec7bd62009-12-03 22:25:38 +00001457 }</PRE></DIV>
1458<DIV class=""><PRE class="badcode">No:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001459 foo = 1000 # comment
1460 long_name = 2 # comment that should not be aligned
1461
1462 dictionary = {
apicard@google.com424ad342012-09-18 23:16:02 +00001463 'foo' : 1,
1464 'long_name': 2,
mmentovai9ec7bd62009-12-03 22:25:38 +00001465 }</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001466
1467
mmentovai9ec7bd62009-12-03 22:25:38 +00001468 </DIV></DIV>
1469 </DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001470
mmentovaicd4ce0f2011-03-29 20:30:47 +00001471 <a name="Python_Interpreter"></a>
1472 <DIV class="">
1473<H3><A name="Shebang_Line" id="Shebang_Line">Shebang Line</A></H3>
1474<SPAN class="link_button" id="link-Shebang_Line__button" name="link-Shebang_Line__button"><A href="?showone=Shebang_Line#Shebang_Line">
1475 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001476 </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 +00001477 <DIV style="display:inline;" class="">
mark@chromium.orge33361f2011-11-04 16:55:22 +00001478 Most <code>.py</code> files do not need to start with a
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001479 <code>#!</code> line. Start the main file of a program with
mark@chromium.orge33361f2011-11-04 16:55:22 +00001480 <code>#!/usr/bin/python</code>.
mmentovaicd4ce0f2011-03-29 20:30:47 +00001481 </DIV>
1482 <DIV class=""><DIV class="stylepoint_body" name="Shebang_Line__body" id="Shebang_Line__body" style="display: none">
1483
1484 <p>
mark@chromium.orge33361f2011-11-04 16:55:22 +00001485 This line is used by the kernel to find the Python interpreter, but is
1486 ignored by Python when importing modules. It is only necessary on a
1487 file that will be executed directly.
mmentovaicd4ce0f2011-03-29 20:30:47 +00001488 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001489 </DIV></DIV>
1490 </DIV>
mmentovaicd4ce0f2011-03-29 20:30:47 +00001491
mmentovai9ec7bd62009-12-03 22:25:38 +00001492 <DIV class="">
1493<H3><A name="Comments" id="Comments">Comments</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001494<SPAN class="link_button" id="link-Comments__button" name="link-Comments__button"><A href="?showone=Comments#Comments">
1495 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001496 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Comments')" name="Comments__button" id="Comments__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001497 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001498 Be sure to use the right style for module, function, method and in-line
1499 comments.
mmentovai9ec7bd62009-12-03 22:25:38 +00001500 </DIV>
1501 <DIV class=""><DIV class="stylepoint_body" name="Comments__body" id="Comments__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001502
1503 <P class="">
1504<SPAN class="stylepoint_subsection">Doc Strings</SPAN>
1505
1506 <p>
1507 Python has a unique commenting style using doc strings. A doc
1508 string is a string that is the first statement in a package,
1509 module, class or function. These strings can be extracted
1510 automatically through the <code>__doc__</code> member of the
1511 object and are used by <code>pydoc</code>. (Try running
1512 <code>pydoc</code> on your module to see how it looks.) Our
1513 convention for doc strings is to use the three double-quote
1514 format for strings. A doc string should be organized as a
1515 summary line (one physical line) terminated by a period,
1516 question mark, or exclamation point, followed by a blank line,
1517 followed by the rest of the doc string starting at the same
1518 cursor position as the first quote of the first line. There are
1519 more formatting guidelines for doc strings below.
1520 </p>
1521
1522 </P>
1523 <P class="">
1524<SPAN class="stylepoint_subsection">Modules</SPAN>
1525
1526
1527
1528 <p>
apicard@google.com424ad342012-09-18 23:16:02 +00001529 Every file should contain license boilerplate.
1530 Choose the appropriate boilerplate for the license used by the project
1531 (for example, Apache 2.0, BSD, LGPL, GPL)
apicard@google.comf900c2c2009-07-23 20:09:56 +00001532 </p>
1533 </P>
1534 <P class="">
1535<SPAN class="stylepoint_subsection">Functions and Methods</SPAN>
1536
1537 <p>
mark@chromium.orge33361f2011-11-04 16:55:22 +00001538 As used in this section "function" applies to methods, function, and
1539 generators.
apicard@google.comf900c2c2009-07-23 20:09:56 +00001540 </p>
1541
mark@chromium.orge33361f2011-11-04 16:55:22 +00001542 <p>
1543 A function must have a docstring, unless it meets all of the following
1544 criteria:
1545 <ul>
1546 <li>not externally visible</li>
1547 <li>very short</li>
1548 <li>obvious</li>
1549 </ul>
1550 </p>
1551
1552 <p>
1553 A docstring should give enough information to write a call to the function
1554 without reading the function's code. A docstring should describe the
1555 function's calling syntax and its semantics, not its implementation. For
1556 tricky code, comments alongside the code are more appropriate than using
1557 docstrings.
1558 </p>
1559
1560 <p>
1561 Certain aspects of a function should be documented in special sections,
1562 listed below. Each section begins with a heading line, which ends with a
1563 colon. Sections should be indented two spaces, except for the heading.
1564 </p>
1565
1566 <dl>
1567 <dt>Args:</dt>
1568 <dd>
1569 List each parameter by name. A description should follow the name, and
1570 be separated by a colon and a space. If the description is too long to
1571 fit on a single 80-character line, use a hanging indent of 2 or 4 spaces
1572 (be consistent with the rest of the file).
1573
1574 <p>
1575 The description should mention required type(s) and the meaning of
1576 the argument.
1577 </p>
1578
1579 <p>
1580 If a function accepts *foo (variable length argument lists) and/or
1581 **bar (arbitrary keyword arguments), they should be listed as *foo and
1582 **bar.
1583 </p>
1584 </dd>
1585
1586 <dt>Returns: (or Yields: for generators)</dt>
1587 <dd>
1588 Describe the type and semantics of the return value. If the function
1589 only returns None, this section is not required.
1590 </dd>
1591
1592 <dt>Raises:</dt>
1593 <dd>
1594 List all exceptions that are relevant to the interface.
1595 </dd>
1596 </dl>
1597
mmentovai9ec7bd62009-12-03 22:25:38 +00001598 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001599<span class="external"></span>def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
1600 <span class="external"> </span>"""Fetches rows from a Bigtable.
1601
1602 <span class="external"> </span>Retrieves rows pertaining to the given keys from the Table instance
1603 <span class="external"> </span>represented by big_table. Silly things may happen if
1604 <span class="external"> </span>other_silly_variable is not None.
1605
1606 <span class="external"> </span>Args:
1607 <span class="external"> </span>big_table: An open Bigtable Table instance.
1608 <span class="external"> </span>keys: A sequence of strings representing the key of each table row
1609 <span class="external"> </span> to fetch.
1610 <span class="external"> </span>other_silly_variable: Another optional variable, that has a much
1611 <span class="external"> </span> longer name than the other args, and which does nothing.
1612
1613 <span class="external"> </span>Returns:
1614 <span class="external"> </span>A dict mapping keys to the corresponding table row data
1615 <span class="external"> </span>fetched. Each row is represented as a tuple of strings. For
1616 <span class="external"> </span>example:
1617
1618 <span class="external"> </span>{'Serak': ('Rigel VII', 'Preparer'),
1619 <span class="external"> </span> 'Zim': ('Irk', 'Invader'),
1620 <span class="external"> </span> 'Lrrr': ('Omicron Persei 8', 'Emperor')}
1621
1622 <span class="external"> </span>If a key from the keys argument is missing from the dictionary,
1623 <span class="external"> </span>then that row was not found in the table.
1624
1625 <span class="external"> </span>Raises:
1626 <span class="external"> </span>IOError: An error occurred accessing the bigtable.Table object.
1627 <span class="external"> </span>"""
1628 <span class="external"> </span>pass
1629<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001630</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001631 </P>
1632 <P class="">
1633<SPAN class="stylepoint_subsection">Classes</SPAN>
1634
1635 <p>
1636 Classes should have a doc string below the class definition describing
1637 the class. If your class has public attributes, they should be documented
1638 here in an Attributes section and follow the same formatting as a
1639 function's Args section.
1640 </p>
1641
mmentovai9ec7bd62009-12-03 22:25:38 +00001642 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001643<span class="external"></span>class SampleClass(object):
1644 <span class="external"> </span>"""Summary of class here.
1645
1646 <span class="external"> </span>Longer class information....
1647 <span class="external"> </span>Longer class information....
1648
1649 <span class="external"> </span>Attributes:
1650 <span class="external"> </span>likes_spam: A boolean indicating if we like SPAM or not.
1651 <span class="external"> </span>eggs: An integer count of the eggs we have laid.
1652 <span class="external"> </span>"""
1653
1654 <span class="external"> </span>def __init__(self, likes_spam=False):
1655 <span class="external"> </span>"""Inits SampleClass with blah."""
1656 <span class="external"> </span>self.likes_spam = likes_spam
1657 <span class="external"> </span>self.eggs = 0
1658
1659 <span class="external"> </span>def public_method(self):
1660 <span class="external"> </span>"""Performs operation blah."""
1661<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001662</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001663
1664 </P>
1665 <P class="">
1666<SPAN class="stylepoint_subsection">Block and Inline Comments</SPAN>
1667
1668 <p>
1669 The final place to have comments is in tricky parts of the
apicard@google.com424ad342012-09-18 23:16:02 +00001670 code. If you're going to have to explain it at the next
1671 <a HREF="http://en.wikipedia.org/wiki/Code_review">code review</a>,
1672 you should comment it now. Complicated operations get a few lines of
apicard@google.comf900c2c2009-07-23 20:09:56 +00001673 comments before the operations
1674 commence. Non-obvious ones get comments at the end of the line.
1675 </p>
1676
mmentovai9ec7bd62009-12-03 22:25:38 +00001677 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001678<span class="external"></span># We use a weighted dictionary search to find out where i is in
1679<span class="external"></span># the array. We extrapolate position based on the largest num
1680<span class="external"></span># in the array and the array size and then do binary search to
1681<span class="external"></span># get the exact number.
1682
1683<span class="external"></span>if i &amp; (i-1) == 0: # true iff i is a power of 2
1684<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001685</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001686
1687 <p>
1688 To improve legibility, these comments should be at least 2 spaces away
1689 from the code.
1690 </p>
1691
1692 <p>
1693 On the other hand, never describe the code. Assume the person
1694 reading the code knows Python (though not what you're trying to
1695 do) better than you do.
1696 </p>
1697
mmentovai9ec7bd62009-12-03 22:25:38 +00001698 <DIV class=""><PRE class="badcode">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001699<span class="external"></span># BAD COMMENT: Now go through the b array and make sure whenever i occurs
1700<span class="external"></span># the next element is i+1
1701<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001702</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001703
1704 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001705 </DIV></DIV>
1706 </DIV>
1707 <DIV class="">
1708<H3><A name="Classes" id="Classes">Classes</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001709<SPAN class="link_button" id="link-Classes__button" name="link-Classes__button"><A href="?showone=Classes#Classes">
1710 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001711 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Classes')" name="Classes__button" id="Classes__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001712 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001713 If a class inherits from no other base classes, explicitly inherit
1714 from <code>object</code>. This also applies to nested classes.
mmentovai9ec7bd62009-12-03 22:25:38 +00001715 </DIV>
1716 <DIV class=""><DIV class="stylepoint_body" name="Classes__body" id="Classes__body" style="display: none">
mmentovai9ec7bd62009-12-03 22:25:38 +00001717 <DIV class=""><PRE>Yes: <span class="external"></span>class SampleClass(object):
apicard@google.comf900c2c2009-07-23 20:09:56 +00001718 <span class="external"> </span>pass
1719
1720
1721 <span class="external"></span>class OuterClass(object):
1722
1723 <span class="external"> </span>class InnerClass(object):
1724 <span class="external"> </span>pass
1725
1726
1727 <span class="external"></span>class ChildClass(ParentClass):
1728 <span class="external"> </span>"""Explicitly inherits from another class already."""
1729<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001730</PRE></DIV>
apicard@google.com424ad342012-09-18 23:16:02 +00001731 <DIV class=""><PRE class="badcode">No: <span class="external"></span>class SampleClass:
1732 <span class="external"> </span>pass
apicard@google.comf900c2c2009-07-23 20:09:56 +00001733
apicard@google.com424ad342012-09-18 23:16:02 +00001734
1735 <span class="external"></span>class OuterClass:
1736
1737 <span class="external"> </span>class InnerClass:
1738 <span class="external"> </span>pass
1739<span class="external"></span>
1740</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001741 <p>Inheriting from <code>object</code> is needed to make properties work
apicard@google.com424ad342012-09-18 23:16:02 +00001742 properly, and it will protect your code from one particular potential
apicard@google.comf900c2c2009-07-23 20:09:56 +00001743 incompatibility with Python 3000. It also defines
1744 special methods that implement the default semantics of objects including
1745 <code>__new__</code>, <code>__init__</code>, <code>__delattr__</code>,
1746 <code>__getattribute__</code>, <code>__setattr__</code>,
1747 <code>__hash__</code>, <code>__repr__</code>, and <code>__str__</code>.
1748 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001749 </DIV></DIV>
1750 </DIV>
1751 <DIV class="">
1752<H3><A name="Strings" id="Strings">Strings</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001753<SPAN class="link_button" id="link-Strings__button" name="link-Strings__button"><A href="?showone=Strings#Strings">
1754 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001755 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Strings')" name="Strings__button" id="Strings__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001756 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001757 Use the <code>%</code> operator for formatting strings,
1758 even when the parameters are all strings. Use your best judgement
1759 to decide between <code>+</code> and <code>%</code> though.
mmentovai9ec7bd62009-12-03 22:25:38 +00001760 </DIV>
1761 <DIV class=""><DIV class="stylepoint_body" name="Strings__body" id="Strings__body" style="display: none">
apicard@google.com424ad342012-09-18 23:16:02 +00001762
mmentovai9ec7bd62009-12-03 22:25:38 +00001763<DIV class=""><PRE>Yes: <span class="external"></span>x = a + b
apicard@google.comf900c2c2009-07-23 20:09:56 +00001764 <span class="external"></span>x = '%s, %s!' % (imperative, expletive)
mmentovai9ec7bd62009-12-03 22:25:38 +00001765 <span class="external"></span>x = 'name: %s; score: %d' % (name, n)</PRE></DIV>
apicard@google.com424ad342012-09-18 23:16:02 +00001766<DIV class=""><PRE class="badcode">No: <span class="external"></span>x = '%s%s' % (a, b) # use + in this case
1767 <span class="external"></span>x = imperative + ', ' + expletive + '!'
1768 <span class="external"></span>x = 'name: ' + name + '; score: ' + str(n)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001769
1770 <p>
1771 Avoid using the <code>+</code> and <code>+=</code> operators to
1772 accumulate a string within a loop. Since strings are immutable, this
1773 creates unnecessary temporary objects and results in quadratic rather
1774 than linear running time. Instead, add each substring to a list and
1775 <code>''.join</code> the list after the loop terminates (or, write each
1776 substring to a <code>cStringIO.StringIO</code> buffer).
1777 </p>
1778
mmentovai9ec7bd62009-12-03 22:25:38 +00001779<DIV class=""><PRE>Yes: <span class="external"></span>items = ['&lt;table&gt;']
apicard@google.comf900c2c2009-07-23 20:09:56 +00001780 <span class="external"></span>for last_name, first_name in employee_list:
1781 <span class="external"> </span>items.append('&lt;tr&gt;&lt;td&gt;%s, %s&lt;/td&gt;&lt;/tr&gt;' % (last_name, first_name))
1782 <span class="external"></span>items.append('&lt;/table&gt;')
mmentovai9ec7bd62009-12-03 22:25:38 +00001783 <span class="external"></span>employee_table = ''.join(items)</PRE></DIV>
apicard@google.com424ad342012-09-18 23:16:02 +00001784<DIV class=""><PRE class="badcode">No: <span class="external"></span>employee_table = '&lt;table&gt;'
1785 <span class="external"></span>for last_name, first_name in employee_list:
1786 <span class="external"> </span>employee_table += '&lt;tr&gt;&lt;td&gt;%s, %s&lt;/td&gt;&lt;/tr&gt;' % (last_name, first_name)
1787 <span class="external"></span>employee_table += '&lt;/table&gt;'</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001788
1789 <p>
1790 Use <code>"""</code> for multi-line strings rather than
1791 <code>'''</code>. Note, however, that it is often cleaner to
1792 use implicit line joining since multi-line strings do
1793 not flow with the indentation of the rest of the program:
1794 </p>
1795
apicard@google.com424ad342012-09-18 23:16:02 +00001796<DIV class=""><PRE>Ye<span class="external"></span>s:
1797 <span class="external"></span>print ("This is much nicer.\n"
1798 <span class="external"></span> "Do it this way.\n")</PRE></DIV>
1799<DIV class=""><PRE class="badcode"> No<span class="external"></span>:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001800 <span class="external"></span>print """This is pretty ugly.
1801Don'<span class="external"></span>t do this.
1802"""<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001803</PRE></DIV>
apicard@google.com424ad342012-09-18 23:16:02 +00001804
1805 </DIV></DIV>
1806 </DIV>
1807 <DIV class="">
1808<H3><A name="Files_and_Sockets" id="Files_and_Sockets">Files and Sockets</A></H3>
1809<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">
1810 link
1811 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Files_and_Sockets')" name="Files_and_Sockets__button" id="Files_and_Sockets__button"></SPAN>
1812 <DIV style="display:inline;" class="">
1813 Explicitly close files and sockets when done with them.
1814 </DIV>
1815 <DIV class=""><DIV class="stylepoint_body" name="Files_and_Sockets__body" id="Files_and_Sockets__body" style="display: none">
1816 <p>
1817 Leaving files, sockets or other file-like objects open unnecessarily
1818 has many downsides, including:
1819
1820 <ul>
1821 <li>They may consume limited system resources, such as file
1822 descriptors. Code that deals with many such objects may exhaust
1823 those resources unnecessarily if they're not returned to the
1824 system promptly after use.</li>
1825 <li>Holding files open may prevent other actions being performed on
1826 them, such as moves or deletion.</li>
1827 <li>Files and sockets that are shared throughout a program may
1828 inadvertantly be read from or written to after logically being
1829 closed. If they are actually closed, attempts to read or write
1830 from them will throw exceptions, making the problem known
1831 sooner.</li>
1832 </ul>
1833 </p>
1834
1835 <p>
1836 Furthermore, while files and sockets are automatically closed when the
1837 file object is destructed, tying the life-time of the file object to
1838 the state of the file is poor practice, for several reasons:
1839
1840 <ul>
1841 <li>There are no guarantees as to when the runtime will actually run
1842 the file's destructor. Different Python implementations use
1843 different memory management techniques, such as delayed Garbage
1844 Collection, which may increase the object's lifetime arbitrarily
1845 and indefinitely.</li>
1846 <li>Unexpected references to the file may keep it around longer than
1847 intended (e.g. in tracebacks of exceptions, inside globals,
1848 etc).</li>
1849 </ul>
1850 </p>
1851
1852 <p>
1853 The preferred way to manage files is using the <a HREF="http://docs.python.org/reference/compound_stmts.html#the-with-statement">
1854 "with" statement</a>:
1855 </p>
1856
1857<DIV class=""><PRE>
1858<span class="external"></span>with open("hello.txt") as hello_file:
1859 <span class="external"> </span>for line in hello_file:
1860 <span class="external"> </span>print line</PRE></DIV>
1861
1862 <p>
1863 For file-like objects that do not support the "with" statement, use
1864 contextlib.closing():
1865 </p>
1866
1867<DIV class=""><PRE>
1868<span class="external"></span>import contextlib
1869
1870<span class="external"></span>with contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page:
1871 <span class="external"> </span>for line in front_page:
1872 <span class="external"> </span>print line</PRE></DIV>
1873
1874 <p>
1875 Legacy AppEngine code using Python 2.5 may enable the "with" statement
1876 using "from __future__ import with_statement".
1877 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001878 </DIV></DIV>
1879 </DIV>
1880 <DIV class="">
1881<H3><A name="TODO_Comments" id="TODO_Comments">TODO Comments</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001882<SPAN class="link_button" id="link-TODO_Comments__button" name="link-TODO_Comments__button"><A href="?showone=TODO_Comments#TODO_Comments">
1883 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001884 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('TODO_Comments')" name="TODO_Comments__button" id="TODO_Comments__button"></SPAN>
1885 <DIV style="display:inline;" class="">
1886 Use <code>TODO</code> comments for code that is temporary, a
1887 short-term solution, or good-enough but not perfect.
1888 </DIV>
1889 <DIV class=""><DIV class="stylepoint_body" name="TODO_Comments__body" id="TODO_Comments__body" style="display: none">
1890 <p>
1891 <code>TODO</code>s should include the string <code>TODO</code> in
1892 all caps, followed by the
1893
1894 name, e-mail address, or other
1895 identifier
1896 of the person who can best provide context about the problem
1897 referenced by the <code>TODO</code>,
1898 in parentheses. A colon is optional. A comment explaining what there
1899 is to do is required. The main purpose is to have
1900 a consistent <code>TODO</code> format that can be searched to find the
1901 person who can provide more details upon request. A
1902 <code>TODO</code> is not a commitment that the person referenced
1903 will fix the problem. Thus when you create a <code>TODO</code>, it is
1904 almost always your
1905
1906 name
1907 that is given.
1908 </p>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001909
mark@chromium.orge33361f2011-11-04 16:55:22 +00001910 <DIV class=""><PRE># TODO(kl@gmail.com): Use a "*" here for string repetition.
1911# TODO(Zeke) Change this to use relations.</PRE></DIV>
1912 <p>
1913 If your <code>TODO</code> is of the form "At a future date do
1914 something" make sure that you either include a very specific
1915 date ("Fix by November 2009") or a very specific event
1916 ("Remove this code when all clients can handle XML responses.").
1917 </p>
1918 </DIV></DIV>
1919 </DIV>
mmentovai9ec7bd62009-12-03 22:25:38 +00001920 <DIV class="">
1921<H3><A name="Imports_formatting" id="Imports_formatting">Imports formatting</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001922<SPAN class="link_button" id="link-Imports_formatting__button" name="link-Imports_formatting__button"><A href="?showone=Imports_formatting#Imports_formatting">
1923 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001924 </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 +00001925 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001926 Imports should be on separate lines.
mmentovai9ec7bd62009-12-03 22:25:38 +00001927 </DIV>
1928 <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 +00001929 <p>
1930 E.g.:
1931 </p>
1932
mmentovai9ec7bd62009-12-03 22:25:38 +00001933<DIV class=""><PRE>Yes: <span class="external"></span>import os
1934 <span class="external"></span>import sys</PRE></DIV>
1935<DIV class=""><PRE class="badcode">No: <span class="external"></span>import os, sys</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001936 <p>
1937 Imports are always put at the top of the file, just after any
1938 module comments and doc strings and before module globals and
1939 constants. Imports should be grouped with the order being most generic
1940 to least generic:
1941 </p>
1942 <ul>
1943 <li>standard library imports</li>
1944 <li>third-party imports</li>
1945
1946 <li>application-specific imports</li>
1947 </ul>
1948 <p>
1949 Within each grouping, imports should be sorted lexicographically,
1950 ignoring case, according to each module's full package path.
1951 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001952 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001953<span class="external"></span>import foo
1954<span class="external"></span>from foo import bar
1955<span class="external"></span>from foo.bar import baz
1956<span class="external"></span>from foo.bar import Quux
mmentovai9ec7bd62009-12-03 22:25:38 +00001957<span class="external"></span>from Foob import ar</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001958
1959
mmentovai9ec7bd62009-12-03 22:25:38 +00001960
1961 </DIV></DIV>
1962 </DIV>
1963 <DIV class="">
1964<H3><A name="Statements" id="Statements">Statements</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001965<SPAN class="link_button" id="link-Statements__button" name="link-Statements__button"><A href="?showone=Statements#Statements">
1966 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001967 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Statements')" name="Statements__button" id="Statements__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001968 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001969 Generally only one statement per line.
mmentovai9ec7bd62009-12-03 22:25:38 +00001970 </DIV>
1971 <DIV class=""><DIV class="stylepoint_body" name="Statements__body" id="Statements__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001972 <p>
1973 However, you may put the
1974 result of a test on the same line as the test only if the entire
1975 statement fits on one line. In particular, you can never do so
1976 with <code>try</code>/<code>except</code> since the
1977 <code>try</code> and <code>except</code> can't both fit on the
1978 same line, and you can only do so with an <code>if</code> if
1979 there is no <code>else</code>.
1980 </p>
1981
mmentovai9ec7bd62009-12-03 22:25:38 +00001982 <DIV class=""><PRE>Ye<span class="external"></span>s:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001983
mmentovai9ec7bd62009-12-03 22:25:38 +00001984 <span class="external"></span>if foo: bar(foo)</PRE></DIV>
1985<DIV class=""><PRE class="badcode">No<span class="external"></span>:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001986
1987 <span class="external"></span>if foo: bar(foo)
1988 <span class="external"></span>else: baz(foo)
1989
1990 <span class="external"></span>try: bar(foo)
1991 <span class="external"></span>except ValueError: baz(foo)
1992
1993 <span class="external"></span>try:
1994 <span class="external"> </span>bar(foo)
1995 <span class="external"></span>except ValueError: baz(foo)
1996<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001997</PRE></DIV>
1998 </DIV></DIV>
1999 </DIV>
2000 <DIV class="">
2001<H3><A name="Access_Control" id="Access_Control">Access Control</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00002002<SPAN class="link_button" id="link-Access_Control__button" name="link-Access_Control__button"><A href="?showone=Access_Control#Access_Control">
2003 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00002004 </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 +00002005 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00002006 If an accessor function would be trivial you should use public variables
apicard@google.com424ad342012-09-18 23:16:02 +00002007 instead of accessor functions to avoid the extra cost of function
2008 calls in Python. When more functionality is added you can use
apicard@google.comf900c2c2009-07-23 20:09:56 +00002009 <code>property</code> to keep the syntax consistent.
mmentovai9ec7bd62009-12-03 22:25:38 +00002010 </DIV>
2011 <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 +00002012 <p>
2013 On the other hand, if access is more complex, or the cost of accessing
2014 the variable is significant, you should use function calls (following the
2015 <a HREF="#naming">Naming</a> guidelines) such as <code>get_foo()</code>
2016 and <code>set_foo()</code>. If the past behavior allowed access through a
2017 property, do not bind the new accessor functions to the property. Any
2018 code still attempting to access the variable by the old method should
2019 break visibly so they are made aware of the change in complexity.
2020 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00002021 </DIV></DIV>
2022 </DIV>
2023 <DIV class="">
2024<H3><A name="Naming" id="Naming">Naming</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00002025<SPAN class="link_button" id="link-Naming__button" name="link-Naming__button"><A href="?showone=Naming#Naming">
2026 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00002027 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Naming')" name="Naming__button" id="Naming__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00002028 <DIV style="display:inline;" class="">
mark@chromium.orge33361f2011-11-04 16:55:22 +00002029 <code>module_name, package_name, ClassName,
2030 method_name, ExceptionName,
2031 function_name, GLOBAL_CONSTANT_NAME,
2032 global_var_name, instance_var_name, function_parameter_name,
2033 local_var_name.</code>
mmentovai9ec7bd62009-12-03 22:25:38 +00002034 </DIV>
2035 <DIV class=""><DIV class="stylepoint_body" name="Naming__body" id="Naming__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00002036 <P class="">
2037<SPAN class="stylepoint_subsection">Names to Avoid</SPAN>
2038
2039 <ul>
2040 <li>single character names except for counters or iterators</li>
2041 <li>dashes (<code>-</code>) in any package/module name</li>
2042 <li>
apicard@google.com424ad342012-09-18 23:16:02 +00002043<code>__double_leading_and_trailing_underscore__</code> names
apicard@google.comf900c2c2009-07-23 20:09:56 +00002044 (reserved by Python)</li>
2045 </ul>
2046
2047 </P>
2048 <P class="">
2049<SPAN class="stylepoint_subsection">Naming Convention</SPAN>
2050
2051 <ul>
2052 <li>
2053 "Internal" means internal to a module or protected
2054 or private within a class.</li>
2055 <li>
2056 Prepending a single underscore (<code>_</code>) has some
2057 support for protecting module variables and functions (not included
2058 with <code>import * from</code>). Prepending a double underscore
2059 (<code>__</code>) to an instance variable or method
2060 effectively serves to make the variable or method private to its class
2061 (using name mangling).</li>
2062 <li>
apicard@google.com424ad342012-09-18 23:16:02 +00002063 Place related classes and top-level functions together in a
apicard@google.comf900c2c2009-07-23 20:09:56 +00002064 module. Unlike Java,
2065 there is no need to limit yourself to one class per module.</li>
2066 <li>
2067 Use CapWords for class names, but lower_with_under.py for module names.
2068 Although there are many existing modules named CapWords.py, this is now
apicard@google.com424ad342012-09-18 23:16:02 +00002069 discouraged because it's confusing when the module happens to be
2070 named after a class. ("wait -- did I write
apicard@google.comf900c2c2009-07-23 20:09:56 +00002071 <code>import StringIO</code> or <code>from StringIO import
2072 StringIO</code>?")</li>
2073 </ul>
2074
2075 </P>
2076 <P class="">
2077<SPAN class="stylepoint_subsection">Guidelines derived from Guido's Recommendations</SPAN>
2078
2079 <table rules="all" border="1" cellspacing="2" cellpadding="2">
2080
2081 <tr>
2082 <th>Type</th>
2083 <th>Public</th>
2084 <th>Internal</th>
2085 </tr>
2086
2087
2088
2089 <tr>
2090 <td>Packages</td>
2091 <td><code>lower_with_under</code></td>
2092 <td></td>
2093 </tr>
2094
2095 <tr>
2096 <td>Modules</td>
2097 <td><code>lower_with_under</code></td>
2098 <td><code>_lower_with_under</code></td>
2099 </tr>
2100
2101 <tr>
2102 <td>Classes</td>
2103 <td><code>CapWords</code></td>
2104 <td><code>_CapWords</code></td>
2105 </tr>
2106
2107 <tr>
2108 <td>Exceptions</td>
2109 <td><code>CapWords</code></td>
2110 <td></td>
2111 </tr>
2112
2113
2114
2115 <tr>
2116 <td>Functions</td>
2117 <td><code>lower_with_under()</code></td>
2118 <td><code>_lower_with_under()</code></td>
2119 </tr>
2120
2121 <tr>
2122 <td>Global/Class Constants</td>
2123 <td><code>CAPS_WITH_UNDER</code></td>
2124 <td><code>_CAPS_WITH_UNDER</code></td>
2125 </tr>
2126
2127 <tr>
2128 <td>Global/Class Variables</td>
2129 <td><code>lower_with_under</code></td>
2130 <td><code>_lower_with_under</code></td>
2131 </tr>
2132
2133 <tr>
2134 <td>Instance Variables</td>
2135 <td><code>lower_with_under</code></td>
2136 <td><code>_lower_with_under (protected) or __lower_with_under (private)</code></td>
2137 </tr>
2138
2139
2140
2141 <tr>
2142 <td>Method Names</td>
2143 <td><code>lower_with_under()</code></td>
2144 <td><code>_lower_with_under() (protected) or __lower_with_under() (private)</code></td>
2145 </tr>
2146
2147 <tr>
2148 <td>Function/Method Parameters</td>
2149 <td><code>lower_with_under</code></td>
2150 <td></td>
2151 </tr>
2152
2153 <tr>
2154 <td>Local Variables</td>
2155 <td><code>lower_with_under</code></td>
2156 <td></td>
2157 </tr>
2158
2159
2160 </table>
2161
2162
2163 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00002164 </DIV></DIV>
2165 </DIV>
2166 <DIV class="">
2167<H3><A name="Main" id="Main">Main</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00002168<SPAN class="link_button" id="link-Main__button" name="link-Main__button"><A href="?showone=Main#Main">
2169 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00002170 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Main')" name="Main__button" id="Main__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00002171 <DIV style="display:inline;" class="">
apicard@google.com424ad342012-09-18 23:16:02 +00002172 Even a file meant to be used as a script should be importable and a
2173 mere import should not have the side effect of executing the script's
2174 main functionality. The main functionality should be in a main()
apicard@google.comf900c2c2009-07-23 20:09:56 +00002175 function.
mmentovai9ec7bd62009-12-03 22:25:38 +00002176 </DIV>
2177 <DIV class=""><DIV class="stylepoint_body" name="Main__body" id="Main__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00002178 <p>
2179 In Python,
2180 <code>pychecker</code>, <code>pydoc</code>, and unit tests
2181 require modules to be importable. Your code should always check
2182 <code>if __name__ == '__main__'</code> before executing your
2183 main program so that the main program is not executed when the
apicard@google.com424ad342012-09-18 23:16:02 +00002184 module is imported.
apicard@google.comf900c2c2009-07-23 20:09:56 +00002185
2186 </p>
2187
2188
2189
2190
2191
2192
2193
mmentovai9ec7bd62009-12-03 22:25:38 +00002194 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002195<span class="external"></span>def main():
2196 <span class="external"> </span>...
2197
2198<span class="external"></span>if __name__ == '__main__':
2199 <span class="external"> </span>main()
2200<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00002201</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002202
2203 <p>
2204 All code at the top level will be executed when the module is
2205 imported. Be careful not to call functions, create objects, or
2206 perform other operations that should not be executed when the
2207 file is being <code>pycheck</code>ed or <code>pydoc</code>ed.
2208 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00002209 </DIV></DIV>
2210 </DIV>
2211 </DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002212
2213<H2>Parting Words</H2>
2214 <p>
2215 <em>BE CONSISTENT</em>.
2216 </p>
2217
2218 <p>
2219 If you're editing code, take a few minutes to look at the code
2220 around you and determine its style. If they use spaces around
2221 all their arithmetic operators, you should too. If their
2222 comments have little boxes of hash marks around them, make your
2223 comments have little boxes of hash marks around them too.
2224 </p>
2225
2226 <p>
2227 The point of having style guidelines is to have a common vocabulary
2228 of coding so people can concentrate on what you're saying rather
2229 than on how you're saying it. We present global style rules here so
2230 people know the vocabulary, but local style is also important. If
2231 code you add to a file looks drastically different from the existing
2232 code around it, it throws readers out of their rhythm when they go to
2233 read it. Avoid this.
2234 </p>
2235
2236
2237
2238<p align="right">
mark@chromium.org8190c132013-03-21 16:03:26 +00002239Revision 2.48
apicard@google.comf900c2c2009-07-23 20:09:56 +00002240</p>
2241
2242
2243<address>
2244 Amit Patel<br>
2245 Antoine Picard<br>
2246 Eugene Jhong<br>
2247 Jeremy Hylton<br>
2248 Matt Smart<br>
2249 Mike Shields<br>
2250</address>
2251</BODY>
2252</HTML>