blob: 632c9c612b4208f8827ff8641c5f60ea09eb4a8f [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.org7b245632013-09-25 21:16:00 +0000139 Revision 2.59
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">
mark@chromium.org7b245632013-09-25 21:16:00 +0000168<SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Lint">Lint</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>
mark@chromium.org7b245632013-09-25 21:16:00 +0000217 <DIV class="">
218<H3><A name="Lint" id="Lint">Lint</A></H3>
219<SPAN class="link_button" id="link-Lint__button" name="link-Lint__button"><A href="?showone=Lint#Lint">
mmentovai8411f0c2010-08-04 17:46:16 +0000220 link
mark@chromium.org7b245632013-09-25 21:16:00 +0000221 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Lint')" name="Lint__button" id="Lint__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000222 <DIV style="display:inline;" class="">
mark@chromium.org7b245632013-09-25 21:16:00 +0000223 Run <code>pylint</code> over your code.
mmentovai9ec7bd62009-12-03 22:25:38 +0000224 </DIV>
mark@chromium.org7b245632013-09-25 21:16:00 +0000225 <DIV class=""><DIV class="stylepoint_body" name="Lint__body" id="Lint__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000226 <P class="">
227<SPAN class="stylepoint_section">Definition: </SPAN>
mark@chromium.org7b245632013-09-25 21:16:00 +0000228 pylint
229 is a tool for finding bugs and style problems in Python source
230 code. It finds
apicard@google.comf900c2c2009-07-23 20:09:56 +0000231 problems that are typically caught by a compiler for less dynamic
mark@chromium.org7b245632013-09-25 21:16:00 +0000232 languages like C and C++.
233
234 Because of the
apicard@google.comf900c2c2009-07-23 20:09:56 +0000235 dynamic nature of Python, some warnings may be incorrect; however,
236 spurious warnings should be fairly infrequent.
237 </P>
238 <P class="">
239<SPAN class="stylepoint_section">Pros: </SPAN>
mark@chromium.org7b245632013-09-25 21:16:00 +0000240 Catches easy-to-miss errors like typos, using-vars-before-assignment, etc.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000241 </P>
242 <P class="">
243<SPAN class="stylepoint_section">Cons: </SPAN>
mark@chromium.org7b245632013-09-25 21:16:00 +0000244 <code>pylint</code>
245 isn't perfect. To take advantage of it, we'll need to sometimes:
246 a) Write around it b) Suppress its warnings or c) Improve it.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000247 </P>
248 <P class="">
apicard@google.com424ad342012-09-18 23:16:02 +0000249<SPAN class="stylepoint_section">Decision: </SPAN>
mark@chromium.org7b245632013-09-25 21:16:00 +0000250 Make sure you run <code>pylint</code> on your code.
251 Suppress warnings if they are inappropriate so that other issues are
252 not hidden.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000253 </P>
254
255 <p>
mark@chromium.org7b245632013-09-25 21:16:00 +0000256 To suppress warnings, you can set a line-level comment:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000257 </p>
mark@chromium.org7b245632013-09-25 21:16:00 +0000258
mmentovai9ec7bd62009-12-03 22:25:38 +0000259 <DIV class=""><PRE>
mark@chromium.org7b245632013-09-25 21:16:00 +0000260<span class="external"></span>dict = 'something awful' # Bad Idea... pylint: disable=redefined-builtin</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000261 <p>
mark@chromium.org7b245632013-09-25 21:16:00 +0000262 pylint
263 warnings are each identified by a alphanumeric code
264 (<code>C0112</code>) and a symbolic name
265 (<code>empty-docstring</code>). Prefer the symbolic
266 names in new code or when updating existing code.
267
apicard@google.comf900c2c2009-07-23 20:09:56 +0000268 </p>
269 <p>
mark@chromium.org7b245632013-09-25 21:16:00 +0000270 If the reason for the suppression is not clear from the symbolic name,
271 add an explanation.
272 </p>
273 <p>
274 Suppressing in this way has the advantage that we can easily search
275 for suppressions and revisit them.
276 </p>
277 <p>
278 You can get a list of
279 pylint
280 warnings by doing
281 <code>pylint --list-msgs</code>.
282 To get more information on a particular message, use
283 <code>pylint --help-msg=C6409</code>.
284 </p>
285 <p>
286 Prefer <code>pylint: disable</code> to the deprecated older form
287 <code>pylint: disable-msg</code>.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000288 </p>
289 <p>
290 Unused argument warnings can be suppressed by using `_' as the
291 identifier for the unused argument or prefixing the argument name with
292 `unused_'. In situations where changing the argument names is
293 infeasible, you can mention them at the beginning of the function.
294 For example:
295 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000296 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000297<span class="external"></span>def foo(a, unused_b, unused_c, d=None, e=None):
apicard@google.com424ad342012-09-18 23:16:02 +0000298 <span class="external"> </span>_ = d, e
apicard@google.comf900c2c2009-07-23 20:09:56 +0000299 <span class="external"> </span>return a
300<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000301</PRE></DIV>
mmentovai9ec7bd62009-12-03 22:25:38 +0000302 </DIV></DIV>
303 </DIV>
304 <DIV class="">
305<H3><A name="Imports" id="Imports">Imports</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000306<SPAN class="link_button" id="link-Imports__button" name="link-Imports__button"><A href="?showone=Imports#Imports">
307 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000308 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Imports')" name="Imports__button" id="Imports__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000309 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000310 Use <code>import</code>s for packages and modules only.
mmentovai9ec7bd62009-12-03 22:25:38 +0000311 </DIV>
312 <DIV class=""><DIV class="stylepoint_body" name="Imports__body" id="Imports__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000313 <P class="">
314<SPAN class="stylepoint_section">Definition: </SPAN>
315 Reusability mechanism for sharing code from one module to another.
316 </P>
317 <P class="">
318<SPAN class="stylepoint_section">Pros: </SPAN>
mmentovaidb989ec2010-11-23 18:02:36 +0000319 The namespace management convention is simple. The source of each
320 identifier is indicated in a consistent way; <code>x.Obj</code> says
321 that object <code>Obj</code> is defined in module <code>x</code>.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000322 </P>
323 <P class="">
mmentovaidb989ec2010-11-23 18:02:36 +0000324<SPAN class="stylepoint_section">Cons: </SPAN> Module names can still collide. Some module names are
325 inconveniently long.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000326 </P>
327 <P class="">
328<SPAN class="stylepoint_section">Decision: </SPAN>
mmentovaidb989ec2010-11-23 18:02:36 +0000329 Use <code>import x</code> for importing packages and modules.
330 <br>
331 Use <code>from x import y</code> where <code>x</code> is
332 the package prefix and <code>y</code> is the module name with no
333 prefix.
334 <br>
335 Use <code>from x import y as z</code> if two modules named
mark@chromium.orge33361f2011-11-04 16:55:22 +0000336 <code>y</code> are to be imported or if <code>y</code> is an
mmentovaidb989ec2010-11-23 18:02:36 +0000337 inconveniently long name.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000338 </P>
mmentovaidb989ec2010-11-23 18:02:36 +0000339 For example the module
340 <code>sound.effects.echo</code> may be imported as follows:
mmentovai9ec7bd62009-12-03 22:25:38 +0000341 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000342<span class="external"></span>from sound.effects import echo
343<span class="external"></span>...
mmentovaidb989ec2010-11-23 18:02:36 +0000344<span class="external"></span>echo.EchoFilter(input, output, delay=0.7, atten=4)
apicard@google.comf900c2c2009-07-23 20:09:56 +0000345<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000346</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000347 <p>
mmentovaidb989ec2010-11-23 18:02:36 +0000348 Do not use relative names in imports. Even if the module is in the
349 same package, use the full package name. This helps prevent
350 unintentionally importing a package twice.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000351 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000352 </DIV></DIV>
353 </DIV>
354 <DIV class="">
355<H3><A name="Packages" id="Packages">Packages</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000356<SPAN class="link_button" id="link-Packages__button" name="link-Packages__button"><A href="?showone=Packages#Packages">
357 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000358 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Packages')" name="Packages__button" id="Packages__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000359 <DIV style="display:inline;" class="">
mmentovaidb989ec2010-11-23 18:02:36 +0000360 Import each module using the full pathname location of the module.
mmentovai9ec7bd62009-12-03 22:25:38 +0000361 </DIV>
362 <DIV class=""><DIV class="stylepoint_body" name="Packages__body" id="Packages__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000363 <P class="">
364<SPAN class="stylepoint_section">Pros: </SPAN>
365 Avoids conflicts in module names. Makes it easier to find modules.
366 </P>
367 <P class="">
368<SPAN class="stylepoint_section">Cons: </SPAN>
369 Makes it harder to deploy code because you have to replicate the
370 package hierarchy.
371 </P>
372 <P class="">
373<SPAN class="stylepoint_section">Decision: </SPAN>
mmentovaidb989ec2010-11-23 18:02:36 +0000374 All new code should import each module by its full package name.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000375 </P>
376 <p>
377 Imports should be as follows:
378 </p>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000379
mmentovai9ec7bd62009-12-03 22:25:38 +0000380 <DIV class=""><PRE># Reference in code with complete name.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000381import sound.effects.echo
382
mmentovaidb989ec2010-11-23 18:02:36 +0000383# Reference in code with just module name (preferred).
apicard@google.comf900c2c2009-07-23 20:09:56 +0000384from sound.effects import echo
mmentovai9ec7bd62009-12-03 22:25:38 +0000385</PRE></DIV>
mmentovai9ec7bd62009-12-03 22:25:38 +0000386 </DIV></DIV>
387 </DIV>
388 <DIV class="">
389<H3><A name="Exceptions" id="Exceptions">Exceptions</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000390<SPAN class="link_button" id="link-Exceptions__button" name="link-Exceptions__button"><A href="?showone=Exceptions#Exceptions">
391 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000392 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Exceptions')" name="Exceptions__button" id="Exceptions__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000393 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000394 Exceptions are allowed but must be used carefully.
mmentovai9ec7bd62009-12-03 22:25:38 +0000395 </DIV>
396 <DIV class=""><DIV class="stylepoint_body" name="Exceptions__body" id="Exceptions__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000397 <P class="">
398<SPAN class="stylepoint_section">Definition: </SPAN>
399 Exceptions are a means of breaking out of the normal flow of control
400 of a code block to handle errors or other exceptional conditions.
401 </P>
402 <P class="">
403<SPAN class="stylepoint_section">Pros: </SPAN>
404 The control flow of normal operation code is not cluttered by
405 error-handling code. It also allows the control flow to skip multiple
406 frames when a certain condition occurs, e.g., returning from N
407 nested functions in one step instead of having to carry-through
408 error codes.
409 </P>
410 <P class="">
411<SPAN class="stylepoint_section">Cons: </SPAN>
412 May cause the control flow to be confusing. Easy to miss error
413 cases when making library calls.
414 </P>
415 <P class="">
416<SPAN class="stylepoint_section">Decision: </SPAN>
417
418
419 Exceptions must follow certain conditions:
420
421 <ul>
apicard@google.com424ad342012-09-18 23:16:02 +0000422 <li>Raise exceptions like this: <code>raise MyException('Error
423 message')</code> or <code>raise MyException</code>. Do not
424 use the two-argument form (<code>raise MyException, 'Error
425 message'</code>) or deprecated string-based exceptions
426 (<code>raise 'Error message'</code>).</li>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000427 <li>Modules or packages should define their own domain-specific
428 base exception class, which should inherit from the built-in
429 Exception class. The base exception for a module should be called
430 <code>Error</code>.
mmentovai9ec7bd62009-12-03 22:25:38 +0000431 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000432<span class="external"></span>class Error(Exception):
mmentovai9ec7bd62009-12-03 22:25:38 +0000433 <span class="external"> </span>pass</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000434</li>
435 <li>Never use catch-all <code>except:</code> statements, or
436 catch <code>Exception</code> or <code>StandardError</code>,
437 unless you are re-raising the exception or in the outermost
438 block in your thread (and printing an error message). Python
439 is very tolerant in this regard and <code>except:</code> will
mark@chromium.orgc8c76a22012-11-28 20:26:27 +0000440 really catch everything including misspelled names, sys.exit()
441 calls, Ctrl+C interrupts, unittest failures and all kinds of
442 other exceptions that you simply don't want to catch.</li>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000443 <li>Minimize the amount of code in a
444 <code>try</code>/<code>except</code> block. The larger the
445 body of the <code>try</code>, the more likely that an
446 exception will be raised by a line of code that you didn't
447 expect to raise an exception. In those cases,
448 the <code>try</code>/<code>except</code> block hides a real
449 error.</li>
450 <li>Use the <code>finally</code> clause to execute code whether
451 or not an exception is raised in the <code>try</code> block.
452 This is often useful for cleanup, i.e., closing a file.</li>
apicard@google.com424ad342012-09-18 23:16:02 +0000453 <li>When capturing an exception, use <code>as</code> rather than
454 a comma. For example:
455 <DIV class=""><PRE>
456<span class="external"></span>try:
457 <span class="external"> </span>raise Error
458<span class="external"></span>except Error as error:
459 <span class="external"> </span>pass</PRE></DIV>
460</li>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000461 </ul>
462 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000463 </DIV></DIV>
464 </DIV>
465 <DIV class="">
466<H3><A name="Global_variables" id="Global_variables">Global variables</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000467<SPAN class="link_button" id="link-Global_variables__button" name="link-Global_variables__button"><A href="?showone=Global_variables#Global_variables">
468 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000469 </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 +0000470 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000471 Avoid global variables.
mmentovai9ec7bd62009-12-03 22:25:38 +0000472 </DIV>
473 <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 +0000474 <P class="">
475<SPAN class="stylepoint_section">Definition: </SPAN>
476 Variables that are declared at the module level.
477 </P>
478 <P class="">
479<SPAN class="stylepoint_section">Pros: </SPAN>
480 Occasionally useful.
481 </P>
482 <P class="">
483<SPAN class="stylepoint_section">Cons: </SPAN>
484 Has the potential to change module behavior during the import,
485 because assignments to module-level variables are done when the
486 module is imported.
487 </P>
488 <P class="">
489<SPAN class="stylepoint_section">Decision: </SPAN>
490 Avoid global variables in favor of class variables. Some
491 exceptions are:
492 <ul>
493 <li>Default options for scripts.</li>
494 <li>Module-level constants. For example: <code>PI = 3.14159</code>.
495 Constants should be named using all caps with underscores;
496 see <a HREF="#Naming">Naming</a> below.</li>
497 <li>It is sometimes useful for globals to cache values needed
498 or returned by functions.</li>
499 <li>If needed, globals should be made internal to the module
500 and accessed through public module level functions;
501 see <a HREF="#Naming">Naming</a> below.</li>
502 </ul>
503 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000504 </DIV></DIV>
505 </DIV>
506 <DIV class="">
507<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 +0000508<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">
509 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000510 </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 +0000511 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000512 Nested/local/inner classes and functions are fine.
mmentovai9ec7bd62009-12-03 22:25:38 +0000513 </DIV>
514 <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 +0000515 <P class="">
516<SPAN class="stylepoint_section">Definition: </SPAN>
mmentovaif7facf92009-10-23 21:01:49 +0000517 A class can be defined inside of a method, function, or class. A
518 function can be defined inside a method or function. Nested functions
519 have read-only access to variables defined in enclosing scopes.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000520 </P>
521 <P class="">
522<SPAN class="stylepoint_section">Pros: </SPAN>
523 Allows definition of utility classes and functions that are only
524 used inside of a very limited scope. Very <a HREF="http://en.wikipedia.org/wiki/Abstract_data_type">ADT</a>-y.
525 </P>
526 <P class="">
527<SPAN class="stylepoint_section">Cons: </SPAN>
528 Instances of nested or local classes cannot be pickled.
529 </P>
530 <P class="">
531<SPAN class="stylepoint_section">Decision: </SPAN>
532 They are fine.
533 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000534 </DIV></DIV>
535 </DIV>
536 <DIV class="">
537<H3><A name="List_Comprehensions" id="List_Comprehensions">List Comprehensions</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000538<SPAN class="link_button" id="link-List_Comprehensions__button" name="link-List_Comprehensions__button"><A href="?showone=List_Comprehensions#List_Comprehensions">
539 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000540 </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 +0000541 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000542 Okay to use for simple cases.
mmentovai9ec7bd62009-12-03 22:25:38 +0000543 </DIV>
544 <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 +0000545 <P class="">
546<SPAN class="stylepoint_section">Definition: </SPAN>
547 List comprehensions and generator expressions provide a concise
548 and efficient way to create lists and iterators without
549 resorting to the use of <code>map()</code>,
550 <code>filter()</code>, or <code>lambda</code>.
551 </P>
552 <P class="">
553<SPAN class="stylepoint_section">Pros: </SPAN>
554 Simple list comprehensions can be clearer and simpler than
555 other list creation techniques. Generator expressions can be
556 very efficient, since they avoid the creation of a list
557 entirely.
558 </P>
559 <P class="">
560<SPAN class="stylepoint_section">Cons: </SPAN>
561 Complicated list comprehensions or generator expressions can be
562 hard to read.
563 </P>
564 <P class="">
565<SPAN class="stylepoint_section">Decision: </SPAN>
566 Okay to use for simple cases. Each portion must fit on one line:
567 mapping expression, <code>for</code> clause, filter expression.
568 Multiple <code>for</code> clauses or filter expressions are not
569 permitted. Use loops instead when things get more complicated.
570 </P>
571
mmentovai9ec7bd62009-12-03 22:25:38 +0000572<DIV class=""><PRE>Ye<span class="external"></span>s:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000573 <span class="external"></span>result = []
574 <span class="external"></span>for x in range(10):
575 <span class="external"> </span>for y in range(5):
576 <span class="external"> </span>if x * y &gt; 10:
577 <span class="external"> </span>result.append((x, y))
578
579 <span class="external"></span>for x in xrange(5):
580 <span class="external"> </span>for y in xrange(5):
581 <span class="external"> </span>if x != y:
582 <span class="external"> </span>for z in xrange(5):
583 <span class="external"> </span>if y != z:
584 <span class="external"> </span>yield (x, y, z)
585
586 <span class="external"></span>return ((x, complicated_transform(x))
587 <span class="external"></span> for x in long_generator_function(parameter)
588 <span class="external"></span> if x is not None)
589
590 <span class="external"></span>squares = [x * x for x in range(10)]
591
592 <span class="external"></span>eat(jelly_bean for jelly_bean in jelly_beans
mmentovai9ec7bd62009-12-03 22:25:38 +0000593 <span class="external"></span> if jelly_bean.color == 'black')</PRE></DIV>
apicard@google.com424ad342012-09-18 23:16:02 +0000594<DIV class=""><PRE class="badcode">No<span class="external"></span>:
595 <span class="external"></span>result = [(x, y) for x in range(10) for y in range(5) if x * y &gt; 10]
596
597 <span class="external"></span>return ((x, y, z)
598 <span class="external"></span> for x in xrange(5)
599 <span class="external"></span> for y in xrange(5)
600 <span class="external"></span> if x != y
601 <span class="external"></span> for z in xrange(5)
602 <span class="external"></span> if y != z)</PRE></DIV>
mmentovai9ec7bd62009-12-03 22:25:38 +0000603 </DIV></DIV>
604 </DIV>
605 <DIV class="">
606<H3><A name="Default_Iterators_and_Operators" id="Default_Iterators_and_Operators">Default Iterators and Operators</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000607<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">
608 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000609 </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 +0000610 <DIV style="display:inline;" class="">
apicard@google.com424ad342012-09-18 23:16:02 +0000611 Use default iterators and operators for types that support them,
apicard@google.comf900c2c2009-07-23 20:09:56 +0000612 like lists, dictionaries, and files.
mmentovai9ec7bd62009-12-03 22:25:38 +0000613 </DIV>
614 <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 +0000615 <P class="">
616<SPAN class="stylepoint_section">Definition: </SPAN>
617 Container types, like dictionaries and lists, define default
618 iterators and membership test operators ("in" and "not in").
619 </P>
620 <P class="">
621<SPAN class="stylepoint_section">Pros: </SPAN>
622 The default iterators and operators are simple and efficient.
623 They express the operation directly, without extra method calls.
624 A function that uses default operators is generic. It can be
625 used with any type that supports the operation.
626 </P>
627 <P class="">
628<SPAN class="stylepoint_section">Cons: </SPAN>
629 You can't tell the type of objects by reading the method names
630 (e.g. has_key() means a dictionary). This is also an advantage.
631 </P>
632 <P class="">
633<SPAN class="stylepoint_section">Decision: </SPAN> Use default iterators and operators for types
634 that support them, like lists, dictionaries, and files. The
635 built-in types define iterator methods, too. Prefer these
636 methods to methods that return lists, except that you should not
637 mutate a container while iterating over it.
638
mmentovai9ec7bd62009-12-03 22:25:38 +0000639<DIV class=""><PRE>Yes: <span class="external"></span>for key in adict: ...
apicard@google.comf900c2c2009-07-23 20:09:56 +0000640 <span class="external"></span>if key not in adict: ...
641 <span class="external"></span>if obj in alist: ...
642 <span class="external"></span>for line in afile: ...
mmentovai9ec7bd62009-12-03 22:25:38 +0000643 <span class="external"></span>for k, v in dict.iteritems(): ...</PRE></DIV>
644<DIV class=""><PRE class="badcode">No: <span class="external"></span>for key in adict.keys(): ...
apicard@google.comf900c2c2009-07-23 20:09:56 +0000645 <span class="external"></span>if not adict.has_key(key): ...
mmentovai9ec7bd62009-12-03 22:25:38 +0000646 <span class="external"></span>for line in afile.readlines(): ...</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000647 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000648 </DIV></DIV>
649 </DIV>
650 <DIV class="">
651<H3><A name="Generators" id="Generators">Generators</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000652<SPAN class="link_button" id="link-Generators__button" name="link-Generators__button"><A href="?showone=Generators#Generators">
653 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000654 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Generators')" name="Generators__button" id="Generators__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000655 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000656 Use generators as needed.
mmentovai9ec7bd62009-12-03 22:25:38 +0000657 </DIV>
658 <DIV class=""><DIV class="stylepoint_body" name="Generators__body" id="Generators__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000659 <P class="">
660<SPAN class="stylepoint_section">Definition: </SPAN>
661 A generator function returns an iterator that yields a value each
662 time it executes a yield statement. After it yields a value, the
663 runtime state of the generator function is suspended until the
664 next value is needed.
665 </P>
666 <P class="">
667<SPAN class="stylepoint_section">Pros: </SPAN>
668 Simpler code, because the state of local variables and control flow
669 are preserved for each call. A generator uses less memory than a
670 function that creates an entire list of values at once.
671 </P>
672 <P class="">
apicard@google.com424ad342012-09-18 23:16:02 +0000673<SPAN class="stylepoint_section">Cons: </SPAN>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000674 None.
675 </P>
676 <P class="">
677<SPAN class="stylepoint_section">Decision: </SPAN>
678 Fine. Use "Yields:" rather than "Returns:" in the
679 doc string for generator functions.
680 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000681 </DIV></DIV>
682 </DIV>
683 <DIV class="">
684<H3><A name="Lambda_Functions" id="Lambda_Functions">Lambda Functions</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000685<SPAN class="link_button" id="link-Lambda_Functions__button" name="link-Lambda_Functions__button"><A href="?showone=Lambda_Functions#Lambda_Functions">
686 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000687 </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 +0000688 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000689 Okay for one-liners.
mmentovai9ec7bd62009-12-03 22:25:38 +0000690 </DIV>
691 <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 +0000692 <P class="">
693<SPAN class="stylepoint_section">Definition: </SPAN>
694 Lambdas define anonymous functions in an expression, as
695 opposed to a statement. They are often used to define callbacks or
696 operators for higher-order functions like <code>map()</code> and
697 <code>filter()</code>.
698 </P>
699 <P class="">
700<SPAN class="stylepoint_section">Pros: </SPAN>
701 Convenient.
702 </P>
703 <P class="">
704<SPAN class="stylepoint_section">Cons: </SPAN> Harder to read and debug than local functions. The
705 lack of names means stack traces are more difficult to
706 understand. Expressiveness is limited because the function may
707 only contain an expression.
708 </P>
709 <P class="">
710<SPAN class="stylepoint_section">Decision: </SPAN>
711 Okay to use them for one-liners. If the code inside the lambda
712 function is any longer than 60–80 chars, it's probably better to
713 define it as a regular (nested) function.
714 <p>
715 For common operations like multiplication, use the functions from the
716 <code>operator</code> module instead of lambda functions. For
717 example, prefer <code>operator.mul</code> to <code>lambda
718 x, y: x * y</code>.
719 </p>
720 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000721 </DIV></DIV>
722 </DIV>
723 <DIV class="">
apicard@google.com424ad342012-09-18 23:16:02 +0000724<H3><A name="Conditional_Expressions" id="Conditional_Expressions">Conditional Expressions</A></H3>
725<SPAN class="link_button" id="link-Conditional_Expressions__button" name="link-Conditional_Expressions__button"><A href="?showone=Conditional_Expressions#Conditional_Expressions">
726 link
727 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Conditional_Expressions')" name="Conditional_Expressions__button" id="Conditional_Expressions__button"></SPAN>
728 <DIV style="display:inline;" class="">
729 Okay for one-liners.
730 </DIV>
731 <DIV class=""><DIV class="stylepoint_body" name="Conditional_Expressions__body" id="Conditional_Expressions__body" style="display: none">
732 <P class="">
733<SPAN class="stylepoint_section">Definition: </SPAN>
734 Conditional expressions are mechanisms that provide a shorter syntax
735 for if statements. For example:
736 <code>x = 1 if cond else 2</code>.
737 </P>
738 <P class="">
739<SPAN class="stylepoint_section">Pros: </SPAN>
740 Shorter and more convenient than an if statement.
741 </P>
742 <P class="">
743<SPAN class="stylepoint_section">Cons: </SPAN>
744 May be harder to read than an if statement. The condition may be difficult
745 to locate if the expression is long.
746 </P>
747 <P class="">
748<SPAN class="stylepoint_section">Decision: </SPAN>
749 Okay to use for one-liners. In other cases prefer to use a complete if
750 statement.
751 </P>
752 </DIV></DIV>
753 </DIV>
754 <DIV class="">
mmentovai9ec7bd62009-12-03 22:25:38 +0000755<H3><A name="Default_Argument_Values" id="Default_Argument_Values">Default Argument Values</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000756<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">
757 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000758 </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 +0000759 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000760 Okay in most cases.
mmentovai9ec7bd62009-12-03 22:25:38 +0000761 </DIV>
762 <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 +0000763 <P class="">
764<SPAN class="stylepoint_section">Definition: </SPAN>
765 You can specify values for variables at the end of a function's
766 parameter list, e.g., <code>def foo(a, b=0):</code>. If
767 <code>foo</code> is called with only one argument,
768 <code>b</code> is set to 0. If it is called with two arguments,
769 <code>b</code> has the value of the second argument.
770 </P>
771 <P class="">
772<SPAN class="stylepoint_section">Pros: </SPAN>
773 Often you have a function that uses lots of default values,
774 but—rarely—you want to override the
775 defaults. Default argument values provide an easy way to do this,
776 without having to define lots of functions for the rare
777 exceptions. Also, Python does not support overloaded
778 methods/functions and default arguments are an easy way of
779 "faking" the overloading behavior.
780 </P>
781 <P class="">
apicard@google.com424ad342012-09-18 23:16:02 +0000782<SPAN class="stylepoint_section">Cons: </SPAN>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000783 Default arguments are evaluated once at module load
784 time. This may cause problems if the argument is a mutable
785 object such as a list or a dictionary. If the function modifies
786 the object (e.g., by appending an item to a list), the default
787 value is modified.
788 </P>
789 <P class="">
790<SPAN class="stylepoint_section">Decision: </SPAN>
mark@chromium.org5684bbc2013-07-12 18:53:13 +0000791 Okay to use with the following caveat:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000792 <p>
793 Do not use mutable objects as default values in the function or method
794 definition.
795 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000796<DIV class=""><PRE>Yes: <span class="external"></span>def foo(a, b=None):
apicard@google.comf900c2c2009-07-23 20:09:56 +0000797 <span class="external"> </span>if b is None:
mmentovai9ec7bd62009-12-03 22:25:38 +0000798 <span class="external"> </span>b = []</PRE></DIV>
799<DIV class=""><PRE class="badcode">No: <span class="external"></span>def foo(a, b=[]):
mark@chromium.org7b245632013-09-25 21:16:00 +0000800 <span class="external"> </span>...
801No: <span class="external"></span>def foo(a, b=time.time()): # The time the module was loaded???
802 <span class="external"> </span>...
803No: <span class="external"></span>def foo(a, b=FLAGS.my_thing): # sys.argv has not yet been parsed...
mmentovai9ec7bd62009-12-03 22:25:38 +0000804 <span class="external"> </span>...</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000805 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000806 </DIV></DIV>
807 </DIV>
808 <DIV class="">
809<H3><A name="Properties" id="Properties">Properties</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000810<SPAN class="link_button" id="link-Properties__button" name="link-Properties__button"><A href="?showone=Properties#Properties">
811 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000812 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Properties')" name="Properties__button" id="Properties__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000813 <DIV style="display:inline;" class="">
apicard@google.com424ad342012-09-18 23:16:02 +0000814 Use properties for accessing or setting data where you would
815 normally have used simple, lightweight accessor or setter methods.
mmentovai9ec7bd62009-12-03 22:25:38 +0000816 </DIV>
817 <DIV class=""><DIV class="stylepoint_body" name="Properties__body" id="Properties__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000818 <P class="">
819<SPAN class="stylepoint_section">Definition: </SPAN> A way to wrap method calls for getting and
820 setting an attribute as a standard attribute access when the
821 computation is lightweight.
822 </P>
823 <P class="">
824<SPAN class="stylepoint_section">Pros: </SPAN> Readability is increased by eliminating explicit
825 get and set method calls for simple attribute access. Allows
826 calculations to be lazy. Considered the Pythonic way to
827 maintain the interface of a class. In terms of performance,
828 allowing properties bypasses needing trivial accessor methods
829 when a direct variable access is reasonable. This also allows
830 accessor methods to be added in the future without breaking the
831 interface.
832 </P>
833 <P class="">
834<SPAN class="stylepoint_section">Cons: </SPAN> Properties are specified after the getter and
835 setter methods are declared, requiring one to notice they are
836 used for properties farther down in the code (except for readonly
837 properties created with the <code>@property</code> decorator - see
838 below). Must inherit from
839 <code>object</code>. Can hide side-effects much like operator
840 overloading. Can be confusing for subclasses.
841 </P>
842 <P class="">
843<SPAN class="stylepoint_section">Decision: </SPAN> Use properties in new code to access or
844 set data where you would normally have used simple, lightweight
845 accessor or setter methods. Read-only properties should be created
apicard@google.com424ad342012-09-18 23:16:02 +0000846 with the <code>@property</code>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000847 <a HREF="#Function_and_Method_Decorators">decorator</a>.
848
849 <p><a id="properties-template-dp">
850 Inheritance with properties can be non-obvious if the property itself is
851 not overridden. Thus one must make sure that accessor methods are
852 called indirectly to ensure methods overridden in subclasses are called
853 by the property (using the Template Method DP).
854 </a></p>
855
mmentovai9ec7bd62009-12-03 22:25:38 +0000856 <DIV class=""><PRE>Yes: <span class="external"></span>import math
apicard@google.comf900c2c2009-07-23 20:09:56 +0000857
858 <span class="external"></span>class Square(object):
859 <span class="external"> </span>"""A square with two properties: a writable area and a read-only perimeter.
860
861 <span class="external"> </span>To use:
862 <span class="external"> </span>&gt;&gt;&gt; sq = Square(3)
863 <span class="external"> </span>&gt;&gt;&gt; sq.area
864 <span class="external"> </span>9
865 <span class="external"> </span>&gt;&gt;&gt; sq.perimeter
866 <span class="external"> </span>12
867 <span class="external"> </span>&gt;&gt;&gt; sq.area = 16
868 <span class="external"> </span>&gt;&gt;&gt; sq.side
869 <span class="external"> </span>4
870 <span class="external"> </span>&gt;&gt;&gt; sq.perimeter
871 <span class="external"> </span>16
872 <span class="external"> </span>"""
873
874 <span class="external"> </span>def __init__(self, side):
875 <span class="external"> </span>self.side = side
876
877 <span class="external"> </span>def __get_area(self):
878 <span class="external"> </span>"""Calculates the 'area' property."""
879 <span class="external"> </span>return self.side ** 2
880
881 <span class="external"> </span>def ___get_area(self):
882 <span class="external"> </span>"""Indirect accessor for 'area' property."""
883 <span class="external"> </span>return self.__get_area()
884
885 <span class="external"> </span>def __set_area(self, area):
886 <span class="external"> </span>"""Sets the 'area' property."""
887 <span class="external"> </span>self.side = math.sqrt(area)
888
889 <span class="external"> </span>def ___set_area(self, area):
890 <span class="external"> </span>"""Indirect setter for 'area' property."""
mark@chromium.org7f891932011-11-04 21:13:33 +0000891 <span class="external"> </span>self.__set_area(area)
apicard@google.comf900c2c2009-07-23 20:09:56 +0000892
893 <span class="external"> </span>area = property(___get_area, ___set_area,
894 <span class="external"> </span> doc="""Gets or sets the area of the square.""")
895
896 <span class="external"> </span>@property
897 <span class="external"> </span>def perimeter(self):
898 <span class="external"> </span>return self.side * 4
899<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000900</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000901 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000902 </DIV></DIV>
903 </DIV>
904 <DIV class="">
905<H3><A name="True/False_evaluations" id="True/False_evaluations">True/False evaluations</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000906<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">
907 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000908 </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 +0000909 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000910 Use the "implicit" false if at all possible.
mmentovai9ec7bd62009-12-03 22:25:38 +0000911 </DIV>
912 <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 +0000913 <P class="">
914<SPAN class="stylepoint_section">Definition: </SPAN> Python evaluates certain values as <code>false</code>
915 when in a boolean context. A quick "rule of thumb" is that all
916 "empty" values are considered <code>false</code> so <code>0, None, [], {},
apicard@google.com424ad342012-09-18 23:16:02 +0000917 ''</code> all evaluate as <code>false</code> in a boolean context.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000918 </P>
919 <P class="">
920<SPAN class="stylepoint_section">Pros: </SPAN> Conditions using Python booleans are easier to read
921 and less error-prone. In most cases, they're also faster.
922 </P>
923 <P class="">
924<SPAN class="stylepoint_section">Cons: </SPAN>
925 May look strange to C/C++ developers.
926 </P>
927 <P class="">
928<SPAN class="stylepoint_section">Decision: </SPAN>
929 Use the "implicit" false if at all possible, e.g., <code>if
930 foo:</code> rather than <code>if foo != []:</code>. There are a
931 few caveats that you should keep in mind though:
932 <ul>
933 <li>
934 Never use <code>==</code> or <code>!=</code> to compare
935 singletons like <code>None</code>. Use <code>is</code>
936 or <code>is not</code>.</li>
937
938 <li>Beware of writing <code>if x:</code> when you really mean
939 <code>if x is not None:</code>—e.g., when testing whether
940 a variable or argument that defaults to <code>None</code> was
941 set to some other value. The other value might be a value
942 that's false in a boolean context!</li>
943
944 <li>
945 Never compare a boolean variable to <code>False</code> using
946 <code>==</code>. Use <code>if not x:</code> instead. If
947 you need to distinguish <code>False</code> from
948 <code>None</code> then chain the expressions,
949 such as <code>if not x and x is not None:</code>.
950 </li>
951
952 <li>
953 For sequences (strings, lists, tuples), use the fact that
954 empty sequences are false, so <code>if not seq:</code> or
955 <code>if seq:</code> is preferable to <code>if
956 len(seq):</code> or <code>if not
957 len(seq):</code>.</li>
958
959 <li>
960 When handling integers, implicit false may involve more risk than
961 benefit (i.e., accidentally handling <code>None</code> as 0). You may
962 compare a value which is known to be an integer (and is not the
963 result of <code>len()</code>) against the integer 0.
mmentovai9ec7bd62009-12-03 22:25:38 +0000964<DIV class=""><PRE>Yes: <span class="external"></span>if not users:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000965 <span class="external"> </span>print 'no users'
966
967 <span class="external"></span>if foo == 0:
968 <span class="external"> </span>self.handle_zero()
969
970 <span class="external"></span>if i % 10 == 0:
mmentovai9ec7bd62009-12-03 22:25:38 +0000971 <span class="external"> </span>self.handle_multiple_of_ten()</PRE></DIV>
972<DIV class=""><PRE class="badcode">No: <span class="external"></span>if len(users) == 0:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000973 <span class="external"> </span>print 'no users'
974
975 <span class="external"></span>if foo is not None and not foo:
976 <span class="external"> </span>self.handle_zero()
977
978 <span class="external"></span>if not i % 10:
mmentovai9ec7bd62009-12-03 22:25:38 +0000979 <span class="external"> </span>self.handle_multiple_of_ten()</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000980</li>
981
982 <li>
983 Note that <code>'0'</code> (i.e., <code>0</code> as string)
984 evaluates to true.</li>
985 </ul>
986 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000987 </DIV></DIV>
988 </DIV>
989 <DIV class="">
990<H3><A name="Deprecated_Language_Features" id="Deprecated_Language_Features">Deprecated Language Features</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000991<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">
992 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000993 </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 +0000994 <DIV style="display:inline;" class="">
mmentovaif7facf92009-10-23 21:01:49 +0000995 Use string methods instead of the <code>string</code> module
996 where possible. Use function call syntax instead
997 of <code>apply</code>. Use list comprehensions
mark@chromium.orgc8c76a22012-11-28 20:26:27 +0000998 and <code>for</code> loops instead of <code>filter</code> and
999 <code>map</code> when the function argument would have been an
1000 inlined lambda anyway. Use <code>for</code> loops instead of
1001 <code>reduce</code>.
mmentovai9ec7bd62009-12-03 22:25:38 +00001002 </DIV>
1003 <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 +00001004 <P class="">
mmentovaif7facf92009-10-23 21:01:49 +00001005<SPAN class="stylepoint_section">Definition: </SPAN>
1006 Current versions of Python provide alternative constructs
1007 that people find generally preferable.
apicard@google.comf900c2c2009-07-23 20:09:56 +00001008 </P>
1009 <P class="">
mmentovaif7facf92009-10-23 21:01:49 +00001010<SPAN class="stylepoint_section">Decision: </SPAN>
1011 We do not use any Python version which does not support
1012 these features, so there is no reason not to use the new
1013 styles.
mmentovai9ec7bd62009-12-03 22:25:38 +00001014<DIV class=""><PRE>Yes: <span class="external"></span>words = foo.split(':')
mmentovaif7facf92009-10-23 21:01:49 +00001015
1016 <span class="external"></span>[x[1] for x in my_list if x[2] == 5]
1017
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001018 <span class="external"></span>map(math.sqrt, data) # Ok. No inlined lambda expression.
1019
mmentovai9ec7bd62009-12-03 22:25:38 +00001020 <span class="external"></span>fn(*args, **kwargs)</PRE></DIV>
apicard@google.com424ad342012-09-18 23:16:02 +00001021<DIV class=""><PRE class="badcode">No: <span class="external"></span>words = string.split(foo, ':')
1022
1023 <span class="external"></span>map(lambda x: x[1], filter(lambda x: x[2] == 5, my_list))
1024
1025 <span class="external"></span>apply(fn, args, kwargs)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001026 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001027 </DIV></DIV>
1028 </DIV>
1029 <DIV class="">
1030<H3><A name="Lexical_Scoping" id="Lexical_Scoping">Lexical Scoping</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001031<SPAN class="link_button" id="link-Lexical_Scoping__button" name="link-Lexical_Scoping__button"><A href="?showone=Lexical_Scoping#Lexical_Scoping">
1032 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001033 </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 +00001034 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001035 Okay to use.
mmentovai9ec7bd62009-12-03 22:25:38 +00001036 </DIV>
1037 <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 +00001038 <P class="">
1039<SPAN class="stylepoint_section">Definition: </SPAN>
1040 A nested Python function can refer to variables defined in
1041 enclosing functions, but can not assign to them. Variable
1042 bindings are resolved using lexical scoping, that is, based on
1043 the static program text. Any assignment to a name in a block
1044 will cause Python to treat all references to that name as a
1045 local variable, even if the use precedes the assignment. If a
1046 global declaration occurs, the name is treated as a global
1047 variable.
apicard@google.com424ad342012-09-18 23:16:02 +00001048
apicard@google.comf900c2c2009-07-23 20:09:56 +00001049 <p>
1050 An example of the use of this feature is:
1051 </p>
1052
mmentovai9ec7bd62009-12-03 22:25:38 +00001053 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001054<span class="external"></span>def get_adder(summand1):
1055 <span class="external"> </span>"""Returns a function that adds numbers to a given number."""
1056 <span class="external"> </span>def adder(summand2):
1057 <span class="external"> </span>return summand1 + summand2
1058
1059 <span class="external"> </span>return adder
1060<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001061</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001062 </P>
1063 <P class="">
1064<SPAN class="stylepoint_section">Pros: </SPAN>
1065 Often results in clearer, more elegant code. Especially comforting
1066 to experienced Lisp and Scheme (and Haskell and ML and …)
1067 programmers.
1068 </P>
1069 <P class="">
1070<SPAN class="stylepoint_section">Cons: </SPAN>
apicard@google.com424ad342012-09-18 23:16:02 +00001071 Can lead to confusing bugs. Such as this example based on
apicard@google.comf900c2c2009-07-23 20:09:56 +00001072 <a HREF="http://www.python.org/dev/peps/pep-0227/">PEP-0227</a>:
mmentovai9ec7bd62009-12-03 22:25:38 +00001073<DIV class=""><PRE class="badcode">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001074<span class="external"></span>i = 4
1075<span class="external"></span>def foo(x):
1076 <span class="external"> </span>def bar():
1077 <span class="external"> </span>print i,
1078 <span class="external"> </span># ...
1079 <span class="external"> </span># A bunch of code here
1080 <span class="external"> </span># ...
1081 <span class="external"> </span>for i in x: # Ah, i *is* local to Foo, so this is what Bar sees
1082 <span class="external"> </span>print i,
mmentovai9ec7bd62009-12-03 22:25:38 +00001083 <span class="external"> </span>bar()</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001084 <p>
1085 So <code>foo([1, 2, 3])</code> will print <code>1 2 3 3</code>, not
1086 <code>1 2 3 4</code>.
apicard@google.com424ad342012-09-18 23:16:02 +00001087 </p>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001088 </P>
1089 <P class="">
1090<SPAN class="stylepoint_section">Decision: </SPAN>
1091 Okay to use.
1092 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001093 </DIV></DIV>
1094 </DIV>
1095 <DIV class="">
1096<H3><A name="Function_and_Method_Decorators" id="Function_and_Method_Decorators">Function and Method Decorators</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001097<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">
1098 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001099 </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 +00001100 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001101 Use decorators judiciously when there is a clear advantage.
mmentovai9ec7bd62009-12-03 22:25:38 +00001102 </DIV>
1103 <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 +00001104 <P class="">
1105<SPAN class="stylepoint_section">Definition: </SPAN>
1106
1107 <a HREF="http://www.python.org/doc/2.4.3/whatsnew/node6.html">Decorators
1108 for Functions and Methods</a>
1109 (a.k.a "the <code>@</code> notation").
1110 The most common decorators are <code>@classmethod</code> and
1111 <code>@staticmethod</code>, for converting ordinary methods to class or
1112 static methods. However, the decorator syntax allows for
1113 user-defined decorators as well. Specifically, for some function
1114 <code>my_decorator</code>, this:
mmentovai9ec7bd62009-12-03 22:25:38 +00001115 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001116<span class="external"></span>class C(object):
1117 <span class="external"> </span>@my_decorator
1118 <span class="external"> </span>def method(self):
1119 <span class="external"> </span># method body ...
1120<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001121</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001122
1123 is equivalent to:
mmentovai9ec7bd62009-12-03 22:25:38 +00001124 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001125<span class="external"></span>class C(object):
1126 <span class="external"> </span>def method(self):
1127 <span class="external"> </span># method body ...
1128 <span class="external"> </span>method = my_decorator(method)
1129<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001130</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001131 </P>
1132 <P class="">
1133<SPAN class="stylepoint_section">Pros: </SPAN> Elegantly specifies some transformation on a method; the
1134 transformation might eliminate some repetitive code, enforce invariants,
1135 etc.
1136 </P>
1137 <P class="">
1138<SPAN class="stylepoint_section">Cons: </SPAN> Decorators can perform arbitrary operations on a
1139 function's arguments or return values, resulting in surprising
1140 implicit behavior.
1141 Additionally, decorators execute at import time. Failures in decorator
1142 code are pretty much impossible to recover from.
1143 </P>
1144 <P class="">
1145<SPAN class="stylepoint_section">Decision: </SPAN> Use decorators judiciously when there is a clear
1146 advantage. Decorators should follow the same import and naming
1147 guidelines as functions. Decorator pydoc should clearly state that the
1148 function is a decorator. Write unit tests for decorators.
1149
1150 <p>
1151 Avoid external dependencies in the decorator itself (e.g. don't rely on
1152 files, sockets, database connections, etc.), since they might not be
1153 available when the decorator runs (at import time, perhaps from
mark@chromium.org7b245632013-09-25 21:16:00 +00001154 <code>pydoc</code> or other tools). A decorator that is
apicard@google.comf900c2c2009-07-23 20:09:56 +00001155 called with valid parameters should (as much as possible) be guaranteed
1156 to succeed in all cases.
1157 </p>
1158 <p>
1159 Decorators are a special case of "top level code" - see
1160 <a HREF="#Main">main</a> for more discussion.
1161 </p>
1162 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001163 </DIV></DIV>
1164 </DIV>
1165 <DIV class="">
1166<H3><A name="Threading" id="Threading">Threading</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001167<SPAN class="link_button" id="link-Threading__button" name="link-Threading__button"><A href="?showone=Threading#Threading">
1168 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001169 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Threading')" name="Threading__button" id="Threading__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001170 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001171 Do not rely on the atomicity of built-in types.
mmentovai9ec7bd62009-12-03 22:25:38 +00001172 </DIV>
1173 <DIV class=""><DIV class="stylepoint_body" name="Threading__body" id="Threading__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001174 <p>
1175 While Python's built-in data types such as dictionaries appear
1176 to have atomic operations, there are corner cases where they
1177 aren't atomic (e.g. if <code>__hash__</code> or
1178 <code>__eq__</code> are implemented as Python methods) and their
1179 atomicity should not be relied upon. Neither should you rely on
1180 atomic variable assignment (since this in turn depends on
1181 dictionaries).
1182 </p>
1183
1184 <p>
apicard@google.com424ad342012-09-18 23:16:02 +00001185 Use the Queue module's <code>Queue</code> data type as the preferred
apicard@google.comf900c2c2009-07-23 20:09:56 +00001186 way to
1187 communicate data between threads. Otherwise, use the threading
1188 module and its locking primitives. Learn about the proper use
1189 of condition variables so you can use
1190 <code>threading.Condition</code> instead of using lower-level
1191 locks.
1192 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001193 </DIV></DIV>
1194 </DIV>
1195 <DIV class="">
1196<H3><A name="Power_Features" id="Power_Features">Power Features</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001197<SPAN class="link_button" id="link-Power_Features__button" name="link-Power_Features__button"><A href="?showone=Power_Features#Power_Features">
1198 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001199 </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 +00001200 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001201 Avoid these features.
mmentovai9ec7bd62009-12-03 22:25:38 +00001202 </DIV>
1203 <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 +00001204 <P class="">
1205<SPAN class="stylepoint_section">Definition: </SPAN> Python is an extremely flexible language and
1206 gives you many fancy features such as metaclasses, access to bytecode,
1207 on-the-fly compilation, dynamic inheritance, object reparenting,
1208 import hacks, reflection, modification of system internals,
1209 etc.
1210 </P>
1211 <P class="">
1212<SPAN class="stylepoint_section">Pros: </SPAN> These are powerful language features. They can
1213 make your code more compact.
1214 </P>
1215 <P class="">
1216<SPAN class="stylepoint_section">Cons: </SPAN> It's very tempting to use these "cool" features
1217 when they're not absolutely necessary. It's harder to read,
1218 understand, and debug code that's using unusual features
1219 underneath. It doesn't seem that way at first (to the original
1220 author), but when revisiting the code, it tends to be more
1221 difficult than code that is longer but is straightforward.
1222 </P>
1223 <P class="">
apicard@google.com424ad342012-09-18 23:16:02 +00001224<SPAN class="stylepoint_section">Decision: </SPAN>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001225 Avoid these features in
1226 your code.
1227 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001228 </DIV></DIV>
1229 </DIV>
1230 </DIV>
1231 <DIV class="">
1232<H2 name="Python_Style_Rules" id="Python_Style_Rules">Python Style Rules</H2>
1233 <DIV class="">
1234<H3><A name="Semicolons" id="Semicolons">Semicolons</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001235<SPAN class="link_button" id="link-Semicolons__button" name="link-Semicolons__button"><A href="?showone=Semicolons#Semicolons">
1236 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001237 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Semicolons')" name="Semicolons__button" id="Semicolons__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001238 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001239 Do not terminate your lines with semi-colons and do not use
1240 semi-colons to put two commands on the same line.
mmentovai9ec7bd62009-12-03 22:25:38 +00001241 </DIV>
1242 <DIV class=""><DIV class="stylepoint_body" name="Semicolons__body" id="Semicolons__body" style="display: none">
mmentovai9ec7bd62009-12-03 22:25:38 +00001243 </DIV></DIV>
1244 </DIV>
1245 <DIV class="">
1246<H3><A name="Line_length" id="Line_length">Line length</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001247<SPAN class="link_button" id="link-Line_length__button" name="link-Line_length__button"><A href="?showone=Line_length#Line_length">
1248 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001249 </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 +00001250 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001251 Maximum line length is <em>80 characters</em>.
mmentovai9ec7bd62009-12-03 22:25:38 +00001252 </DIV>
1253 <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 +00001254 <p>
mark@chromium.org8190c132013-03-21 16:03:26 +00001255 Exceptions:
1256 <ul>
1257 <li>Long import statements.</li>
1258 <li>URLs in comments.</li>
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001259
mark@chromium.org8190c132013-03-21 16:03:26 +00001260 </ul>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001261 </p>
1262
1263 <p>
mark@chromium.orge33361f2011-11-04 16:55:22 +00001264 Do not use backslash line continuation.
1265 </p>
1266
1267 <p>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001268 Make use of Python's
1269
mark@chromium.org8190c132013-03-21 16:03:26 +00001270 <a HREF="http://docs.python.org/reference/lexical_analysis.html#implicit-line-joining">implicit
apicard@google.comf900c2c2009-07-23 20:09:56 +00001271 line joining inside parentheses, brackets and braces</a>.
1272 If necessary, you can add an extra pair of parentheses around an
1273 expression.
1274 </p>
1275
1276
mmentovai9ec7bd62009-12-03 22:25:38 +00001277 <DIV class=""><PRE>Yes: foo_bar(self, width, height, color='black', design=None, x='foo',
apicard@google.comf900c2c2009-07-23 20:09:56 +00001278 emphasis=None, highlight=0)
1279
1280 if (width == 0 and height == 0 and
mmentovai9ec7bd62009-12-03 22:25:38 +00001281 color == 'red' and emphasis == 'strong'):</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001282
1283
1284 <p>
1285 When a literal string won't fit on a single line, use parentheses for
1286 implicit line joining.
1287 </p>
1288
mmentovai9ec7bd62009-12-03 22:25:38 +00001289 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001290<span class="external"></span>x = ('This will build a very long long '
mmentovai9ec7bd62009-12-03 22:25:38 +00001291<span class="external"></span> 'long long long long long long string')</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001292
1293 <p>
mark@chromium.org8190c132013-03-21 16:03:26 +00001294 Within comments, put long URLs on their own line if necessary.
1295 </p>
1296
1297 <DIV class=""><PRE>Yes: <span class="external"></span># See details at
1298 <span class="external"></span># http://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.html</PRE></DIV>
1299
1300 <DIV class=""><PRE class="badcode">No: <span class="external"></span># See details at
1301 <span class="external"></span># http://www.example.com/us/developer/documentation/api/content/\
1302 <span class="external"></span># v2.0/csv_file_name_extension_full_specification.html</PRE></DIV>
1303
1304 <p>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001305 Make note of the indentation of the elements in the line
apicard@google.com424ad342012-09-18 23:16:02 +00001306 continuation examples above; see the
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001307 <a HREF="#Indentation">indentation</a>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001308 section for explanation.
1309 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001310 </DIV></DIV>
1311 </DIV>
1312 <DIV class="">
1313<H3><A name="Parentheses" id="Parentheses">Parentheses</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001314<SPAN class="link_button" id="link-Parentheses__button" name="link-Parentheses__button"><A href="?showone=Parentheses#Parentheses">
1315 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001316 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Parentheses')" name="Parentheses__button" id="Parentheses__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001317 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001318 Use parentheses sparingly.
mmentovai9ec7bd62009-12-03 22:25:38 +00001319 </DIV>
1320 <DIV class=""><DIV class="stylepoint_body" name="Parentheses__body" id="Parentheses__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001321 <p>
apicard@google.com424ad342012-09-18 23:16:02 +00001322 Do not use them in return statements or conditional statements unless
1323 using parentheses for implied line continuation. (See above.)
apicard@google.comf900c2c2009-07-23 20:09:56 +00001324 It is however fine to use parentheses around tuples.
1325 </p>
1326
mmentovai9ec7bd62009-12-03 22:25:38 +00001327<DIV class=""><PRE>Yes: <span class="external"></span>if foo:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001328 <span class="external"> </span>bar()
1329 <span class="external"></span>while x:
1330 <span class="external"> </span>x = bar()
1331 <span class="external"></span>if x and y:
1332 <span class="external"> </span>bar()
1333 <span class="external"></span>if not x:
1334 <span class="external"> </span>bar()
1335 <span class="external"></span>return foo
mmentovai9ec7bd62009-12-03 22:25:38 +00001336 <span class="external"></span>for (x, y) in dict.items(): ...</PRE></DIV>
1337<DIV class=""><PRE class="badcode">No: <span class="external"></span>if (x):
apicard@google.comf900c2c2009-07-23 20:09:56 +00001338 <span class="external"> </span>bar()
1339 <span class="external"></span>if not(x):
1340 <span class="external"> </span>bar()
mmentovai9ec7bd62009-12-03 22:25:38 +00001341 <span class="external"></span>return (foo)</PRE></DIV>
1342 </DIV></DIV>
1343 </DIV>
1344 <DIV class="">
1345<H3><A name="Indentation" id="Indentation">Indentation</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001346<SPAN class="link_button" id="link-Indentation__button" name="link-Indentation__button"><A href="?showone=Indentation#Indentation">
1347 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001348 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Indentation')" name="Indentation__button" id="Indentation__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001349 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001350 Indent your code blocks with <em>4 spaces</em>.
mmentovai9ec7bd62009-12-03 22:25:38 +00001351 </DIV>
1352 <DIV class=""><DIV class="stylepoint_body" name="Indentation__body" id="Indentation__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001353 <p>
1354 Never use tabs or mix tabs and spaces.
1355 In cases of implied line continuation, you should align wrapped elements
1356 either vertically, as per the examples in the
1357 <a HREF="#Line_length">line length</a> section; or using a hanging
1358 indent of 4 spaces, in which case there should be no argument on
1359 the first line.
1360 </p>
1361
1362
mmentovai9ec7bd62009-12-03 22:25:38 +00001363<DIV class=""><PRE>Yes: # Aligned with opening delimiter
apicard@google.comf900c2c2009-07-23 20:09:56 +00001364 foo = long_function_name(var_one, var_two,
1365 var_three, var_four)
1366
mark@chromium.org7b245632013-09-25 21:16:00 +00001367 # Aligned with opening delimiter in a dictionary
1368 foo = {
1369 long_dictionary_key: value1 +
1370 value2,
1371 ...
1372 }
1373
apicard@google.comf900c2c2009-07-23 20:09:56 +00001374 # 4-space hanging indent; nothing on first line
1375 foo = long_function_name(
1376 var_one, var_two, var_three,
mark@chromium.org7b245632013-09-25 21:16:00 +00001377 var_four)
1378
1379 # 4-space hanging indent in a dictionary
1380 foo = {
1381 long_dictionary_key:
1382 long_dictionary_value,
1383 ...
1384 }</PRE></DIV>
mmentovai9ec7bd62009-12-03 22:25:38 +00001385<DIV class=""><PRE class="badcode">No: <span class="external"></span># Stuff on first line forbidden
apicard@google.comf900c2c2009-07-23 20:09:56 +00001386 <span class="external"></span>foo = long_function_name(var_one, var_two,
1387 <span class="external"></span> var_three, var_four)
1388
1389 <span class="external"></span># 2-space hanging indent forbidden
1390 <span class="external"></span>foo = long_function_name(
1391 <span class="external"></span> var_one, var_two, var_three,
mark@chromium.org7b245632013-09-25 21:16:00 +00001392 <span class="external"></span> var_four)
1393
1394 <span class="external"></span># No hanging indent in a dictionary
1395 <span class="external"></span>foo = {
1396 <span class="external"></span> long_dictionary_key:
1397 <span class="external"> </span>long_dictionary_value,
1398 <span class="external"> </span>...
1399 <span class="external"></span>}</PRE></DIV>
mmentovai9ec7bd62009-12-03 22:25:38 +00001400 </DIV></DIV>
1401 </DIV>
1402 <DIV class="">
1403<H3><A name="Blank_Lines" id="Blank_Lines">Blank Lines</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001404<SPAN class="link_button" id="link-Blank_Lines__button" name="link-Blank_Lines__button"><A href="?showone=Blank_Lines#Blank_Lines">
1405 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001406 </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 +00001407 <DIV style="display:inline;" class="">
apicard@google.com424ad342012-09-18 23:16:02 +00001408 Two blank lines between top-level definitions, one blank line
apicard@google.comf900c2c2009-07-23 20:09:56 +00001409 between method definitions.
mmentovai9ec7bd62009-12-03 22:25:38 +00001410 </DIV>
1411 <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 +00001412 <p>
1413 Two blank lines between top-level definitions, be they function
1414 or class definitions. One blank line between method definitions
1415 and between the <code>class</code> line and the first method.
1416 Use single blank lines as you judge appropriate within functions or
1417 methods.
1418 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001419 </DIV></DIV>
1420 </DIV>
1421 <DIV class="">
1422<H3><A name="Whitespace" id="Whitespace">Whitespace</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001423<SPAN class="link_button" id="link-Whitespace__button" name="link-Whitespace__button"><A href="?showone=Whitespace#Whitespace">
1424 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001425 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Whitespace')" name="Whitespace__button" id="Whitespace__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001426 <DIV style="display:inline;" class="">
apicard@google.com424ad342012-09-18 23:16:02 +00001427 Follow standard typographic rules for the use of spaces around
apicard@google.comf900c2c2009-07-23 20:09:56 +00001428 punctuation.
mmentovai9ec7bd62009-12-03 22:25:38 +00001429 </DIV>
1430 <DIV class=""><DIV class="stylepoint_body" name="Whitespace__body" id="Whitespace__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001431 <p>
1432 No whitespace inside parentheses, brackets or braces.
1433 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001434<DIV class=""><PRE>Yes: <span class="external"></span>spam(ham[1], {eggs: 2}, [])</PRE></DIV>
1435<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 +00001436 <p>
1437 No whitespace before a comma, semicolon, or colon. Do use
1438 whitespace after a comma, semicolon, or colon except at the end
1439 of the line.
1440 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001441<DIV class=""><PRE>Yes: <span class="external"></span>if x == 4:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001442 <span class="external"> </span>print x, y
mmentovai9ec7bd62009-12-03 22:25:38 +00001443 <span class="external"></span>x, y = y, x</PRE></DIV>
1444<DIV class=""><PRE class="badcode">No: <span class="external"></span>if x == 4 :
apicard@google.comf900c2c2009-07-23 20:09:56 +00001445 <span class="external"> </span>print x , y
mmentovai9ec7bd62009-12-03 22:25:38 +00001446 <span class="external"></span>x , y = y , x</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001447 <p>
1448 No whitespace before the open paren/bracket that starts an argument list,
1449 indexing or slicing.
1450 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001451 <DIV class=""><PRE>Yes: <span class="external"></span>spam(1)</PRE></DIV>
1452<DIV class=""><PRE class="badcode">No: <span class="external"></span>spam (1)</PRE></DIV>
1453<DIV class=""><PRE>Yes: <span class="external"></span>dict['key'] = list[index]</PRE></DIV>
1454<DIV class=""><PRE class="badcode">No: <span class="external"></span>dict ['key'] = list [index]</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001455
1456 <p>
1457 Surround binary operators with a single space on either side for
1458 assignment (<code>=</code>), comparisons (<code>==, &lt;, &gt;, !=,
1459 &lt;&gt;, &lt;=, &gt;=, in, not in, is, is not</code>), and Booleans
1460 (<code>and, or, not</code>). Use your better judgment for the
1461 insertion of spaces around arithmetic operators but always be
1462 consistent about whitespace on either side of a binary operator.
1463 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001464<DIV class=""><PRE>Yes: <span class="external"></span>x == 1</PRE></DIV>
1465<DIV class=""><PRE class="badcode">No: <span class="external"></span>x&lt;1</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001466 <p>
1467 Don't use spaces around the '=' sign when used to indicate a
1468 keyword argument or a default parameter value.
1469 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001470<DIV class=""><PRE>Yes: <span class="external"></span>def complex(real, imag=0.0): return magic(r=real, i=imag)</PRE></DIV>
1471<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 +00001472
1473 <p>
1474 Don't use spaces to vertically align tokens on consecutive lines, since it
1475 becomes a maintenance burden (applies to <code>:</code>, <code>#</code>,
1476 <code>=</code>, etc.):
1477 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001478<DIV class=""><PRE>Yes:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001479 foo = 1000 # comment
1480 long_name = 2 # comment that should not be aligned
1481
1482 dictionary = {
apicard@google.com424ad342012-09-18 23:16:02 +00001483 'foo': 1,
1484 'long_name': 2,
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001485 }</PRE></DIV>
mmentovai9ec7bd62009-12-03 22:25:38 +00001486<DIV class=""><PRE class="badcode">No:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001487 foo = 1000 # comment
1488 long_name = 2 # comment that should not be aligned
1489
1490 dictionary = {
apicard@google.com424ad342012-09-18 23:16:02 +00001491 'foo' : 1,
1492 'long_name': 2,
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001493 }</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001494
1495
mmentovai9ec7bd62009-12-03 22:25:38 +00001496 </DIV></DIV>
1497 </DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001498
mmentovaicd4ce0f2011-03-29 20:30:47 +00001499 <a name="Python_Interpreter"></a>
1500 <DIV class="">
1501<H3><A name="Shebang_Line" id="Shebang_Line">Shebang Line</A></H3>
1502<SPAN class="link_button" id="link-Shebang_Line__button" name="link-Shebang_Line__button"><A href="?showone=Shebang_Line#Shebang_Line">
1503 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001504 </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 +00001505 <DIV style="display:inline;" class="">
mark@chromium.orge33361f2011-11-04 16:55:22 +00001506 Most <code>.py</code> files do not need to start with a
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001507 <code>#!</code> line. Start the main file of a
1508 program with
1509 <code>#!/usr/bin/python</code> with an optional single digit
1510 <code>2</code> or <code>3</code> suffix per
1511 <a href="http://www.python.org/dev/peps/pep-0394/">PEP-394</a>.
mmentovaicd4ce0f2011-03-29 20:30:47 +00001512 </DIV>
1513 <DIV class=""><DIV class="stylepoint_body" name="Shebang_Line__body" id="Shebang_Line__body" style="display: none">
1514
1515 <p>
mark@chromium.orge33361f2011-11-04 16:55:22 +00001516 This line is used by the kernel to find the Python interpreter, but is
1517 ignored by Python when importing modules. It is only necessary on a
1518 file that will be executed directly.
mmentovaicd4ce0f2011-03-29 20:30:47 +00001519 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001520 </DIV></DIV>
1521 </DIV>
mmentovaicd4ce0f2011-03-29 20:30:47 +00001522
mmentovai9ec7bd62009-12-03 22:25:38 +00001523 <DIV class="">
1524<H3><A name="Comments" id="Comments">Comments</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001525<SPAN class="link_button" id="link-Comments__button" name="link-Comments__button"><A href="?showone=Comments#Comments">
1526 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001527 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Comments')" name="Comments__button" id="Comments__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001528 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001529 Be sure to use the right style for module, function, method and in-line
1530 comments.
mmentovai9ec7bd62009-12-03 22:25:38 +00001531 </DIV>
1532 <DIV class=""><DIV class="stylepoint_body" name="Comments__body" id="Comments__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001533
1534 <P class="">
1535<SPAN class="stylepoint_subsection">Doc Strings</SPAN>
1536
1537 <p>
1538 Python has a unique commenting style using doc strings. A doc
1539 string is a string that is the first statement in a package,
1540 module, class or function. These strings can be extracted
1541 automatically through the <code>__doc__</code> member of the
1542 object and are used by <code>pydoc</code>. (Try running
mark@chromium.org7b245632013-09-25 21:16:00 +00001543 <code>pydoc</code> on your module to see how it looks.) We
1544 always use the three double-quote <code>"""</code> format for doc strings
1545 (per <a href="http://www.python.org/dev/peps/pep-0257/">PEP 257</a>).
1546 A doc string should be organized as a
apicard@google.comf900c2c2009-07-23 20:09:56 +00001547 summary line (one physical line) terminated by a period,
1548 question mark, or exclamation point, followed by a blank line,
1549 followed by the rest of the doc string starting at the same
1550 cursor position as the first quote of the first line. There are
1551 more formatting guidelines for doc strings below.
1552 </p>
1553
1554 </P>
1555 <P class="">
1556<SPAN class="stylepoint_subsection">Modules</SPAN>
1557
1558
1559
1560 <p>
apicard@google.com424ad342012-09-18 23:16:02 +00001561 Every file should contain license boilerplate.
1562 Choose the appropriate boilerplate for the license used by the project
1563 (for example, Apache 2.0, BSD, LGPL, GPL)
apicard@google.comf900c2c2009-07-23 20:09:56 +00001564 </p>
1565 </P>
1566 <P class="">
1567<SPAN class="stylepoint_subsection">Functions and Methods</SPAN>
1568
1569 <p>
mark@chromium.orge33361f2011-11-04 16:55:22 +00001570 As used in this section "function" applies to methods, function, and
1571 generators.
apicard@google.comf900c2c2009-07-23 20:09:56 +00001572 </p>
1573
mark@chromium.orge33361f2011-11-04 16:55:22 +00001574 <p>
1575 A function must have a docstring, unless it meets all of the following
1576 criteria:
1577 <ul>
1578 <li>not externally visible</li>
1579 <li>very short</li>
1580 <li>obvious</li>
1581 </ul>
1582 </p>
1583
1584 <p>
1585 A docstring should give enough information to write a call to the function
1586 without reading the function's code. A docstring should describe the
1587 function's calling syntax and its semantics, not its implementation. For
1588 tricky code, comments alongside the code are more appropriate than using
1589 docstrings.
1590 </p>
1591
1592 <p>
1593 Certain aspects of a function should be documented in special sections,
1594 listed below. Each section begins with a heading line, which ends with a
1595 colon. Sections should be indented two spaces, except for the heading.
1596 </p>
1597
1598 <dl>
1599 <dt>Args:</dt>
1600 <dd>
1601 List each parameter by name. A description should follow the name, and
1602 be separated by a colon and a space. If the description is too long to
1603 fit on a single 80-character line, use a hanging indent of 2 or 4 spaces
1604 (be consistent with the rest of the file).
1605
1606 <p>
1607 The description should mention required type(s) and the meaning of
1608 the argument.
1609 </p>
1610
1611 <p>
1612 If a function accepts *foo (variable length argument lists) and/or
1613 **bar (arbitrary keyword arguments), they should be listed as *foo and
1614 **bar.
1615 </p>
1616 </dd>
1617
1618 <dt>Returns: (or Yields: for generators)</dt>
1619 <dd>
1620 Describe the type and semantics of the return value. If the function
1621 only returns None, this section is not required.
1622 </dd>
1623
1624 <dt>Raises:</dt>
1625 <dd>
1626 List all exceptions that are relevant to the interface.
1627 </dd>
1628 </dl>
1629
mmentovai9ec7bd62009-12-03 22:25:38 +00001630 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001631<span class="external"></span>def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
1632 <span class="external"> </span>"""Fetches rows from a Bigtable.
1633
1634 <span class="external"> </span>Retrieves rows pertaining to the given keys from the Table instance
1635 <span class="external"> </span>represented by big_table. Silly things may happen if
1636 <span class="external"> </span>other_silly_variable is not None.
1637
1638 <span class="external"> </span>Args:
1639 <span class="external"> </span>big_table: An open Bigtable Table instance.
1640 <span class="external"> </span>keys: A sequence of strings representing the key of each table row
1641 <span class="external"> </span> to fetch.
1642 <span class="external"> </span>other_silly_variable: Another optional variable, that has a much
1643 <span class="external"> </span> longer name than the other args, and which does nothing.
1644
1645 <span class="external"> </span>Returns:
1646 <span class="external"> </span>A dict mapping keys to the corresponding table row data
1647 <span class="external"> </span>fetched. Each row is represented as a tuple of strings. For
1648 <span class="external"> </span>example:
1649
1650 <span class="external"> </span>{'Serak': ('Rigel VII', 'Preparer'),
1651 <span class="external"> </span> 'Zim': ('Irk', 'Invader'),
1652 <span class="external"> </span> 'Lrrr': ('Omicron Persei 8', 'Emperor')}
1653
1654 <span class="external"> </span>If a key from the keys argument is missing from the dictionary,
1655 <span class="external"> </span>then that row was not found in the table.
1656
1657 <span class="external"> </span>Raises:
1658 <span class="external"> </span>IOError: An error occurred accessing the bigtable.Table object.
1659 <span class="external"> </span>"""
1660 <span class="external"> </span>pass
1661<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001662</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001663 </P>
1664 <P class="">
1665<SPAN class="stylepoint_subsection">Classes</SPAN>
1666
1667 <p>
1668 Classes should have a doc string below the class definition describing
1669 the class. If your class has public attributes, they should be documented
1670 here in an Attributes section and follow the same formatting as a
1671 function's Args section.
1672 </p>
1673
mmentovai9ec7bd62009-12-03 22:25:38 +00001674 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001675<span class="external"></span>class SampleClass(object):
1676 <span class="external"> </span>"""Summary of class here.
1677
1678 <span class="external"> </span>Longer class information....
1679 <span class="external"> </span>Longer class information....
1680
1681 <span class="external"> </span>Attributes:
1682 <span class="external"> </span>likes_spam: A boolean indicating if we like SPAM or not.
1683 <span class="external"> </span>eggs: An integer count of the eggs we have laid.
1684 <span class="external"> </span>"""
1685
1686 <span class="external"> </span>def __init__(self, likes_spam=False):
1687 <span class="external"> </span>"""Inits SampleClass with blah."""
1688 <span class="external"> </span>self.likes_spam = likes_spam
1689 <span class="external"> </span>self.eggs = 0
1690
1691 <span class="external"> </span>def public_method(self):
1692 <span class="external"> </span>"""Performs operation blah."""
1693<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001694</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001695
1696 </P>
1697 <P class="">
1698<SPAN class="stylepoint_subsection">Block and Inline Comments</SPAN>
1699
1700 <p>
1701 The final place to have comments is in tricky parts of the
apicard@google.com424ad342012-09-18 23:16:02 +00001702 code. If you're going to have to explain it at the next
1703 <a HREF="http://en.wikipedia.org/wiki/Code_review">code review</a>,
1704 you should comment it now. Complicated operations get a few lines of
apicard@google.comf900c2c2009-07-23 20:09:56 +00001705 comments before the operations
1706 commence. Non-obvious ones get comments at the end of the line.
1707 </p>
1708
mmentovai9ec7bd62009-12-03 22:25:38 +00001709 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001710<span class="external"></span># We use a weighted dictionary search to find out where i is in
1711<span class="external"></span># the array. We extrapolate position based on the largest num
1712<span class="external"></span># in the array and the array size and then do binary search to
1713<span class="external"></span># get the exact number.
1714
1715<span class="external"></span>if i &amp; (i-1) == 0: # true iff i is a power of 2
1716<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001717</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001718
1719 <p>
1720 To improve legibility, these comments should be at least 2 spaces away
1721 from the code.
1722 </p>
1723
1724 <p>
1725 On the other hand, never describe the code. Assume the person
1726 reading the code knows Python (though not what you're trying to
1727 do) better than you do.
1728 </p>
1729
mmentovai9ec7bd62009-12-03 22:25:38 +00001730 <DIV class=""><PRE class="badcode">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001731<span class="external"></span># BAD COMMENT: Now go through the b array and make sure whenever i occurs
1732<span class="external"></span># the next element is i+1
1733<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001734</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001735
1736 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001737 </DIV></DIV>
1738 </DIV>
1739 <DIV class="">
1740<H3><A name="Classes" id="Classes">Classes</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001741<SPAN class="link_button" id="link-Classes__button" name="link-Classes__button"><A href="?showone=Classes#Classes">
1742 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001743 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Classes')" name="Classes__button" id="Classes__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001744 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001745 If a class inherits from no other base classes, explicitly inherit
1746 from <code>object</code>. This also applies to nested classes.
mmentovai9ec7bd62009-12-03 22:25:38 +00001747 </DIV>
1748 <DIV class=""><DIV class="stylepoint_body" name="Classes__body" id="Classes__body" style="display: none">
mmentovai9ec7bd62009-12-03 22:25:38 +00001749 <DIV class=""><PRE>Yes: <span class="external"></span>class SampleClass(object):
apicard@google.comf900c2c2009-07-23 20:09:56 +00001750 <span class="external"> </span>pass
1751
1752
1753 <span class="external"></span>class OuterClass(object):
1754
1755 <span class="external"> </span>class InnerClass(object):
1756 <span class="external"> </span>pass
1757
1758
1759 <span class="external"></span>class ChildClass(ParentClass):
1760 <span class="external"> </span>"""Explicitly inherits from another class already."""
1761<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001762</PRE></DIV>
apicard@google.com424ad342012-09-18 23:16:02 +00001763 <DIV class=""><PRE class="badcode">No: <span class="external"></span>class SampleClass:
1764 <span class="external"> </span>pass
apicard@google.comf900c2c2009-07-23 20:09:56 +00001765
apicard@google.com424ad342012-09-18 23:16:02 +00001766
1767 <span class="external"></span>class OuterClass:
1768
1769 <span class="external"> </span>class InnerClass:
1770 <span class="external"> </span>pass
1771<span class="external"></span>
1772</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001773 <p>Inheriting from <code>object</code> is needed to make properties work
apicard@google.com424ad342012-09-18 23:16:02 +00001774 properly, and it will protect your code from one particular potential
apicard@google.comf900c2c2009-07-23 20:09:56 +00001775 incompatibility with Python 3000. It also defines
1776 special methods that implement the default semantics of objects including
1777 <code>__new__</code>, <code>__init__</code>, <code>__delattr__</code>,
1778 <code>__getattribute__</code>, <code>__setattr__</code>,
1779 <code>__hash__</code>, <code>__repr__</code>, and <code>__str__</code>.
1780 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001781 </DIV></DIV>
1782 </DIV>
1783 <DIV class="">
1784<H3><A name="Strings" id="Strings">Strings</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001785<SPAN class="link_button" id="link-Strings__button" name="link-Strings__button"><A href="?showone=Strings#Strings">
1786 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001787 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Strings')" name="Strings__button" id="Strings__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001788 <DIV style="display:inline;" class="">
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001789 Use the <code>format</code> method or the <code>%</code> operator for
1790 formatting strings, even when the parameters are all strings. Use your
1791 best judgement to decide between <code>+</code> and <code>%</code>
1792 (or <code>format</code>) though.
mmentovai9ec7bd62009-12-03 22:25:38 +00001793 </DIV>
1794 <DIV class=""><DIV class="stylepoint_body" name="Strings__body" id="Strings__body" style="display: none">
apicard@google.com424ad342012-09-18 23:16:02 +00001795
mmentovai9ec7bd62009-12-03 22:25:38 +00001796<DIV class=""><PRE>Yes: <span class="external"></span>x = a + b
apicard@google.comf900c2c2009-07-23 20:09:56 +00001797 <span class="external"></span>x = '%s, %s!' % (imperative, expletive)
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001798 <span class="external"></span>x = '{}, {}!'.format(imperative, expletive)
1799 <span class="external"></span>x = 'name: %s; score: %d' % (name, n)
1800 <span class="external"></span>x = 'name: {}; score: {}'.format(name, n)</PRE></DIV>
apicard@google.com424ad342012-09-18 23:16:02 +00001801<DIV class=""><PRE class="badcode">No: <span class="external"></span>x = '%s%s' % (a, b) # use + in this case
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001802 <span class="external"></span>x = '{}{}'.format(a, b) # use + in this case
apicard@google.com424ad342012-09-18 23:16:02 +00001803 <span class="external"></span>x = imperative + ', ' + expletive + '!'
1804 <span class="external"></span>x = 'name: ' + name + '; score: ' + str(n)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001805
1806 <p>
1807 Avoid using the <code>+</code> and <code>+=</code> operators to
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001808 accumulate a string within a loop. Since strings are immutable, this
apicard@google.comf900c2c2009-07-23 20:09:56 +00001809 creates unnecessary temporary objects and results in quadratic rather
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001810 than linear running time. Instead, add each substring to a list
1811 and <code>''.join</code> the list after the loop terminates (or, write
1812 each substring to a <code>io.BytesIO</code> buffer).
apicard@google.comf900c2c2009-07-23 20:09:56 +00001813 </p>
1814
mmentovai9ec7bd62009-12-03 22:25:38 +00001815<DIV class=""><PRE>Yes: <span class="external"></span>items = ['&lt;table&gt;']
apicard@google.comf900c2c2009-07-23 20:09:56 +00001816 <span class="external"></span>for last_name, first_name in employee_list:
1817 <span class="external"> </span>items.append('&lt;tr&gt;&lt;td&gt;%s, %s&lt;/td&gt;&lt;/tr&gt;' % (last_name, first_name))
1818 <span class="external"></span>items.append('&lt;/table&gt;')
mmentovai9ec7bd62009-12-03 22:25:38 +00001819 <span class="external"></span>employee_table = ''.join(items)</PRE></DIV>
apicard@google.com424ad342012-09-18 23:16:02 +00001820<DIV class=""><PRE class="badcode">No: <span class="external"></span>employee_table = '&lt;table&gt;'
1821 <span class="external"></span>for last_name, first_name in employee_list:
1822 <span class="external"> </span>employee_table += '&lt;tr&gt;&lt;td&gt;%s, %s&lt;/td&gt;&lt;/tr&gt;' % (last_name, first_name)
1823 <span class="external"></span>employee_table += '&lt;/table&gt;'</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001824
1825 <p>
mark@chromium.org7b245632013-09-25 21:16:00 +00001826 Be consistent with your choice of string quote character within a file.
1827 Pick <code>'</code> or <code>"</code> and stick with it.
1828 It is okay to use the other quote character on a string to avoid the
1829 need to <code>\</code> escape within the string.
1830 GPyLint enforces this.
1831 </p>
1832
1833<DIV class=""><PRE>Ye<span class="external"></span>s:
1834 <span class="external"></span>Python('Why are you hiding your eyes?')
1835 <span class="external"></span>Gollum("I'm scared of lint errors.")
1836 <span class="external"></span>Narrator('"Good!" thought a happy Python reviewer.')</PRE></DIV>
1837<DIV class=""><PRE class="badcode">No<span class="external"></span>:
1838 <span class="external"></span>Python("Why are you hiding your eyes?")
1839 <span class="external"></span>Gollum('The lint. It burns. It burns us.')
1840 <span class="external"></span>Gollum("Always the great lint. Watching. Watching.")</PRE></DIV>
1841
1842 <p>
1843 Prefer <code>"""</code> for multi-line strings rather than
1844 <code>'''</code>. Projects may choose to use <code>'''</code> for
1845 all non-docstring multi-line strings if and only if they also use
1846 <code>'</code> for regular strings.
1847 Doc strings must use <code>"""</code> regardless.
1848 Note that it is often cleaner to
apicard@google.comf900c2c2009-07-23 20:09:56 +00001849 use implicit line joining since multi-line strings do
1850 not flow with the indentation of the rest of the program:
1851 </p>
1852
apicard@google.com424ad342012-09-18 23:16:02 +00001853<DIV class=""><PRE>Ye<span class="external"></span>s:
1854 <span class="external"></span>print ("This is much nicer.\n"
1855 <span class="external"></span> "Do it this way.\n")</PRE></DIV>
1856<DIV class=""><PRE class="badcode"> No<span class="external"></span>:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001857 <span class="external"></span>print """This is pretty ugly.
1858Don'<span class="external"></span>t do this.
1859"""<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001860</PRE></DIV>
apicard@google.com424ad342012-09-18 23:16:02 +00001861
1862 </DIV></DIV>
1863 </DIV>
1864 <DIV class="">
1865<H3><A name="Files_and_Sockets" id="Files_and_Sockets">Files and Sockets</A></H3>
1866<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">
1867 link
1868 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Files_and_Sockets')" name="Files_and_Sockets__button" id="Files_and_Sockets__button"></SPAN>
1869 <DIV style="display:inline;" class="">
1870 Explicitly close files and sockets when done with them.
1871 </DIV>
1872 <DIV class=""><DIV class="stylepoint_body" name="Files_and_Sockets__body" id="Files_and_Sockets__body" style="display: none">
1873 <p>
1874 Leaving files, sockets or other file-like objects open unnecessarily
1875 has many downsides, including:
1876
1877 <ul>
1878 <li>They may consume limited system resources, such as file
1879 descriptors. Code that deals with many such objects may exhaust
1880 those resources unnecessarily if they're not returned to the
1881 system promptly after use.</li>
1882 <li>Holding files open may prevent other actions being performed on
1883 them, such as moves or deletion.</li>
1884 <li>Files and sockets that are shared throughout a program may
1885 inadvertantly be read from or written to after logically being
1886 closed. If they are actually closed, attempts to read or write
1887 from them will throw exceptions, making the problem known
1888 sooner.</li>
1889 </ul>
1890 </p>
1891
1892 <p>
1893 Furthermore, while files and sockets are automatically closed when the
1894 file object is destructed, tying the life-time of the file object to
1895 the state of the file is poor practice, for several reasons:
1896
1897 <ul>
1898 <li>There are no guarantees as to when the runtime will actually run
1899 the file's destructor. Different Python implementations use
1900 different memory management techniques, such as delayed Garbage
1901 Collection, which may increase the object's lifetime arbitrarily
1902 and indefinitely.</li>
1903 <li>Unexpected references to the file may keep it around longer than
1904 intended (e.g. in tracebacks of exceptions, inside globals,
1905 etc).</li>
1906 </ul>
1907 </p>
1908
1909 <p>
1910 The preferred way to manage files is using the <a HREF="http://docs.python.org/reference/compound_stmts.html#the-with-statement">
1911 "with" statement</a>:
1912 </p>
1913
1914<DIV class=""><PRE>
1915<span class="external"></span>with open("hello.txt") as hello_file:
1916 <span class="external"> </span>for line in hello_file:
1917 <span class="external"> </span>print line</PRE></DIV>
1918
1919 <p>
1920 For file-like objects that do not support the "with" statement, use
1921 contextlib.closing():
1922 </p>
1923
1924<DIV class=""><PRE>
1925<span class="external"></span>import contextlib
1926
1927<span class="external"></span>with contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page:
1928 <span class="external"> </span>for line in front_page:
1929 <span class="external"> </span>print line</PRE></DIV>
1930
1931 <p>
1932 Legacy AppEngine code using Python 2.5 may enable the "with" statement
1933 using "from __future__ import with_statement".
1934 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001935 </DIV></DIV>
1936 </DIV>
1937 <DIV class="">
1938<H3><A name="TODO_Comments" id="TODO_Comments">TODO Comments</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001939<SPAN class="link_button" id="link-TODO_Comments__button" name="link-TODO_Comments__button"><A href="?showone=TODO_Comments#TODO_Comments">
1940 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001941 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('TODO_Comments')" name="TODO_Comments__button" id="TODO_Comments__button"></SPAN>
1942 <DIV style="display:inline;" class="">
1943 Use <code>TODO</code> comments for code that is temporary, a
1944 short-term solution, or good-enough but not perfect.
1945 </DIV>
1946 <DIV class=""><DIV class="stylepoint_body" name="TODO_Comments__body" id="TODO_Comments__body" style="display: none">
1947 <p>
1948 <code>TODO</code>s should include the string <code>TODO</code> in
1949 all caps, followed by the
1950
1951 name, e-mail address, or other
1952 identifier
1953 of the person who can best provide context about the problem
1954 referenced by the <code>TODO</code>,
1955 in parentheses. A colon is optional. A comment explaining what there
1956 is to do is required. The main purpose is to have
1957 a consistent <code>TODO</code> format that can be searched to find the
1958 person who can provide more details upon request. A
1959 <code>TODO</code> is not a commitment that the person referenced
1960 will fix the problem. Thus when you create a <code>TODO</code>, it is
1961 almost always your
1962
1963 name
1964 that is given.
1965 </p>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001966
mark@chromium.orge33361f2011-11-04 16:55:22 +00001967 <DIV class=""><PRE># TODO(kl@gmail.com): Use a "*" here for string repetition.
1968# TODO(Zeke) Change this to use relations.</PRE></DIV>
1969 <p>
1970 If your <code>TODO</code> is of the form "At a future date do
1971 something" make sure that you either include a very specific
1972 date ("Fix by November 2009") or a very specific event
1973 ("Remove this code when all clients can handle XML responses.").
1974 </p>
1975 </DIV></DIV>
1976 </DIV>
mmentovai9ec7bd62009-12-03 22:25:38 +00001977 <DIV class="">
1978<H3><A name="Imports_formatting" id="Imports_formatting">Imports formatting</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001979<SPAN class="link_button" id="link-Imports_formatting__button" name="link-Imports_formatting__button"><A href="?showone=Imports_formatting#Imports_formatting">
1980 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001981 </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 +00001982 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001983 Imports should be on separate lines.
mmentovai9ec7bd62009-12-03 22:25:38 +00001984 </DIV>
1985 <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 +00001986 <p>
1987 E.g.:
1988 </p>
1989
mmentovai9ec7bd62009-12-03 22:25:38 +00001990<DIV class=""><PRE>Yes: <span class="external"></span>import os
1991 <span class="external"></span>import sys</PRE></DIV>
1992<DIV class=""><PRE class="badcode">No: <span class="external"></span>import os, sys</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001993 <p>
1994 Imports are always put at the top of the file, just after any
1995 module comments and doc strings and before module globals and
1996 constants. Imports should be grouped with the order being most generic
1997 to least generic:
1998 </p>
1999 <ul>
2000 <li>standard library imports</li>
2001 <li>third-party imports</li>
2002
2003 <li>application-specific imports</li>
2004 </ul>
2005 <p>
2006 Within each grouping, imports should be sorted lexicographically,
2007 ignoring case, according to each module's full package path.
2008 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00002009 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002010<span class="external"></span>import foo
2011<span class="external"></span>from foo import bar
2012<span class="external"></span>from foo.bar import baz
2013<span class="external"></span>from foo.bar import Quux
mmentovai9ec7bd62009-12-03 22:25:38 +00002014<span class="external"></span>from Foob import ar</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002015
2016
mmentovai9ec7bd62009-12-03 22:25:38 +00002017
2018 </DIV></DIV>
2019 </DIV>
2020 <DIV class="">
2021<H3><A name="Statements" id="Statements">Statements</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00002022<SPAN class="link_button" id="link-Statements__button" name="link-Statements__button"><A href="?showone=Statements#Statements">
2023 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00002024 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Statements')" name="Statements__button" id="Statements__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00002025 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00002026 Generally only one statement per line.
mmentovai9ec7bd62009-12-03 22:25:38 +00002027 </DIV>
2028 <DIV class=""><DIV class="stylepoint_body" name="Statements__body" id="Statements__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00002029 <p>
2030 However, you may put the
2031 result of a test on the same line as the test only if the entire
2032 statement fits on one line. In particular, you can never do so
2033 with <code>try</code>/<code>except</code> since the
2034 <code>try</code> and <code>except</code> can't both fit on the
2035 same line, and you can only do so with an <code>if</code> if
2036 there is no <code>else</code>.
2037 </p>
2038
mmentovai9ec7bd62009-12-03 22:25:38 +00002039 <DIV class=""><PRE>Ye<span class="external"></span>s:
apicard@google.comf900c2c2009-07-23 20:09:56 +00002040
mmentovai9ec7bd62009-12-03 22:25:38 +00002041 <span class="external"></span>if foo: bar(foo)</PRE></DIV>
2042<DIV class=""><PRE class="badcode">No<span class="external"></span>:
apicard@google.comf900c2c2009-07-23 20:09:56 +00002043
2044 <span class="external"></span>if foo: bar(foo)
2045 <span class="external"></span>else: baz(foo)
2046
2047 <span class="external"></span>try: bar(foo)
2048 <span class="external"></span>except ValueError: baz(foo)
2049
2050 <span class="external"></span>try:
2051 <span class="external"> </span>bar(foo)
2052 <span class="external"></span>except ValueError: baz(foo)
2053<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00002054</PRE></DIV>
2055 </DIV></DIV>
2056 </DIV>
2057 <DIV class="">
2058<H3><A name="Access_Control" id="Access_Control">Access Control</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00002059<SPAN class="link_button" id="link-Access_Control__button" name="link-Access_Control__button"><A href="?showone=Access_Control#Access_Control">
2060 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00002061 </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 +00002062 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00002063 If an accessor function would be trivial you should use public variables
apicard@google.com424ad342012-09-18 23:16:02 +00002064 instead of accessor functions to avoid the extra cost of function
2065 calls in Python. When more functionality is added you can use
apicard@google.comf900c2c2009-07-23 20:09:56 +00002066 <code>property</code> to keep the syntax consistent.
mmentovai9ec7bd62009-12-03 22:25:38 +00002067 </DIV>
2068 <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 +00002069 <p>
2070 On the other hand, if access is more complex, or the cost of accessing
2071 the variable is significant, you should use function calls (following the
2072 <a HREF="#naming">Naming</a> guidelines) such as <code>get_foo()</code>
2073 and <code>set_foo()</code>. If the past behavior allowed access through a
2074 property, do not bind the new accessor functions to the property. Any
2075 code still attempting to access the variable by the old method should
2076 break visibly so they are made aware of the change in complexity.
2077 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00002078 </DIV></DIV>
2079 </DIV>
2080 <DIV class="">
2081<H3><A name="Naming" id="Naming">Naming</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00002082<SPAN class="link_button" id="link-Naming__button" name="link-Naming__button"><A href="?showone=Naming#Naming">
2083 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00002084 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Naming')" name="Naming__button" id="Naming__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00002085 <DIV style="display:inline;" class="">
mark@chromium.orge33361f2011-11-04 16:55:22 +00002086 <code>module_name, package_name, ClassName,
2087 method_name, ExceptionName,
2088 function_name, GLOBAL_CONSTANT_NAME,
2089 global_var_name, instance_var_name, function_parameter_name,
2090 local_var_name.</code>
mmentovai9ec7bd62009-12-03 22:25:38 +00002091 </DIV>
2092 <DIV class=""><DIV class="stylepoint_body" name="Naming__body" id="Naming__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00002093 <P class="">
2094<SPAN class="stylepoint_subsection">Names to Avoid</SPAN>
2095
2096 <ul>
2097 <li>single character names except for counters or iterators</li>
2098 <li>dashes (<code>-</code>) in any package/module name</li>
2099 <li>
apicard@google.com424ad342012-09-18 23:16:02 +00002100<code>__double_leading_and_trailing_underscore__</code> names
apicard@google.comf900c2c2009-07-23 20:09:56 +00002101 (reserved by Python)</li>
2102 </ul>
2103
2104 </P>
2105 <P class="">
2106<SPAN class="stylepoint_subsection">Naming Convention</SPAN>
2107
2108 <ul>
2109 <li>
2110 "Internal" means internal to a module or protected
2111 or private within a class.</li>
2112 <li>
2113 Prepending a single underscore (<code>_</code>) has some
2114 support for protecting module variables and functions (not included
2115 with <code>import * from</code>). Prepending a double underscore
2116 (<code>__</code>) to an instance variable or method
2117 effectively serves to make the variable or method private to its class
2118 (using name mangling).</li>
2119 <li>
apicard@google.com424ad342012-09-18 23:16:02 +00002120 Place related classes and top-level functions together in a
apicard@google.comf900c2c2009-07-23 20:09:56 +00002121 module. Unlike Java,
2122 there is no need to limit yourself to one class per module.</li>
2123 <li>
2124 Use CapWords for class names, but lower_with_under.py for module names.
2125 Although there are many existing modules named CapWords.py, this is now
apicard@google.com424ad342012-09-18 23:16:02 +00002126 discouraged because it's confusing when the module happens to be
2127 named after a class. ("wait -- did I write
apicard@google.comf900c2c2009-07-23 20:09:56 +00002128 <code>import StringIO</code> or <code>from StringIO import
2129 StringIO</code>?")</li>
2130 </ul>
2131
2132 </P>
2133 <P class="">
2134<SPAN class="stylepoint_subsection">Guidelines derived from Guido's Recommendations</SPAN>
2135
2136 <table rules="all" border="1" cellspacing="2" cellpadding="2">
2137
2138 <tr>
2139 <th>Type</th>
2140 <th>Public</th>
2141 <th>Internal</th>
2142 </tr>
2143
2144
2145
2146 <tr>
2147 <td>Packages</td>
2148 <td><code>lower_with_under</code></td>
2149 <td></td>
2150 </tr>
2151
2152 <tr>
2153 <td>Modules</td>
2154 <td><code>lower_with_under</code></td>
2155 <td><code>_lower_with_under</code></td>
2156 </tr>
2157
2158 <tr>
2159 <td>Classes</td>
2160 <td><code>CapWords</code></td>
2161 <td><code>_CapWords</code></td>
2162 </tr>
2163
2164 <tr>
2165 <td>Exceptions</td>
2166 <td><code>CapWords</code></td>
2167 <td></td>
2168 </tr>
2169
2170
2171
2172 <tr>
2173 <td>Functions</td>
2174 <td><code>lower_with_under()</code></td>
2175 <td><code>_lower_with_under()</code></td>
2176 </tr>
2177
2178 <tr>
2179 <td>Global/Class Constants</td>
2180 <td><code>CAPS_WITH_UNDER</code></td>
2181 <td><code>_CAPS_WITH_UNDER</code></td>
2182 </tr>
2183
2184 <tr>
2185 <td>Global/Class Variables</td>
2186 <td><code>lower_with_under</code></td>
2187 <td><code>_lower_with_under</code></td>
2188 </tr>
2189
2190 <tr>
2191 <td>Instance Variables</td>
2192 <td><code>lower_with_under</code></td>
2193 <td><code>_lower_with_under (protected) or __lower_with_under (private)</code></td>
2194 </tr>
2195
2196
2197
2198 <tr>
2199 <td>Method Names</td>
2200 <td><code>lower_with_under()</code></td>
2201 <td><code>_lower_with_under() (protected) or __lower_with_under() (private)</code></td>
2202 </tr>
2203
2204 <tr>
2205 <td>Function/Method Parameters</td>
2206 <td><code>lower_with_under</code></td>
2207 <td></td>
2208 </tr>
2209
2210 <tr>
2211 <td>Local Variables</td>
2212 <td><code>lower_with_under</code></td>
2213 <td></td>
2214 </tr>
2215
2216
2217 </table>
2218
2219
2220 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00002221 </DIV></DIV>
2222 </DIV>
2223 <DIV class="">
2224<H3><A name="Main" id="Main">Main</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00002225<SPAN class="link_button" id="link-Main__button" name="link-Main__button"><A href="?showone=Main#Main">
2226 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00002227 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Main')" name="Main__button" id="Main__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00002228 <DIV style="display:inline;" class="">
apicard@google.com424ad342012-09-18 23:16:02 +00002229 Even a file meant to be used as a script should be importable and a
2230 mere import should not have the side effect of executing the script's
2231 main functionality. The main functionality should be in a main()
apicard@google.comf900c2c2009-07-23 20:09:56 +00002232 function.
mmentovai9ec7bd62009-12-03 22:25:38 +00002233 </DIV>
2234 <DIV class=""><DIV class="stylepoint_body" name="Main__body" id="Main__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00002235 <p>
2236 In Python,
mark@chromium.org7b245632013-09-25 21:16:00 +00002237 <code>pydoc</code> as well as unit tests
apicard@google.comf900c2c2009-07-23 20:09:56 +00002238 require modules to be importable. Your code should always check
2239 <code>if __name__ == '__main__'</code> before executing your
2240 main program so that the main program is not executed when the
apicard@google.com424ad342012-09-18 23:16:02 +00002241 module is imported.
apicard@google.comf900c2c2009-07-23 20:09:56 +00002242
2243 </p>
2244
2245
2246
2247
2248
2249
2250
mmentovai9ec7bd62009-12-03 22:25:38 +00002251 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002252<span class="external"></span>def main():
2253 <span class="external"> </span>...
2254
2255<span class="external"></span>if __name__ == '__main__':
2256 <span class="external"> </span>main()
2257<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00002258</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002259
2260 <p>
2261 All code at the top level will be executed when the module is
2262 imported. Be careful not to call functions, create objects, or
2263 perform other operations that should not be executed when the
mark@chromium.org7b245632013-09-25 21:16:00 +00002264 file is being <code>pydoc</code>ed.
apicard@google.comf900c2c2009-07-23 20:09:56 +00002265 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00002266 </DIV></DIV>
2267 </DIV>
2268 </DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002269
2270<H2>Parting Words</H2>
2271 <p>
2272 <em>BE CONSISTENT</em>.
2273 </p>
2274
2275 <p>
2276 If you're editing code, take a few minutes to look at the code
2277 around you and determine its style. If they use spaces around
2278 all their arithmetic operators, you should too. If their
2279 comments have little boxes of hash marks around them, make your
2280 comments have little boxes of hash marks around them too.
2281 </p>
2282
2283 <p>
2284 The point of having style guidelines is to have a common vocabulary
2285 of coding so people can concentrate on what you're saying rather
2286 than on how you're saying it. We present global style rules here so
2287 people know the vocabulary, but local style is also important. If
2288 code you add to a file looks drastically different from the existing
2289 code around it, it throws readers out of their rhythm when they go to
2290 read it. Avoid this.
2291 </p>
2292
2293
2294
2295<p align="right">
mark@chromium.org7b245632013-09-25 21:16:00 +00002296Revision 2.59
apicard@google.comf900c2c2009-07-23 20:09:56 +00002297</p>
2298
2299
2300<address>
2301 Amit Patel<br>
2302 Antoine Picard<br>
2303 Eugene Jhong<br>
mark@chromium.org7b245632013-09-25 21:16:00 +00002304 Gregory P. Smith<br>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002305 Jeremy Hylton<br>
2306 Matt Smart<br>
2307 Mike Shields<br>
mark@chromium.org7b245632013-09-25 21:16:00 +00002308 Shane Liebling<br>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002309</address>
2310</BODY>
2311</HTML>