blob: 31fc512d409802a7574b84d6872886e0e5153933 [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.org5684bbc2013-07-12 18:53:13 +0000139 Revision 2.54
apicard@google.comf900c2c2009-07-23 20:09:56 +0000140 </p>
141
142 <address>
143 Amit Patel<br>
144 Antoine Picard<br>
145 Eugene Jhong<br>
146 Jeremy Hylton<br>
147 Matt Smart<br>
148 Mike Shields<br>
149 </address>
150 <DIV style="margin-left: 50%; font-size: 75%;">
151<P>
152 Each style point has a summary for which additional information is available
153 by toggling the accompanying arrow button that looks this way:
mmentovai8411f0c2010-08-04 17:46:16 +0000154 <SPAN class="showhide_button" style="margin-left: 0; float: none"></SPAN>.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000155 You may toggle all summaries with the big arrow button:
156 </P>
157<DIV style=" font-size: larger; margin-left: +2em;">
mmentovai8411f0c2010-08-04 17:46:16 +0000158<SPAN class="showhide_button" style="font-size: 180%; float: none" onclick="javascript:ShowHideAll()" name="show_hide_all_button" id="show_hide_all_button"></SPAN>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000159 Toggle all summaries
160 </DIV>
161</DIV>
162<DIV class="toc">
163<DIV class="toc_title">Table of Contents</DIV>
164<TABLE>
165<TR valign="top" class="">
166<TD><DIV class="toc_category"><A href="#Python_Language_Rules">Python Language Rules</A></DIV></TD>
167<TD><DIV class="toc_stylepoint">
apicard@google.com424ad342012-09-18 23:16:02 +0000168<SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#pychecker">pychecker</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Imports">Imports</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Packages">Packages</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Exceptions">Exceptions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Global_variables">Global variables</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Nested/Local/Inner_Classes_and_Functions">Nested/Local/Inner Classes and Functions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#List_Comprehensions">List Comprehensions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Default_Iterators_and_Operators">Default Iterators and Operators</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Generators">Generators</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Lambda_Functions">Lambda Functions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Conditional_Expressions">Conditional Expressions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Default_Argument_Values">Default Argument Values</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Properties">Properties</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#True/False_evaluations">True/False evaluations</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Deprecated_Language_Features">Deprecated Language Features</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Lexical_Scoping">Lexical Scoping</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Function_and_Method_Decorators">Function and Method Decorators</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Threading">Threading</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Power_Features">Power Features</A></SPAN> </DIV></TD>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000169</TR>
170<TR valign="top" class="">
171<TD><DIV class="toc_category"><A href="#Python_Style_Rules">Python Style Rules</A></DIV></TD>
172<TD><DIV class="toc_stylepoint">
apicard@google.com424ad342012-09-18 23:16:02 +0000173<SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Semicolons">Semicolons</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Line_length">Line length</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Parentheses">Parentheses</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Indentation">Indentation</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Blank_Lines">Blank Lines</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Whitespace">Whitespace</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Shebang_Line">Shebang Line</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Comments">Comments</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Classes">Classes</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Strings">Strings</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Files_and_Sockets">Files and Sockets</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#TODO_Comments">TODO Comments</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Imports_formatting">Imports formatting</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Statements">Statements</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Access_Control">Access Control</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Naming">Naming</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Main">Main</A></SPAN> </DIV></TD>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000174</TR>
175</TABLE>
176</DIV>
mmentovai9ec7bd62009-12-03 22:25:38 +0000177 <DIV class="">
178<H2 name="Important_Note" id="Important_Note">Important Note</H2>
179 <DIV class="">
180<H3><A name="Displaying_Hidden_Details_in_this_Guide" id="Displaying_Hidden_Details_in_this_Guide">Displaying Hidden Details in this Guide</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000181<SPAN class="link_button" id="link-Displaying_Hidden_Details_in_this_Guide__button" name="link-Displaying_Hidden_Details_in_this_Guide__button"><A href="?showone=Displaying_Hidden_Details_in_this_Guide#Displaying_Hidden_Details_in_this_Guide">
182 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000183 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Displaying_Hidden_Details_in_this_Guide')" name="Displaying_Hidden_Details_in_this_Guide__button" id="Displaying_Hidden_Details_in_this_Guide__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000184 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000185 This style guide contains many details that are initially
186 hidden from view. They are marked by the triangle icon, which you
187 see here on your left. Click it now.
188 You should see "Hooray" appear below.
mmentovai9ec7bd62009-12-03 22:25:38 +0000189 </DIV>
190 <DIV class=""><DIV class="stylepoint_body" name="Displaying_Hidden_Details_in_this_Guide__body" id="Displaying_Hidden_Details_in_this_Guide__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000191 <p>
192 Hooray! Now you know you can expand points to get more
193 details. Alternatively, there's a "toggle all" at the
194 top of this document.
195 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000196 </DIV></DIV>
197 </DIV>
198 </DIV>
199 <DIV class="">
200<H2 name="Background" id="Background">Background</H2>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000201 <p>
202 Python is the main scripting language used at Google. This
203 style guide is a list of <em>do</em>s and <em>don't</em>s for Python
204 programs.
205 </p>
206
mshields@google.com222e6da2010-11-29 20:32:06 +0000207 <p>
208 To help you format code correctly, we've created a <a href="google_python_style.vim">settings
209 file for Vim</a>. For Emacs, the default settings should be fine.
210 </p>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000211
212
mmentovai9ec7bd62009-12-03 22:25:38 +0000213 </DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000214
mmentovai9ec7bd62009-12-03 22:25:38 +0000215 <DIV class="">
216<H2 name="Python_Language_Rules" id="Python_Language_Rules">Python Language Rules</H2>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000217
mmentovai9ec7bd62009-12-03 22:25:38 +0000218 <DIV class="">
219<H3><A name="pychecker" id="pychecker">pychecker</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000220<SPAN class="link_button" id="link-pychecker__button" name="link-pychecker__button"><A href="?showone=pychecker#pychecker">
221 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000222 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('pychecker')" name="pychecker__button" id="pychecker__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000223 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000224 Run <code>pychecker</code> over your code.
mmentovai9ec7bd62009-12-03 22:25:38 +0000225 </DIV>
apicard@google.com424ad342012-09-18 23:16:02 +0000226 <DIV class=""><DIV class="stylepoint_body" name="pychecker__body" id="pychecker__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000227 <P class="">
228<SPAN class="stylepoint_section">Definition: </SPAN>
229 PyChecker is a tool for finding bugs in Python source code. It finds
230 problems that are typically caught by a compiler for less dynamic
231 languages like C and C++. It is similar to lint. Because of the
232 dynamic nature of Python, some warnings may be incorrect; however,
233 spurious warnings should be fairly infrequent.
234 </P>
235 <P class="">
236<SPAN class="stylepoint_section">Pros: </SPAN>
237 Catches easy-to-miss errors like typos, use-vars-before-assignment, etc.
238 </P>
239 <P class="">
240<SPAN class="stylepoint_section">Cons: </SPAN>
241 <code>pychecker</code> isn't perfect. To take
242 advantage of it, we'll need to sometimes: a) Write around it b)
243 Suppress its warnings c) Improve it or d) Ignore it.
244 </P>
245 <P class="">
apicard@google.com424ad342012-09-18 23:16:02 +0000246<SPAN class="stylepoint_section">Decision: </SPAN>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000247 Make sure you run <code>pychecker</code> on your code.
248 </P>
249
250 <p>
251 For information on how to run <code>pychecker</code>, see the
252 <a HREF="http://pychecker.sourceforge.net">pychecker
253 homepage</a>
254 </p>
255 <p>
256 To suppress warnings, you can set a module-level variable named
apicard@google.com424ad342012-09-18 23:16:02 +0000257 <code>__pychecker__</code> to suppress appropriate warnings.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000258 For example:
259 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000260 <DIV class=""><PRE>
261<span class="external"></span>__pychecker__ = 'no-callinit no-classattr'</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000262 <p>
263 Suppressing in this way has the advantage that we can easily search
264 for suppressions and revisit them.
265 </p>
266 <p>
apicard@google.com424ad342012-09-18 23:16:02 +0000267 You can get a list of pychecker warnings by doing
apicard@google.comf900c2c2009-07-23 20:09:56 +0000268 <code>pychecker --help</code>.
269 </p>
270 <p>
271 Unused argument warnings can be suppressed by using `_' as the
272 identifier for the unused argument or prefixing the argument name with
273 `unused_'. In situations where changing the argument names is
274 infeasible, you can mention them at the beginning of the function.
275 For example:
276 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000277 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000278<span class="external"></span>def foo(a, unused_b, unused_c, d=None, e=None):
apicard@google.com424ad342012-09-18 23:16:02 +0000279 <span class="external"> </span>_ = d, e
apicard@google.comf900c2c2009-07-23 20:09:56 +0000280 <span class="external"> </span>return a
281<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000282</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000283 <p>
284 Ideally, pychecker would be extended to ensure that such `unused
285 declarations' were true.
286 </p>
287
mmentovai9ec7bd62009-12-03 22:25:38 +0000288 </DIV></DIV>
289 </DIV>
290 <DIV class="">
291<H3><A name="Imports" id="Imports">Imports</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000292<SPAN class="link_button" id="link-Imports__button" name="link-Imports__button"><A href="?showone=Imports#Imports">
293 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000294 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Imports')" name="Imports__button" id="Imports__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000295 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000296 Use <code>import</code>s for packages and modules only.
mmentovai9ec7bd62009-12-03 22:25:38 +0000297 </DIV>
298 <DIV class=""><DIV class="stylepoint_body" name="Imports__body" id="Imports__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000299 <P class="">
300<SPAN class="stylepoint_section">Definition: </SPAN>
301 Reusability mechanism for sharing code from one module to another.
302 </P>
303 <P class="">
304<SPAN class="stylepoint_section">Pros: </SPAN>
mmentovaidb989ec2010-11-23 18:02:36 +0000305 The namespace management convention is simple. The source of each
306 identifier is indicated in a consistent way; <code>x.Obj</code> says
307 that object <code>Obj</code> is defined in module <code>x</code>.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000308 </P>
309 <P class="">
mmentovaidb989ec2010-11-23 18:02:36 +0000310<SPAN class="stylepoint_section">Cons: </SPAN> Module names can still collide. Some module names are
311 inconveniently long.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000312 </P>
313 <P class="">
314<SPAN class="stylepoint_section">Decision: </SPAN>
mmentovaidb989ec2010-11-23 18:02:36 +0000315 Use <code>import x</code> for importing packages and modules.
316 <br>
317 Use <code>from x import y</code> where <code>x</code> is
318 the package prefix and <code>y</code> is the module name with no
319 prefix.
320 <br>
321 Use <code>from x import y as z</code> if two modules named
mark@chromium.orge33361f2011-11-04 16:55:22 +0000322 <code>y</code> are to be imported or if <code>y</code> is an
mmentovaidb989ec2010-11-23 18:02:36 +0000323 inconveniently long name.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000324 </P>
mmentovaidb989ec2010-11-23 18:02:36 +0000325 For example the module
326 <code>sound.effects.echo</code> may be imported as follows:
mmentovai9ec7bd62009-12-03 22:25:38 +0000327 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000328<span class="external"></span>from sound.effects import echo
329<span class="external"></span>...
mmentovaidb989ec2010-11-23 18:02:36 +0000330<span class="external"></span>echo.EchoFilter(input, output, delay=0.7, atten=4)
apicard@google.comf900c2c2009-07-23 20:09:56 +0000331<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000332</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000333 <p>
mmentovaidb989ec2010-11-23 18:02:36 +0000334 Do not use relative names in imports. Even if the module is in the
335 same package, use the full package name. This helps prevent
336 unintentionally importing a package twice.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000337 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000338 </DIV></DIV>
339 </DIV>
340 <DIV class="">
341<H3><A name="Packages" id="Packages">Packages</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000342<SPAN class="link_button" id="link-Packages__button" name="link-Packages__button"><A href="?showone=Packages#Packages">
343 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000344 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Packages')" name="Packages__button" id="Packages__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000345 <DIV style="display:inline;" class="">
mmentovaidb989ec2010-11-23 18:02:36 +0000346 Import each module using the full pathname location of the module.
mmentovai9ec7bd62009-12-03 22:25:38 +0000347 </DIV>
348 <DIV class=""><DIV class="stylepoint_body" name="Packages__body" id="Packages__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000349 <P class="">
350<SPAN class="stylepoint_section">Pros: </SPAN>
351 Avoids conflicts in module names. Makes it easier to find modules.
352 </P>
353 <P class="">
354<SPAN class="stylepoint_section">Cons: </SPAN>
355 Makes it harder to deploy code because you have to replicate the
356 package hierarchy.
357 </P>
358 <P class="">
359<SPAN class="stylepoint_section">Decision: </SPAN>
mmentovaidb989ec2010-11-23 18:02:36 +0000360 All new code should import each module by its full package name.
361
apicard@google.comf900c2c2009-07-23 20:09:56 +0000362 </P>
363 <p>
364 Imports should be as follows:
365 </p>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000366
mmentovai9ec7bd62009-12-03 22:25:38 +0000367 <DIV class=""><PRE># Reference in code with complete name.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000368import sound.effects.echo
369
mmentovaidb989ec2010-11-23 18:02:36 +0000370# Reference in code with just module name (preferred).
apicard@google.comf900c2c2009-07-23 20:09:56 +0000371from sound.effects import echo
mmentovai9ec7bd62009-12-03 22:25:38 +0000372</PRE></DIV>
mmentovai9ec7bd62009-12-03 22:25:38 +0000373 </DIV></DIV>
374 </DIV>
375 <DIV class="">
376<H3><A name="Exceptions" id="Exceptions">Exceptions</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000377<SPAN class="link_button" id="link-Exceptions__button" name="link-Exceptions__button"><A href="?showone=Exceptions#Exceptions">
378 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000379 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Exceptions')" name="Exceptions__button" id="Exceptions__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000380 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000381 Exceptions are allowed but must be used carefully.
mmentovai9ec7bd62009-12-03 22:25:38 +0000382 </DIV>
383 <DIV class=""><DIV class="stylepoint_body" name="Exceptions__body" id="Exceptions__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000384 <P class="">
385<SPAN class="stylepoint_section">Definition: </SPAN>
386 Exceptions are a means of breaking out of the normal flow of control
387 of a code block to handle errors or other exceptional conditions.
388 </P>
389 <P class="">
390<SPAN class="stylepoint_section">Pros: </SPAN>
391 The control flow of normal operation code is not cluttered by
392 error-handling code. It also allows the control flow to skip multiple
393 frames when a certain condition occurs, e.g., returning from N
394 nested functions in one step instead of having to carry-through
395 error codes.
396 </P>
397 <P class="">
398<SPAN class="stylepoint_section">Cons: </SPAN>
399 May cause the control flow to be confusing. Easy to miss error
400 cases when making library calls.
401 </P>
402 <P class="">
403<SPAN class="stylepoint_section">Decision: </SPAN>
404
405
406 Exceptions must follow certain conditions:
407
408 <ul>
apicard@google.com424ad342012-09-18 23:16:02 +0000409 <li>Raise exceptions like this: <code>raise MyException('Error
410 message')</code> or <code>raise MyException</code>. Do not
411 use the two-argument form (<code>raise MyException, 'Error
412 message'</code>) or deprecated string-based exceptions
413 (<code>raise 'Error message'</code>).</li>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000414 <li>Modules or packages should define their own domain-specific
415 base exception class, which should inherit from the built-in
416 Exception class. The base exception for a module should be called
417 <code>Error</code>.
mmentovai9ec7bd62009-12-03 22:25:38 +0000418 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000419<span class="external"></span>class Error(Exception):
mmentovai9ec7bd62009-12-03 22:25:38 +0000420 <span class="external"> </span>pass</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000421</li>
422 <li>Never use catch-all <code>except:</code> statements, or
423 catch <code>Exception</code> or <code>StandardError</code>,
424 unless you are re-raising the exception or in the outermost
425 block in your thread (and printing an error message). Python
426 is very tolerant in this regard and <code>except:</code> will
mark@chromium.orgc8c76a22012-11-28 20:26:27 +0000427 really catch everything including misspelled names, sys.exit()
428 calls, Ctrl+C interrupts, unittest failures and all kinds of
429 other exceptions that you simply don't want to catch.</li>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000430 <li>Minimize the amount of code in a
431 <code>try</code>/<code>except</code> block. The larger the
432 body of the <code>try</code>, the more likely that an
433 exception will be raised by a line of code that you didn't
434 expect to raise an exception. In those cases,
435 the <code>try</code>/<code>except</code> block hides a real
436 error.</li>
437 <li>Use the <code>finally</code> clause to execute code whether
438 or not an exception is raised in the <code>try</code> block.
439 This is often useful for cleanup, i.e., closing a file.</li>
apicard@google.com424ad342012-09-18 23:16:02 +0000440 <li>When capturing an exception, use <code>as</code> rather than
441 a comma. For example:
442 <DIV class=""><PRE>
443<span class="external"></span>try:
444 <span class="external"> </span>raise Error
445<span class="external"></span>except Error as error:
446 <span class="external"> </span>pass</PRE></DIV>
447</li>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000448 </ul>
449 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000450 </DIV></DIV>
451 </DIV>
452 <DIV class="">
453<H3><A name="Global_variables" id="Global_variables">Global variables</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000454<SPAN class="link_button" id="link-Global_variables__button" name="link-Global_variables__button"><A href="?showone=Global_variables#Global_variables">
455 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000456 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Global_variables')" name="Global_variables__button" id="Global_variables__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000457 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000458 Avoid global variables.
mmentovai9ec7bd62009-12-03 22:25:38 +0000459 </DIV>
460 <DIV class=""><DIV class="stylepoint_body" name="Global_variables__body" id="Global_variables__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000461 <P class="">
462<SPAN class="stylepoint_section">Definition: </SPAN>
463 Variables that are declared at the module level.
464 </P>
465 <P class="">
466<SPAN class="stylepoint_section">Pros: </SPAN>
467 Occasionally useful.
468 </P>
469 <P class="">
470<SPAN class="stylepoint_section">Cons: </SPAN>
471 Has the potential to change module behavior during the import,
472 because assignments to module-level variables are done when the
473 module is imported.
474 </P>
475 <P class="">
476<SPAN class="stylepoint_section">Decision: </SPAN>
477 Avoid global variables in favor of class variables. Some
478 exceptions are:
479 <ul>
480 <li>Default options for scripts.</li>
481 <li>Module-level constants. For example: <code>PI = 3.14159</code>.
482 Constants should be named using all caps with underscores;
483 see <a HREF="#Naming">Naming</a> below.</li>
484 <li>It is sometimes useful for globals to cache values needed
485 or returned by functions.</li>
486 <li>If needed, globals should be made internal to the module
487 and accessed through public module level functions;
488 see <a HREF="#Naming">Naming</a> below.</li>
489 </ul>
490 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000491 </DIV></DIV>
492 </DIV>
493 <DIV class="">
494<H3><A name="Nested/Local/Inner_Classes_and_Functions" id="Nested/Local/Inner_Classes_and_Functions">Nested/Local/Inner Classes and Functions</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000495<SPAN class="link_button" id="link-Nested/Local/Inner_Classes_and_Functions__button" name="link-Nested/Local/Inner_Classes_and_Functions__button"><A href="?showone=Nested/Local/Inner_Classes_and_Functions#Nested/Local/Inner_Classes_and_Functions">
496 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000497 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Nested/Local/Inner_Classes_and_Functions')" name="Nested/Local/Inner_Classes_and_Functions__button" id="Nested/Local/Inner_Classes_and_Functions__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000498 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000499 Nested/local/inner classes and functions are fine.
mmentovai9ec7bd62009-12-03 22:25:38 +0000500 </DIV>
501 <DIV class=""><DIV class="stylepoint_body" name="Nested/Local/Inner_Classes_and_Functions__body" id="Nested/Local/Inner_Classes_and_Functions__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000502 <P class="">
503<SPAN class="stylepoint_section">Definition: </SPAN>
mmentovaif7facf92009-10-23 21:01:49 +0000504 A class can be defined inside of a method, function, or class. A
505 function can be defined inside a method or function. Nested functions
506 have read-only access to variables defined in enclosing scopes.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000507 </P>
508 <P class="">
509<SPAN class="stylepoint_section">Pros: </SPAN>
510 Allows definition of utility classes and functions that are only
511 used inside of a very limited scope. Very <a HREF="http://en.wikipedia.org/wiki/Abstract_data_type">ADT</a>-y.
512 </P>
513 <P class="">
514<SPAN class="stylepoint_section">Cons: </SPAN>
515 Instances of nested or local classes cannot be pickled.
516 </P>
517 <P class="">
518<SPAN class="stylepoint_section">Decision: </SPAN>
519 They are fine.
520 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000521 </DIV></DIV>
522 </DIV>
523 <DIV class="">
524<H3><A name="List_Comprehensions" id="List_Comprehensions">List Comprehensions</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000525<SPAN class="link_button" id="link-List_Comprehensions__button" name="link-List_Comprehensions__button"><A href="?showone=List_Comprehensions#List_Comprehensions">
526 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000527 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('List_Comprehensions')" name="List_Comprehensions__button" id="List_Comprehensions__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000528 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000529 Okay to use for simple cases.
mmentovai9ec7bd62009-12-03 22:25:38 +0000530 </DIV>
531 <DIV class=""><DIV class="stylepoint_body" name="List_Comprehensions__body" id="List_Comprehensions__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000532 <P class="">
533<SPAN class="stylepoint_section">Definition: </SPAN>
534 List comprehensions and generator expressions provide a concise
535 and efficient way to create lists and iterators without
536 resorting to the use of <code>map()</code>,
537 <code>filter()</code>, or <code>lambda</code>.
538 </P>
539 <P class="">
540<SPAN class="stylepoint_section">Pros: </SPAN>
541 Simple list comprehensions can be clearer and simpler than
542 other list creation techniques. Generator expressions can be
543 very efficient, since they avoid the creation of a list
544 entirely.
545 </P>
546 <P class="">
547<SPAN class="stylepoint_section">Cons: </SPAN>
548 Complicated list comprehensions or generator expressions can be
549 hard to read.
550 </P>
551 <P class="">
552<SPAN class="stylepoint_section">Decision: </SPAN>
553 Okay to use for simple cases. Each portion must fit on one line:
554 mapping expression, <code>for</code> clause, filter expression.
555 Multiple <code>for</code> clauses or filter expressions are not
556 permitted. Use loops instead when things get more complicated.
557 </P>
558
mmentovai9ec7bd62009-12-03 22:25:38 +0000559<DIV class=""><PRE>Ye<span class="external"></span>s:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000560 <span class="external"></span>result = []
561 <span class="external"></span>for x in range(10):
562 <span class="external"> </span>for y in range(5):
563 <span class="external"> </span>if x * y &gt; 10:
564 <span class="external"> </span>result.append((x, y))
565
566 <span class="external"></span>for x in xrange(5):
567 <span class="external"> </span>for y in xrange(5):
568 <span class="external"> </span>if x != y:
569 <span class="external"> </span>for z in xrange(5):
570 <span class="external"> </span>if y != z:
571 <span class="external"> </span>yield (x, y, z)
572
573 <span class="external"></span>return ((x, complicated_transform(x))
574 <span class="external"></span> for x in long_generator_function(parameter)
575 <span class="external"></span> if x is not None)
576
577 <span class="external"></span>squares = [x * x for x in range(10)]
578
579 <span class="external"></span>eat(jelly_bean for jelly_bean in jelly_beans
mmentovai9ec7bd62009-12-03 22:25:38 +0000580 <span class="external"></span> if jelly_bean.color == 'black')</PRE></DIV>
apicard@google.com424ad342012-09-18 23:16:02 +0000581<DIV class=""><PRE class="badcode">No<span class="external"></span>:
582 <span class="external"></span>result = [(x, y) for x in range(10) for y in range(5) if x * y &gt; 10]
583
584 <span class="external"></span>return ((x, y, z)
585 <span class="external"></span> for x in xrange(5)
586 <span class="external"></span> for y in xrange(5)
587 <span class="external"></span> if x != y
588 <span class="external"></span> for z in xrange(5)
589 <span class="external"></span> if y != z)</PRE></DIV>
mmentovai9ec7bd62009-12-03 22:25:38 +0000590 </DIV></DIV>
591 </DIV>
592 <DIV class="">
593<H3><A name="Default_Iterators_and_Operators" id="Default_Iterators_and_Operators">Default Iterators and Operators</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000594<SPAN class="link_button" id="link-Default_Iterators_and_Operators__button" name="link-Default_Iterators_and_Operators__button"><A href="?showone=Default_Iterators_and_Operators#Default_Iterators_and_Operators">
595 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000596 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Default_Iterators_and_Operators')" name="Default_Iterators_and_Operators__button" id="Default_Iterators_and_Operators__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000597 <DIV style="display:inline;" class="">
apicard@google.com424ad342012-09-18 23:16:02 +0000598 Use default iterators and operators for types that support them,
apicard@google.comf900c2c2009-07-23 20:09:56 +0000599 like lists, dictionaries, and files.
mmentovai9ec7bd62009-12-03 22:25:38 +0000600 </DIV>
601 <DIV class=""><DIV class="stylepoint_body" name="Default_Iterators_and_Operators__body" id="Default_Iterators_and_Operators__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000602 <P class="">
603<SPAN class="stylepoint_section">Definition: </SPAN>
604 Container types, like dictionaries and lists, define default
605 iterators and membership test operators ("in" and "not in").
606 </P>
607 <P class="">
608<SPAN class="stylepoint_section">Pros: </SPAN>
609 The default iterators and operators are simple and efficient.
610 They express the operation directly, without extra method calls.
611 A function that uses default operators is generic. It can be
612 used with any type that supports the operation.
613 </P>
614 <P class="">
615<SPAN class="stylepoint_section">Cons: </SPAN>
616 You can't tell the type of objects by reading the method names
617 (e.g. has_key() means a dictionary). This is also an advantage.
618 </P>
619 <P class="">
620<SPAN class="stylepoint_section">Decision: </SPAN> Use default iterators and operators for types
621 that support them, like lists, dictionaries, and files. The
622 built-in types define iterator methods, too. Prefer these
623 methods to methods that return lists, except that you should not
624 mutate a container while iterating over it.
625
mmentovai9ec7bd62009-12-03 22:25:38 +0000626<DIV class=""><PRE>Yes: <span class="external"></span>for key in adict: ...
apicard@google.comf900c2c2009-07-23 20:09:56 +0000627 <span class="external"></span>if key not in adict: ...
628 <span class="external"></span>if obj in alist: ...
629 <span class="external"></span>for line in afile: ...
mmentovai9ec7bd62009-12-03 22:25:38 +0000630 <span class="external"></span>for k, v in dict.iteritems(): ...</PRE></DIV>
631<DIV class=""><PRE class="badcode">No: <span class="external"></span>for key in adict.keys(): ...
apicard@google.comf900c2c2009-07-23 20:09:56 +0000632 <span class="external"></span>if not adict.has_key(key): ...
mmentovai9ec7bd62009-12-03 22:25:38 +0000633 <span class="external"></span>for line in afile.readlines(): ...</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000634 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000635 </DIV></DIV>
636 </DIV>
637 <DIV class="">
638<H3><A name="Generators" id="Generators">Generators</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000639<SPAN class="link_button" id="link-Generators__button" name="link-Generators__button"><A href="?showone=Generators#Generators">
640 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000641 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Generators')" name="Generators__button" id="Generators__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000642 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000643 Use generators as needed.
mmentovai9ec7bd62009-12-03 22:25:38 +0000644 </DIV>
645 <DIV class=""><DIV class="stylepoint_body" name="Generators__body" id="Generators__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000646 <P class="">
647<SPAN class="stylepoint_section">Definition: </SPAN>
648 A generator function returns an iterator that yields a value each
649 time it executes a yield statement. After it yields a value, the
650 runtime state of the generator function is suspended until the
651 next value is needed.
652 </P>
653 <P class="">
654<SPAN class="stylepoint_section">Pros: </SPAN>
655 Simpler code, because the state of local variables and control flow
656 are preserved for each call. A generator uses less memory than a
657 function that creates an entire list of values at once.
658 </P>
659 <P class="">
apicard@google.com424ad342012-09-18 23:16:02 +0000660<SPAN class="stylepoint_section">Cons: </SPAN>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000661 None.
662 </P>
663 <P class="">
664<SPAN class="stylepoint_section">Decision: </SPAN>
665 Fine. Use "Yields:" rather than "Returns:" in the
666 doc string for generator functions.
667 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000668 </DIV></DIV>
669 </DIV>
670 <DIV class="">
671<H3><A name="Lambda_Functions" id="Lambda_Functions">Lambda Functions</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000672<SPAN class="link_button" id="link-Lambda_Functions__button" name="link-Lambda_Functions__button"><A href="?showone=Lambda_Functions#Lambda_Functions">
673 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000674 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Lambda_Functions')" name="Lambda_Functions__button" id="Lambda_Functions__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000675 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000676 Okay for one-liners.
mmentovai9ec7bd62009-12-03 22:25:38 +0000677 </DIV>
678 <DIV class=""><DIV class="stylepoint_body" name="Lambda_Functions__body" id="Lambda_Functions__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000679 <P class="">
680<SPAN class="stylepoint_section">Definition: </SPAN>
681 Lambdas define anonymous functions in an expression, as
682 opposed to a statement. They are often used to define callbacks or
683 operators for higher-order functions like <code>map()</code> and
684 <code>filter()</code>.
685 </P>
686 <P class="">
687<SPAN class="stylepoint_section">Pros: </SPAN>
688 Convenient.
689 </P>
690 <P class="">
691<SPAN class="stylepoint_section">Cons: </SPAN> Harder to read and debug than local functions. The
692 lack of names means stack traces are more difficult to
693 understand. Expressiveness is limited because the function may
694 only contain an expression.
695 </P>
696 <P class="">
697<SPAN class="stylepoint_section">Decision: </SPAN>
698 Okay to use them for one-liners. If the code inside the lambda
699 function is any longer than 60–80 chars, it's probably better to
700 define it as a regular (nested) function.
701 <p>
702 For common operations like multiplication, use the functions from the
703 <code>operator</code> module instead of lambda functions. For
704 example, prefer <code>operator.mul</code> to <code>lambda
705 x, y: x * y</code>.
706 </p>
707 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000708 </DIV></DIV>
709 </DIV>
710 <DIV class="">
apicard@google.com424ad342012-09-18 23:16:02 +0000711<H3><A name="Conditional_Expressions" id="Conditional_Expressions">Conditional Expressions</A></H3>
712<SPAN class="link_button" id="link-Conditional_Expressions__button" name="link-Conditional_Expressions__button"><A href="?showone=Conditional_Expressions#Conditional_Expressions">
713 link
714 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Conditional_Expressions')" name="Conditional_Expressions__button" id="Conditional_Expressions__button"></SPAN>
715 <DIV style="display:inline;" class="">
716 Okay for one-liners.
717 </DIV>
718 <DIV class=""><DIV class="stylepoint_body" name="Conditional_Expressions__body" id="Conditional_Expressions__body" style="display: none">
719 <P class="">
720<SPAN class="stylepoint_section">Definition: </SPAN>
721 Conditional expressions are mechanisms that provide a shorter syntax
722 for if statements. For example:
723 <code>x = 1 if cond else 2</code>.
724 </P>
725 <P class="">
726<SPAN class="stylepoint_section">Pros: </SPAN>
727 Shorter and more convenient than an if statement.
728 </P>
729 <P class="">
730<SPAN class="stylepoint_section">Cons: </SPAN>
731 May be harder to read than an if statement. The condition may be difficult
732 to locate if the expression is long.
733 </P>
734 <P class="">
735<SPAN class="stylepoint_section">Decision: </SPAN>
736 Okay to use for one-liners. In other cases prefer to use a complete if
737 statement.
738 </P>
739 </DIV></DIV>
740 </DIV>
741 <DIV class="">
mmentovai9ec7bd62009-12-03 22:25:38 +0000742<H3><A name="Default_Argument_Values" id="Default_Argument_Values">Default Argument Values</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000743<SPAN class="link_button" id="link-Default_Argument_Values__button" name="link-Default_Argument_Values__button"><A href="?showone=Default_Argument_Values#Default_Argument_Values">
744 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000745 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Default_Argument_Values')" name="Default_Argument_Values__button" id="Default_Argument_Values__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000746 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000747 Okay in most cases.
mmentovai9ec7bd62009-12-03 22:25:38 +0000748 </DIV>
749 <DIV class=""><DIV class="stylepoint_body" name="Default_Argument_Values__body" id="Default_Argument_Values__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000750 <P class="">
751<SPAN class="stylepoint_section">Definition: </SPAN>
752 You can specify values for variables at the end of a function's
753 parameter list, e.g., <code>def foo(a, b=0):</code>. If
754 <code>foo</code> is called with only one argument,
755 <code>b</code> is set to 0. If it is called with two arguments,
756 <code>b</code> has the value of the second argument.
757 </P>
758 <P class="">
759<SPAN class="stylepoint_section">Pros: </SPAN>
760 Often you have a function that uses lots of default values,
761 but—rarely—you want to override the
762 defaults. Default argument values provide an easy way to do this,
763 without having to define lots of functions for the rare
764 exceptions. Also, Python does not support overloaded
765 methods/functions and default arguments are an easy way of
766 "faking" the overloading behavior.
767 </P>
768 <P class="">
apicard@google.com424ad342012-09-18 23:16:02 +0000769<SPAN class="stylepoint_section">Cons: </SPAN>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000770 Default arguments are evaluated once at module load
771 time. This may cause problems if the argument is a mutable
772 object such as a list or a dictionary. If the function modifies
773 the object (e.g., by appending an item to a list), the default
774 value is modified.
775 </P>
776 <P class="">
777<SPAN class="stylepoint_section">Decision: </SPAN>
mark@chromium.org5684bbc2013-07-12 18:53:13 +0000778 Okay to use with the following caveat:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000779 <p>
780 Do not use mutable objects as default values in the function or method
781 definition.
782 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +0000783<DIV class=""><PRE>Yes: <span class="external"></span>def foo(a, b=None):
apicard@google.comf900c2c2009-07-23 20:09:56 +0000784 <span class="external"> </span>if b is None:
mmentovai9ec7bd62009-12-03 22:25:38 +0000785 <span class="external"> </span>b = []</PRE></DIV>
786<DIV class=""><PRE class="badcode">No: <span class="external"></span>def foo(a, b=[]):
787 <span class="external"> </span>...</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000788 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000789 </DIV></DIV>
790 </DIV>
791 <DIV class="">
792<H3><A name="Properties" id="Properties">Properties</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000793<SPAN class="link_button" id="link-Properties__button" name="link-Properties__button"><A href="?showone=Properties#Properties">
794 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000795 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Properties')" name="Properties__button" id="Properties__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +0000796 <DIV style="display:inline;" class="">
apicard@google.com424ad342012-09-18 23:16:02 +0000797 Use properties for accessing or setting data where you would
798 normally have used simple, lightweight accessor or setter methods.
mmentovai9ec7bd62009-12-03 22:25:38 +0000799 </DIV>
800 <DIV class=""><DIV class="stylepoint_body" name="Properties__body" id="Properties__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000801 <P class="">
802<SPAN class="stylepoint_section">Definition: </SPAN> A way to wrap method calls for getting and
803 setting an attribute as a standard attribute access when the
804 computation is lightweight.
805 </P>
806 <P class="">
807<SPAN class="stylepoint_section">Pros: </SPAN> Readability is increased by eliminating explicit
808 get and set method calls for simple attribute access. Allows
809 calculations to be lazy. Considered the Pythonic way to
810 maintain the interface of a class. In terms of performance,
811 allowing properties bypasses needing trivial accessor methods
812 when a direct variable access is reasonable. This also allows
813 accessor methods to be added in the future without breaking the
814 interface.
815 </P>
816 <P class="">
817<SPAN class="stylepoint_section">Cons: </SPAN> Properties are specified after the getter and
818 setter methods are declared, requiring one to notice they are
819 used for properties farther down in the code (except for readonly
820 properties created with the <code>@property</code> decorator - see
821 below). Must inherit from
822 <code>object</code>. Can hide side-effects much like operator
823 overloading. Can be confusing for subclasses.
824 </P>
825 <P class="">
826<SPAN class="stylepoint_section">Decision: </SPAN> Use properties in new code to access or
827 set data where you would normally have used simple, lightweight
828 accessor or setter methods. Read-only properties should be created
apicard@google.com424ad342012-09-18 23:16:02 +0000829 with the <code>@property</code>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000830 <a HREF="#Function_and_Method_Decorators">decorator</a>.
831
832 <p><a id="properties-template-dp">
833 Inheritance with properties can be non-obvious if the property itself is
834 not overridden. Thus one must make sure that accessor methods are
835 called indirectly to ensure methods overridden in subclasses are called
836 by the property (using the Template Method DP).
837 </a></p>
838
mmentovai9ec7bd62009-12-03 22:25:38 +0000839 <DIV class=""><PRE>Yes: <span class="external"></span>import math
apicard@google.comf900c2c2009-07-23 20:09:56 +0000840
841 <span class="external"></span>class Square(object):
842 <span class="external"> </span>"""A square with two properties: a writable area and a read-only perimeter.
843
844 <span class="external"> </span>To use:
845 <span class="external"> </span>&gt;&gt;&gt; sq = Square(3)
846 <span class="external"> </span>&gt;&gt;&gt; sq.area
847 <span class="external"> </span>9
848 <span class="external"> </span>&gt;&gt;&gt; sq.perimeter
849 <span class="external"> </span>12
850 <span class="external"> </span>&gt;&gt;&gt; sq.area = 16
851 <span class="external"> </span>&gt;&gt;&gt; sq.side
852 <span class="external"> </span>4
853 <span class="external"> </span>&gt;&gt;&gt; sq.perimeter
854 <span class="external"> </span>16
855 <span class="external"> </span>"""
856
857 <span class="external"> </span>def __init__(self, side):
858 <span class="external"> </span>self.side = side
859
860 <span class="external"> </span>def __get_area(self):
861 <span class="external"> </span>"""Calculates the 'area' property."""
862 <span class="external"> </span>return self.side ** 2
863
864 <span class="external"> </span>def ___get_area(self):
865 <span class="external"> </span>"""Indirect accessor for 'area' property."""
866 <span class="external"> </span>return self.__get_area()
867
868 <span class="external"> </span>def __set_area(self, area):
869 <span class="external"> </span>"""Sets the 'area' property."""
870 <span class="external"> </span>self.side = math.sqrt(area)
871
872 <span class="external"> </span>def ___set_area(self, area):
873 <span class="external"> </span>"""Indirect setter for 'area' property."""
mark@chromium.org7f891932011-11-04 21:13:33 +0000874 <span class="external"> </span>self.__set_area(area)
apicard@google.comf900c2c2009-07-23 20:09:56 +0000875
876 <span class="external"> </span>area = property(___get_area, ___set_area,
877 <span class="external"> </span> doc="""Gets or sets the area of the square.""")
878
879 <span class="external"> </span>@property
880 <span class="external"> </span>def perimeter(self):
881 <span class="external"> </span>return self.side * 4
882<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +0000883</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000884 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000885 </DIV></DIV>
886 </DIV>
887 <DIV class="">
888<H3><A name="True/False_evaluations" id="True/False_evaluations">True/False evaluations</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000889<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">
890 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000891 </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 +0000892 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +0000893 Use the "implicit" false if at all possible.
mmentovai9ec7bd62009-12-03 22:25:38 +0000894 </DIV>
895 <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 +0000896 <P class="">
897<SPAN class="stylepoint_section">Definition: </SPAN> Python evaluates certain values as <code>false</code>
898 when in a boolean context. A quick "rule of thumb" is that all
899 "empty" values are considered <code>false</code> so <code>0, None, [], {},
apicard@google.com424ad342012-09-18 23:16:02 +0000900 ''</code> all evaluate as <code>false</code> in a boolean context.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000901 </P>
902 <P class="">
903<SPAN class="stylepoint_section">Pros: </SPAN> Conditions using Python booleans are easier to read
904 and less error-prone. In most cases, they're also faster.
905 </P>
906 <P class="">
907<SPAN class="stylepoint_section">Cons: </SPAN>
908 May look strange to C/C++ developers.
909 </P>
910 <P class="">
911<SPAN class="stylepoint_section">Decision: </SPAN>
912 Use the "implicit" false if at all possible, e.g., <code>if
913 foo:</code> rather than <code>if foo != []:</code>. There are a
914 few caveats that you should keep in mind though:
915 <ul>
916 <li>
917 Never use <code>==</code> or <code>!=</code> to compare
918 singletons like <code>None</code>. Use <code>is</code>
919 or <code>is not</code>.</li>
920
921 <li>Beware of writing <code>if x:</code> when you really mean
922 <code>if x is not None:</code>—e.g., when testing whether
923 a variable or argument that defaults to <code>None</code> was
924 set to some other value. The other value might be a value
925 that's false in a boolean context!</li>
926
927 <li>
928 Never compare a boolean variable to <code>False</code> using
929 <code>==</code>. Use <code>if not x:</code> instead. If
930 you need to distinguish <code>False</code> from
931 <code>None</code> then chain the expressions,
932 such as <code>if not x and x is not None:</code>.
933 </li>
934
935 <li>
936 For sequences (strings, lists, tuples), use the fact that
937 empty sequences are false, so <code>if not seq:</code> or
938 <code>if seq:</code> is preferable to <code>if
939 len(seq):</code> or <code>if not
940 len(seq):</code>.</li>
941
942 <li>
943 When handling integers, implicit false may involve more risk than
944 benefit (i.e., accidentally handling <code>None</code> as 0). You may
945 compare a value which is known to be an integer (and is not the
946 result of <code>len()</code>) against the integer 0.
mmentovai9ec7bd62009-12-03 22:25:38 +0000947<DIV class=""><PRE>Yes: <span class="external"></span>if not users:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000948 <span class="external"> </span>print 'no users'
949
950 <span class="external"></span>if foo == 0:
951 <span class="external"> </span>self.handle_zero()
952
953 <span class="external"></span>if i % 10 == 0:
mmentovai9ec7bd62009-12-03 22:25:38 +0000954 <span class="external"> </span>self.handle_multiple_of_ten()</PRE></DIV>
955<DIV class=""><PRE class="badcode">No: <span class="external"></span>if len(users) == 0:
apicard@google.comf900c2c2009-07-23 20:09:56 +0000956 <span class="external"> </span>print 'no users'
957
958 <span class="external"></span>if foo is not None and not foo:
959 <span class="external"> </span>self.handle_zero()
960
961 <span class="external"></span>if not i % 10:
mmentovai9ec7bd62009-12-03 22:25:38 +0000962 <span class="external"> </span>self.handle_multiple_of_ten()</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +0000963</li>
964
965 <li>
966 Note that <code>'0'</code> (i.e., <code>0</code> as string)
967 evaluates to true.</li>
968 </ul>
969 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +0000970 </DIV></DIV>
971 </DIV>
972 <DIV class="">
973<H3><A name="Deprecated_Language_Features" id="Deprecated_Language_Features">Deprecated Language Features</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +0000974<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">
975 link
mark@chromium.orge33361f2011-11-04 16:55:22 +0000976 </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 +0000977 <DIV style="display:inline;" class="">
mmentovaif7facf92009-10-23 21:01:49 +0000978 Use string methods instead of the <code>string</code> module
979 where possible. Use function call syntax instead
980 of <code>apply</code>. Use list comprehensions
mark@chromium.orgc8c76a22012-11-28 20:26:27 +0000981 and <code>for</code> loops instead of <code>filter</code> and
982 <code>map</code> when the function argument would have been an
983 inlined lambda anyway. Use <code>for</code> loops instead of
984 <code>reduce</code>.
mmentovai9ec7bd62009-12-03 22:25:38 +0000985 </DIV>
986 <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 +0000987 <P class="">
mmentovaif7facf92009-10-23 21:01:49 +0000988<SPAN class="stylepoint_section">Definition: </SPAN>
989 Current versions of Python provide alternative constructs
990 that people find generally preferable.
apicard@google.comf900c2c2009-07-23 20:09:56 +0000991 </P>
992 <P class="">
mmentovaif7facf92009-10-23 21:01:49 +0000993<SPAN class="stylepoint_section">Decision: </SPAN>
994 We do not use any Python version which does not support
995 these features, so there is no reason not to use the new
996 styles.
mmentovai9ec7bd62009-12-03 22:25:38 +0000997<DIV class=""><PRE>Yes: <span class="external"></span>words = foo.split(':')
mmentovaif7facf92009-10-23 21:01:49 +0000998
999 <span class="external"></span>[x[1] for x in my_list if x[2] == 5]
1000
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001001 <span class="external"></span>map(math.sqrt, data) # Ok. No inlined lambda expression.
1002
mmentovai9ec7bd62009-12-03 22:25:38 +00001003 <span class="external"></span>fn(*args, **kwargs)</PRE></DIV>
apicard@google.com424ad342012-09-18 23:16:02 +00001004<DIV class=""><PRE class="badcode">No: <span class="external"></span>words = string.split(foo, ':')
1005
1006 <span class="external"></span>map(lambda x: x[1], filter(lambda x: x[2] == 5, my_list))
1007
1008 <span class="external"></span>apply(fn, args, kwargs)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001009 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001010 </DIV></DIV>
1011 </DIV>
1012 <DIV class="">
1013<H3><A name="Lexical_Scoping" id="Lexical_Scoping">Lexical Scoping</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001014<SPAN class="link_button" id="link-Lexical_Scoping__button" name="link-Lexical_Scoping__button"><A href="?showone=Lexical_Scoping#Lexical_Scoping">
1015 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001016 </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 +00001017 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001018 Okay to use.
mmentovai9ec7bd62009-12-03 22:25:38 +00001019 </DIV>
1020 <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 +00001021 <P class="">
1022<SPAN class="stylepoint_section">Definition: </SPAN>
1023 A nested Python function can refer to variables defined in
1024 enclosing functions, but can not assign to them. Variable
1025 bindings are resolved using lexical scoping, that is, based on
1026 the static program text. Any assignment to a name in a block
1027 will cause Python to treat all references to that name as a
1028 local variable, even if the use precedes the assignment. If a
1029 global declaration occurs, the name is treated as a global
1030 variable.
apicard@google.com424ad342012-09-18 23:16:02 +00001031
apicard@google.comf900c2c2009-07-23 20:09:56 +00001032 <p>
1033 An example of the use of this feature is:
1034 </p>
1035
mmentovai9ec7bd62009-12-03 22:25:38 +00001036 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001037<span class="external"></span>def get_adder(summand1):
1038 <span class="external"> </span>"""Returns a function that adds numbers to a given number."""
1039 <span class="external"> </span>def adder(summand2):
1040 <span class="external"> </span>return summand1 + summand2
1041
1042 <span class="external"> </span>return adder
1043<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001044</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001045 </P>
1046 <P class="">
1047<SPAN class="stylepoint_section">Pros: </SPAN>
1048 Often results in clearer, more elegant code. Especially comforting
1049 to experienced Lisp and Scheme (and Haskell and ML and …)
1050 programmers.
1051 </P>
1052 <P class="">
1053<SPAN class="stylepoint_section">Cons: </SPAN>
apicard@google.com424ad342012-09-18 23:16:02 +00001054 Can lead to confusing bugs. Such as this example based on
apicard@google.comf900c2c2009-07-23 20:09:56 +00001055 <a HREF="http://www.python.org/dev/peps/pep-0227/">PEP-0227</a>:
mmentovai9ec7bd62009-12-03 22:25:38 +00001056<DIV class=""><PRE class="badcode">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001057<span class="external"></span>i = 4
1058<span class="external"></span>def foo(x):
1059 <span class="external"> </span>def bar():
1060 <span class="external"> </span>print i,
1061 <span class="external"> </span># ...
1062 <span class="external"> </span># A bunch of code here
1063 <span class="external"> </span># ...
1064 <span class="external"> </span>for i in x: # Ah, i *is* local to Foo, so this is what Bar sees
1065 <span class="external"> </span>print i,
mmentovai9ec7bd62009-12-03 22:25:38 +00001066 <span class="external"> </span>bar()</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001067 <p>
1068 So <code>foo([1, 2, 3])</code> will print <code>1 2 3 3</code>, not
1069 <code>1 2 3 4</code>.
apicard@google.com424ad342012-09-18 23:16:02 +00001070 </p>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001071 </P>
1072 <P class="">
1073<SPAN class="stylepoint_section">Decision: </SPAN>
1074 Okay to use.
1075 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001076 </DIV></DIV>
1077 </DIV>
1078 <DIV class="">
1079<H3><A name="Function_and_Method_Decorators" id="Function_and_Method_Decorators">Function and Method Decorators</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001080<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">
1081 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001082 </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 +00001083 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001084 Use decorators judiciously when there is a clear advantage.
mmentovai9ec7bd62009-12-03 22:25:38 +00001085 </DIV>
1086 <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 +00001087 <P class="">
1088<SPAN class="stylepoint_section">Definition: </SPAN>
1089
1090 <a HREF="http://www.python.org/doc/2.4.3/whatsnew/node6.html">Decorators
1091 for Functions and Methods</a>
1092 (a.k.a "the <code>@</code> notation").
1093 The most common decorators are <code>@classmethod</code> and
1094 <code>@staticmethod</code>, for converting ordinary methods to class or
1095 static methods. However, the decorator syntax allows for
1096 user-defined decorators as well. Specifically, for some function
1097 <code>my_decorator</code>, this:
mmentovai9ec7bd62009-12-03 22:25:38 +00001098 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001099<span class="external"></span>class C(object):
1100 <span class="external"> </span>@my_decorator
1101 <span class="external"> </span>def method(self):
1102 <span class="external"> </span># method body ...
1103<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001104</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001105
1106 is equivalent to:
mmentovai9ec7bd62009-12-03 22:25:38 +00001107 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001108<span class="external"></span>class C(object):
1109 <span class="external"> </span>def method(self):
1110 <span class="external"> </span># method body ...
1111 <span class="external"> </span>method = my_decorator(method)
1112<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001113</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001114 </P>
1115 <P class="">
1116<SPAN class="stylepoint_section">Pros: </SPAN> Elegantly specifies some transformation on a method; the
1117 transformation might eliminate some repetitive code, enforce invariants,
1118 etc.
1119 </P>
1120 <P class="">
1121<SPAN class="stylepoint_section">Cons: </SPAN> Decorators can perform arbitrary operations on a
1122 function's arguments or return values, resulting in surprising
1123 implicit behavior.
1124 Additionally, decorators execute at import time. Failures in decorator
1125 code are pretty much impossible to recover from.
1126 </P>
1127 <P class="">
1128<SPAN class="stylepoint_section">Decision: </SPAN> Use decorators judiciously when there is a clear
1129 advantage. Decorators should follow the same import and naming
1130 guidelines as functions. Decorator pydoc should clearly state that the
1131 function is a decorator. Write unit tests for decorators.
1132
1133 <p>
1134 Avoid external dependencies in the decorator itself (e.g. don't rely on
1135 files, sockets, database connections, etc.), since they might not be
1136 available when the decorator runs (at import time, perhaps from
1137 <code>pychecker</code> or other tools). A decorator that is
1138 called with valid parameters should (as much as possible) be guaranteed
1139 to succeed in all cases.
1140 </p>
1141 <p>
1142 Decorators are a special case of "top level code" - see
1143 <a HREF="#Main">main</a> for more discussion.
1144 </p>
1145 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001146 </DIV></DIV>
1147 </DIV>
1148 <DIV class="">
1149<H3><A name="Threading" id="Threading">Threading</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001150<SPAN class="link_button" id="link-Threading__button" name="link-Threading__button"><A href="?showone=Threading#Threading">
1151 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001152 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Threading')" name="Threading__button" id="Threading__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001153 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001154 Do not rely on the atomicity of built-in types.
mmentovai9ec7bd62009-12-03 22:25:38 +00001155 </DIV>
1156 <DIV class=""><DIV class="stylepoint_body" name="Threading__body" id="Threading__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001157 <p>
1158 While Python's built-in data types such as dictionaries appear
1159 to have atomic operations, there are corner cases where they
1160 aren't atomic (e.g. if <code>__hash__</code> or
1161 <code>__eq__</code> are implemented as Python methods) and their
1162 atomicity should not be relied upon. Neither should you rely on
1163 atomic variable assignment (since this in turn depends on
1164 dictionaries).
1165 </p>
1166
1167 <p>
apicard@google.com424ad342012-09-18 23:16:02 +00001168 Use the Queue module's <code>Queue</code> data type as the preferred
apicard@google.comf900c2c2009-07-23 20:09:56 +00001169 way to
1170 communicate data between threads. Otherwise, use the threading
1171 module and its locking primitives. Learn about the proper use
1172 of condition variables so you can use
1173 <code>threading.Condition</code> instead of using lower-level
1174 locks.
1175 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001176 </DIV></DIV>
1177 </DIV>
1178 <DIV class="">
1179<H3><A name="Power_Features" id="Power_Features">Power Features</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001180<SPAN class="link_button" id="link-Power_Features__button" name="link-Power_Features__button"><A href="?showone=Power_Features#Power_Features">
1181 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001182 </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 +00001183 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001184 Avoid these features.
mmentovai9ec7bd62009-12-03 22:25:38 +00001185 </DIV>
1186 <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 +00001187 <P class="">
1188<SPAN class="stylepoint_section">Definition: </SPAN> Python is an extremely flexible language and
1189 gives you many fancy features such as metaclasses, access to bytecode,
1190 on-the-fly compilation, dynamic inheritance, object reparenting,
1191 import hacks, reflection, modification of system internals,
1192 etc.
1193 </P>
1194 <P class="">
1195<SPAN class="stylepoint_section">Pros: </SPAN> These are powerful language features. They can
1196 make your code more compact.
1197 </P>
1198 <P class="">
1199<SPAN class="stylepoint_section">Cons: </SPAN> It's very tempting to use these "cool" features
1200 when they're not absolutely necessary. It's harder to read,
1201 understand, and debug code that's using unusual features
1202 underneath. It doesn't seem that way at first (to the original
1203 author), but when revisiting the code, it tends to be more
1204 difficult than code that is longer but is straightforward.
1205 </P>
1206 <P class="">
apicard@google.com424ad342012-09-18 23:16:02 +00001207<SPAN class="stylepoint_section">Decision: </SPAN>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001208 Avoid these features in
1209 your code.
1210 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001211 </DIV></DIV>
1212 </DIV>
1213 </DIV>
1214 <DIV class="">
1215<H2 name="Python_Style_Rules" id="Python_Style_Rules">Python Style Rules</H2>
1216 <DIV class="">
1217<H3><A name="Semicolons" id="Semicolons">Semicolons</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001218<SPAN class="link_button" id="link-Semicolons__button" name="link-Semicolons__button"><A href="?showone=Semicolons#Semicolons">
1219 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001220 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Semicolons')" name="Semicolons__button" id="Semicolons__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001221 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001222 Do not terminate your lines with semi-colons and do not use
1223 semi-colons to put two commands on the same line.
mmentovai9ec7bd62009-12-03 22:25:38 +00001224 </DIV>
1225 <DIV class=""><DIV class="stylepoint_body" name="Semicolons__body" id="Semicolons__body" style="display: none">
mmentovai9ec7bd62009-12-03 22:25:38 +00001226 </DIV></DIV>
1227 </DIV>
1228 <DIV class="">
1229<H3><A name="Line_length" id="Line_length">Line length</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001230<SPAN class="link_button" id="link-Line_length__button" name="link-Line_length__button"><A href="?showone=Line_length#Line_length">
1231 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001232 </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 +00001233 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001234 Maximum line length is <em>80 characters</em>.
mmentovai9ec7bd62009-12-03 22:25:38 +00001235 </DIV>
1236 <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 +00001237 <p>
mark@chromium.org8190c132013-03-21 16:03:26 +00001238 Exceptions:
1239 <ul>
1240 <li>Long import statements.</li>
1241 <li>URLs in comments.</li>
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001242
mark@chromium.org8190c132013-03-21 16:03:26 +00001243 </ul>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001244 </p>
1245
1246 <p>
mark@chromium.orge33361f2011-11-04 16:55:22 +00001247 Do not use backslash line continuation.
1248 </p>
1249
1250 <p>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001251 Make use of Python's
1252
mark@chromium.org8190c132013-03-21 16:03:26 +00001253 <a HREF="http://docs.python.org/reference/lexical_analysis.html#implicit-line-joining">implicit
apicard@google.comf900c2c2009-07-23 20:09:56 +00001254 line joining inside parentheses, brackets and braces</a>.
1255 If necessary, you can add an extra pair of parentheses around an
1256 expression.
1257 </p>
1258
1259
mmentovai9ec7bd62009-12-03 22:25:38 +00001260 <DIV class=""><PRE>Yes: foo_bar(self, width, height, color='black', design=None, x='foo',
apicard@google.comf900c2c2009-07-23 20:09:56 +00001261 emphasis=None, highlight=0)
1262
1263 if (width == 0 and height == 0 and
mmentovai9ec7bd62009-12-03 22:25:38 +00001264 color == 'red' and emphasis == 'strong'):</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001265
1266
1267 <p>
1268 When a literal string won't fit on a single line, use parentheses for
1269 implicit line joining.
1270 </p>
1271
mmentovai9ec7bd62009-12-03 22:25:38 +00001272 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001273<span class="external"></span>x = ('This will build a very long long '
mmentovai9ec7bd62009-12-03 22:25:38 +00001274<span class="external"></span> 'long long long long long long string')</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001275
1276 <p>
mark@chromium.org8190c132013-03-21 16:03:26 +00001277 Within comments, put long URLs on their own line if necessary.
1278 </p>
1279
1280 <DIV class=""><PRE>Yes: <span class="external"></span># See details at
1281 <span class="external"></span># http://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.html</PRE></DIV>
1282
1283 <DIV class=""><PRE class="badcode">No: <span class="external"></span># See details at
1284 <span class="external"></span># http://www.example.com/us/developer/documentation/api/content/\
1285 <span class="external"></span># v2.0/csv_file_name_extension_full_specification.html</PRE></DIV>
1286
1287 <p>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001288 Make note of the indentation of the elements in the line
apicard@google.com424ad342012-09-18 23:16:02 +00001289 continuation examples above; see the
mark@chromium.orgc8c76a22012-11-28 20:26:27 +00001290 <a HREF="#Indentation">indentation</a>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001291 section for explanation.
1292 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001293 </DIV></DIV>
1294 </DIV>
1295 <DIV class="">
1296<H3><A name="Parentheses" id="Parentheses">Parentheses</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001297<SPAN class="link_button" id="link-Parentheses__button" name="link-Parentheses__button"><A href="?showone=Parentheses#Parentheses">
1298 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001299 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Parentheses')" name="Parentheses__button" id="Parentheses__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001300 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001301 Use parentheses sparingly.
mmentovai9ec7bd62009-12-03 22:25:38 +00001302 </DIV>
1303 <DIV class=""><DIV class="stylepoint_body" name="Parentheses__body" id="Parentheses__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001304 <p>
apicard@google.com424ad342012-09-18 23:16:02 +00001305 Do not use them in return statements or conditional statements unless
1306 using parentheses for implied line continuation. (See above.)
apicard@google.comf900c2c2009-07-23 20:09:56 +00001307 It is however fine to use parentheses around tuples.
1308 </p>
1309
mmentovai9ec7bd62009-12-03 22:25:38 +00001310<DIV class=""><PRE>Yes: <span class="external"></span>if foo:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001311 <span class="external"> </span>bar()
1312 <span class="external"></span>while x:
1313 <span class="external"> </span>x = bar()
1314 <span class="external"></span>if x and y:
1315 <span class="external"> </span>bar()
1316 <span class="external"></span>if not x:
1317 <span class="external"> </span>bar()
1318 <span class="external"></span>return foo
mmentovai9ec7bd62009-12-03 22:25:38 +00001319 <span class="external"></span>for (x, y) in dict.items(): ...</PRE></DIV>
1320<DIV class=""><PRE class="badcode">No: <span class="external"></span>if (x):
apicard@google.comf900c2c2009-07-23 20:09:56 +00001321 <span class="external"> </span>bar()
1322 <span class="external"></span>if not(x):
1323 <span class="external"> </span>bar()
mmentovai9ec7bd62009-12-03 22:25:38 +00001324 <span class="external"></span>return (foo)</PRE></DIV>
1325 </DIV></DIV>
1326 </DIV>
1327 <DIV class="">
1328<H3><A name="Indentation" id="Indentation">Indentation</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001329<SPAN class="link_button" id="link-Indentation__button" name="link-Indentation__button"><A href="?showone=Indentation#Indentation">
1330 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001331 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Indentation')" name="Indentation__button" id="Indentation__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001332 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001333 Indent your code blocks with <em>4 spaces</em>.
mmentovai9ec7bd62009-12-03 22:25:38 +00001334 </DIV>
1335 <DIV class=""><DIV class="stylepoint_body" name="Indentation__body" id="Indentation__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001336 <p>
1337 Never use tabs or mix tabs and spaces.
1338 In cases of implied line continuation, you should align wrapped elements
1339 either vertically, as per the examples in the
1340 <a HREF="#Line_length">line length</a> section; or using a hanging
1341 indent of 4 spaces, in which case there should be no argument on
1342 the first line.
1343 </p>
1344
1345
mmentovai9ec7bd62009-12-03 22:25:38 +00001346<DIV class=""><PRE>Yes: # Aligned with opening delimiter
apicard@google.comf900c2c2009-07-23 20:09:56 +00001347 foo = long_function_name(var_one, var_two,
1348 var_three, var_four)
1349
1350 # 4-space hanging indent; nothing on first line
1351 foo = long_function_name(
1352 var_one, var_two, var_three,
mmentovai9ec7bd62009-12-03 22:25:38 +00001353 var_four)</PRE></DIV>
1354<DIV class=""><PRE class="badcode">No: <span class="external"></span># Stuff on first line forbidden
apicard@google.comf900c2c2009-07-23 20:09:56 +00001355 <span class="external"></span>foo = long_function_name(var_one, var_two,
1356 <span class="external"></span> var_three, var_four)
1357
1358 <span class="external"></span># 2-space hanging indent forbidden
1359 <span class="external"></span>foo = long_function_name(
1360 <span class="external"></span> var_one, var_two, var_three,
mmentovai9ec7bd62009-12-03 22:25:38 +00001361 <span class="external"></span> var_four)</PRE></DIV>
1362 </DIV></DIV>
1363 </DIV>
1364 <DIV class="">
1365<H3><A name="Blank_Lines" id="Blank_Lines">Blank Lines</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001366<SPAN class="link_button" id="link-Blank_Lines__button" name="link-Blank_Lines__button"><A href="?showone=Blank_Lines#Blank_Lines">
1367 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001368 </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 +00001369 <DIV style="display:inline;" class="">
apicard@google.com424ad342012-09-18 23:16:02 +00001370 Two blank lines between top-level definitions, one blank line
apicard@google.comf900c2c2009-07-23 20:09:56 +00001371 between method definitions.
mmentovai9ec7bd62009-12-03 22:25:38 +00001372 </DIV>
1373 <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 +00001374 <p>
1375 Two blank lines between top-level definitions, be they function
1376 or class definitions. One blank line between method definitions
1377 and between the <code>class</code> line and the first method.
1378 Use single blank lines as you judge appropriate within functions or
1379 methods.
1380 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001381 </DIV></DIV>
1382 </DIV>
1383 <DIV class="">
1384<H3><A name="Whitespace" id="Whitespace">Whitespace</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001385<SPAN class="link_button" id="link-Whitespace__button" name="link-Whitespace__button"><A href="?showone=Whitespace#Whitespace">
1386 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001387 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Whitespace')" name="Whitespace__button" id="Whitespace__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001388 <DIV style="display:inline;" class="">
apicard@google.com424ad342012-09-18 23:16:02 +00001389 Follow standard typographic rules for the use of spaces around
apicard@google.comf900c2c2009-07-23 20:09:56 +00001390 punctuation.
mmentovai9ec7bd62009-12-03 22:25:38 +00001391 </DIV>
1392 <DIV class=""><DIV class="stylepoint_body" name="Whitespace__body" id="Whitespace__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001393 <p>
1394 No whitespace inside parentheses, brackets or braces.
1395 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001396<DIV class=""><PRE>Yes: <span class="external"></span>spam(ham[1], {eggs: 2}, [])</PRE></DIV>
1397<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 +00001398 <p>
1399 No whitespace before a comma, semicolon, or colon. Do use
1400 whitespace after a comma, semicolon, or colon except at the end
1401 of the line.
1402 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001403<DIV class=""><PRE>Yes: <span class="external"></span>if x == 4:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001404 <span class="external"> </span>print x, y
mmentovai9ec7bd62009-12-03 22:25:38 +00001405 <span class="external"></span>x, y = y, x</PRE></DIV>
1406<DIV class=""><PRE class="badcode">No: <span class="external"></span>if x == 4 :
apicard@google.comf900c2c2009-07-23 20:09:56 +00001407 <span class="external"> </span>print x , y
mmentovai9ec7bd62009-12-03 22:25:38 +00001408 <span class="external"></span>x , y = y , x</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001409 <p>
1410 No whitespace before the open paren/bracket that starts an argument list,
1411 indexing or slicing.
1412 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001413 <DIV class=""><PRE>Yes: <span class="external"></span>spam(1)</PRE></DIV>
1414<DIV class=""><PRE class="badcode">No: <span class="external"></span>spam (1)</PRE></DIV>
1415<DIV class=""><PRE>Yes: <span class="external"></span>dict['key'] = list[index]</PRE></DIV>
1416<DIV class=""><PRE class="badcode">No: <span class="external"></span>dict ['key'] = list [index]</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001417
1418 <p>
1419 Surround binary operators with a single space on either side for
1420 assignment (<code>=</code>), comparisons (<code>==, &lt;, &gt;, !=,
1421 &lt;&gt;, &lt;=, &gt;=, in, not in, is, is not</code>), and Booleans
1422 (<code>and, or, not</code>). Use your better judgment for the
1423 insertion of spaces around arithmetic operators but always be
1424 consistent about whitespace on either side of a binary operator.
1425 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001426<DIV class=""><PRE>Yes: <span class="external"></span>x == 1</PRE></DIV>
1427<DIV class=""><PRE class="badcode">No: <span class="external"></span>x&lt;1</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001428 <p>
1429 Don't use spaces around the '=' sign when used to indicate a
1430 keyword argument or a default parameter value.
1431 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001432<DIV class=""><PRE>Yes: <span class="external"></span>def complex(real, imag=0.0): return magic(r=real, i=imag)</PRE></DIV>
1433<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 +00001434
1435 <p>
1436 Don't use spaces to vertically align tokens on consecutive lines, since it
1437 becomes a maintenance burden (applies to <code>:</code>, <code>#</code>,
1438 <code>=</code>, etc.):
1439 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001440<DIV class=""><PRE>Yes:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001441 foo = 1000 # comment
1442 long_name = 2 # comment that should not be aligned
1443
1444 dictionary = {
apicard@google.com424ad342012-09-18 23:16:02 +00001445 'foo': 1,
1446 'long_name': 2,
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001447 }</PRE></DIV>
mmentovai9ec7bd62009-12-03 22:25:38 +00001448<DIV class=""><PRE class="badcode">No:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001449 foo = 1000 # comment
1450 long_name = 2 # comment that should not be aligned
1451
1452 dictionary = {
apicard@google.com424ad342012-09-18 23:16:02 +00001453 'foo' : 1,
1454 'long_name': 2,
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001455 }</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001456
1457
mmentovai9ec7bd62009-12-03 22:25:38 +00001458 </DIV></DIV>
1459 </DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001460
mmentovaicd4ce0f2011-03-29 20:30:47 +00001461 <a name="Python_Interpreter"></a>
1462 <DIV class="">
1463<H3><A name="Shebang_Line" id="Shebang_Line">Shebang Line</A></H3>
1464<SPAN class="link_button" id="link-Shebang_Line__button" name="link-Shebang_Line__button"><A href="?showone=Shebang_Line#Shebang_Line">
1465 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001466 </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 +00001467 <DIV style="display:inline;" class="">
mark@chromium.orge33361f2011-11-04 16:55:22 +00001468 Most <code>.py</code> files do not need to start with a
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001469 <code>#!</code> line. Start the main file of a
1470 program with
1471 <code>#!/usr/bin/python</code> with an optional single digit
1472 <code>2</code> or <code>3</code> suffix per
1473 <a href="http://www.python.org/dev/peps/pep-0394/">PEP-394</a>.
mmentovaicd4ce0f2011-03-29 20:30:47 +00001474 </DIV>
1475 <DIV class=""><DIV class="stylepoint_body" name="Shebang_Line__body" id="Shebang_Line__body" style="display: none">
1476
1477 <p>
mark@chromium.orge33361f2011-11-04 16:55:22 +00001478 This line is used by the kernel to find the Python interpreter, but is
1479 ignored by Python when importing modules. It is only necessary on a
1480 file that will be executed directly.
mmentovaicd4ce0f2011-03-29 20:30:47 +00001481 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001482 </DIV></DIV>
1483 </DIV>
mmentovaicd4ce0f2011-03-29 20:30:47 +00001484
mmentovai9ec7bd62009-12-03 22:25:38 +00001485 <DIV class="">
1486<H3><A name="Comments" id="Comments">Comments</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001487<SPAN class="link_button" id="link-Comments__button" name="link-Comments__button"><A href="?showone=Comments#Comments">
1488 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001489 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Comments')" name="Comments__button" id="Comments__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001490 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001491 Be sure to use the right style for module, function, method and in-line
1492 comments.
mmentovai9ec7bd62009-12-03 22:25:38 +00001493 </DIV>
1494 <DIV class=""><DIV class="stylepoint_body" name="Comments__body" id="Comments__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001495
1496 <P class="">
1497<SPAN class="stylepoint_subsection">Doc Strings</SPAN>
1498
1499 <p>
1500 Python has a unique commenting style using doc strings. A doc
1501 string is a string that is the first statement in a package,
1502 module, class or function. These strings can be extracted
1503 automatically through the <code>__doc__</code> member of the
1504 object and are used by <code>pydoc</code>. (Try running
1505 <code>pydoc</code> on your module to see how it looks.) Our
1506 convention for doc strings is to use the three double-quote
1507 format for strings. A doc string should be organized as a
1508 summary line (one physical line) terminated by a period,
1509 question mark, or exclamation point, followed by a blank line,
1510 followed by the rest of the doc string starting at the same
1511 cursor position as the first quote of the first line. There are
1512 more formatting guidelines for doc strings below.
1513 </p>
1514
1515 </P>
1516 <P class="">
1517<SPAN class="stylepoint_subsection">Modules</SPAN>
1518
1519
1520
1521 <p>
apicard@google.com424ad342012-09-18 23:16:02 +00001522 Every file should contain license boilerplate.
1523 Choose the appropriate boilerplate for the license used by the project
1524 (for example, Apache 2.0, BSD, LGPL, GPL)
apicard@google.comf900c2c2009-07-23 20:09:56 +00001525 </p>
1526 </P>
1527 <P class="">
1528<SPAN class="stylepoint_subsection">Functions and Methods</SPAN>
1529
1530 <p>
mark@chromium.orge33361f2011-11-04 16:55:22 +00001531 As used in this section "function" applies to methods, function, and
1532 generators.
apicard@google.comf900c2c2009-07-23 20:09:56 +00001533 </p>
1534
mark@chromium.orge33361f2011-11-04 16:55:22 +00001535 <p>
1536 A function must have a docstring, unless it meets all of the following
1537 criteria:
1538 <ul>
1539 <li>not externally visible</li>
1540 <li>very short</li>
1541 <li>obvious</li>
1542 </ul>
1543 </p>
1544
1545 <p>
1546 A docstring should give enough information to write a call to the function
1547 without reading the function's code. A docstring should describe the
1548 function's calling syntax and its semantics, not its implementation. For
1549 tricky code, comments alongside the code are more appropriate than using
1550 docstrings.
1551 </p>
1552
1553 <p>
1554 Certain aspects of a function should be documented in special sections,
1555 listed below. Each section begins with a heading line, which ends with a
1556 colon. Sections should be indented two spaces, except for the heading.
1557 </p>
1558
1559 <dl>
1560 <dt>Args:</dt>
1561 <dd>
1562 List each parameter by name. A description should follow the name, and
1563 be separated by a colon and a space. If the description is too long to
1564 fit on a single 80-character line, use a hanging indent of 2 or 4 spaces
1565 (be consistent with the rest of the file).
1566
1567 <p>
1568 The description should mention required type(s) and the meaning of
1569 the argument.
1570 </p>
1571
1572 <p>
1573 If a function accepts *foo (variable length argument lists) and/or
1574 **bar (arbitrary keyword arguments), they should be listed as *foo and
1575 **bar.
1576 </p>
1577 </dd>
1578
1579 <dt>Returns: (or Yields: for generators)</dt>
1580 <dd>
1581 Describe the type and semantics of the return value. If the function
1582 only returns None, this section is not required.
1583 </dd>
1584
1585 <dt>Raises:</dt>
1586 <dd>
1587 List all exceptions that are relevant to the interface.
1588 </dd>
1589 </dl>
1590
mmentovai9ec7bd62009-12-03 22:25:38 +00001591 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001592<span class="external"></span>def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
1593 <span class="external"> </span>"""Fetches rows from a Bigtable.
1594
1595 <span class="external"> </span>Retrieves rows pertaining to the given keys from the Table instance
1596 <span class="external"> </span>represented by big_table. Silly things may happen if
1597 <span class="external"> </span>other_silly_variable is not None.
1598
1599 <span class="external"> </span>Args:
1600 <span class="external"> </span>big_table: An open Bigtable Table instance.
1601 <span class="external"> </span>keys: A sequence of strings representing the key of each table row
1602 <span class="external"> </span> to fetch.
1603 <span class="external"> </span>other_silly_variable: Another optional variable, that has a much
1604 <span class="external"> </span> longer name than the other args, and which does nothing.
1605
1606 <span class="external"> </span>Returns:
1607 <span class="external"> </span>A dict mapping keys to the corresponding table row data
1608 <span class="external"> </span>fetched. Each row is represented as a tuple of strings. For
1609 <span class="external"> </span>example:
1610
1611 <span class="external"> </span>{'Serak': ('Rigel VII', 'Preparer'),
1612 <span class="external"> </span> 'Zim': ('Irk', 'Invader'),
1613 <span class="external"> </span> 'Lrrr': ('Omicron Persei 8', 'Emperor')}
1614
1615 <span class="external"> </span>If a key from the keys argument is missing from the dictionary,
1616 <span class="external"> </span>then that row was not found in the table.
1617
1618 <span class="external"> </span>Raises:
1619 <span class="external"> </span>IOError: An error occurred accessing the bigtable.Table object.
1620 <span class="external"> </span>"""
1621 <span class="external"> </span>pass
1622<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001623</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001624 </P>
1625 <P class="">
1626<SPAN class="stylepoint_subsection">Classes</SPAN>
1627
1628 <p>
1629 Classes should have a doc string below the class definition describing
1630 the class. If your class has public attributes, they should be documented
1631 here in an Attributes section and follow the same formatting as a
1632 function's Args section.
1633 </p>
1634
mmentovai9ec7bd62009-12-03 22:25:38 +00001635 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001636<span class="external"></span>class SampleClass(object):
1637 <span class="external"> </span>"""Summary of class here.
1638
1639 <span class="external"> </span>Longer class information....
1640 <span class="external"> </span>Longer class information....
1641
1642 <span class="external"> </span>Attributes:
1643 <span class="external"> </span>likes_spam: A boolean indicating if we like SPAM or not.
1644 <span class="external"> </span>eggs: An integer count of the eggs we have laid.
1645 <span class="external"> </span>"""
1646
1647 <span class="external"> </span>def __init__(self, likes_spam=False):
1648 <span class="external"> </span>"""Inits SampleClass with blah."""
1649 <span class="external"> </span>self.likes_spam = likes_spam
1650 <span class="external"> </span>self.eggs = 0
1651
1652 <span class="external"> </span>def public_method(self):
1653 <span class="external"> </span>"""Performs operation blah."""
1654<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001655</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001656
1657 </P>
1658 <P class="">
1659<SPAN class="stylepoint_subsection">Block and Inline Comments</SPAN>
1660
1661 <p>
1662 The final place to have comments is in tricky parts of the
apicard@google.com424ad342012-09-18 23:16:02 +00001663 code. If you're going to have to explain it at the next
1664 <a HREF="http://en.wikipedia.org/wiki/Code_review">code review</a>,
1665 you should comment it now. Complicated operations get a few lines of
apicard@google.comf900c2c2009-07-23 20:09:56 +00001666 comments before the operations
1667 commence. Non-obvious ones get comments at the end of the line.
1668 </p>
1669
mmentovai9ec7bd62009-12-03 22:25:38 +00001670 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001671<span class="external"></span># We use a weighted dictionary search to find out where i is in
1672<span class="external"></span># the array. We extrapolate position based on the largest num
1673<span class="external"></span># in the array and the array size and then do binary search to
1674<span class="external"></span># get the exact number.
1675
1676<span class="external"></span>if i &amp; (i-1) == 0: # true iff i is a power of 2
1677<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001678</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001679
1680 <p>
1681 To improve legibility, these comments should be at least 2 spaces away
1682 from the code.
1683 </p>
1684
1685 <p>
1686 On the other hand, never describe the code. Assume the person
1687 reading the code knows Python (though not what you're trying to
1688 do) better than you do.
1689 </p>
1690
mmentovai9ec7bd62009-12-03 22:25:38 +00001691 <DIV class=""><PRE class="badcode">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001692<span class="external"></span># BAD COMMENT: Now go through the b array and make sure whenever i occurs
1693<span class="external"></span># the next element is i+1
1694<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001695</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001696
1697 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00001698 </DIV></DIV>
1699 </DIV>
1700 <DIV class="">
1701<H3><A name="Classes" id="Classes">Classes</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001702<SPAN class="link_button" id="link-Classes__button" name="link-Classes__button"><A href="?showone=Classes#Classes">
1703 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001704 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Classes')" name="Classes__button" id="Classes__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001705 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001706 If a class inherits from no other base classes, explicitly inherit
1707 from <code>object</code>. This also applies to nested classes.
mmentovai9ec7bd62009-12-03 22:25:38 +00001708 </DIV>
1709 <DIV class=""><DIV class="stylepoint_body" name="Classes__body" id="Classes__body" style="display: none">
mmentovai9ec7bd62009-12-03 22:25:38 +00001710 <DIV class=""><PRE>Yes: <span class="external"></span>class SampleClass(object):
apicard@google.comf900c2c2009-07-23 20:09:56 +00001711 <span class="external"> </span>pass
1712
1713
1714 <span class="external"></span>class OuterClass(object):
1715
1716 <span class="external"> </span>class InnerClass(object):
1717 <span class="external"> </span>pass
1718
1719
1720 <span class="external"></span>class ChildClass(ParentClass):
1721 <span class="external"> </span>"""Explicitly inherits from another class already."""
1722<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001723</PRE></DIV>
apicard@google.com424ad342012-09-18 23:16:02 +00001724 <DIV class=""><PRE class="badcode">No: <span class="external"></span>class SampleClass:
1725 <span class="external"> </span>pass
apicard@google.comf900c2c2009-07-23 20:09:56 +00001726
apicard@google.com424ad342012-09-18 23:16:02 +00001727
1728 <span class="external"></span>class OuterClass:
1729
1730 <span class="external"> </span>class InnerClass:
1731 <span class="external"> </span>pass
1732<span class="external"></span>
1733</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001734 <p>Inheriting from <code>object</code> is needed to make properties work
apicard@google.com424ad342012-09-18 23:16:02 +00001735 properly, and it will protect your code from one particular potential
apicard@google.comf900c2c2009-07-23 20:09:56 +00001736 incompatibility with Python 3000. It also defines
1737 special methods that implement the default semantics of objects including
1738 <code>__new__</code>, <code>__init__</code>, <code>__delattr__</code>,
1739 <code>__getattribute__</code>, <code>__setattr__</code>,
1740 <code>__hash__</code>, <code>__repr__</code>, and <code>__str__</code>.
1741 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001742 </DIV></DIV>
1743 </DIV>
1744 <DIV class="">
1745<H3><A name="Strings" id="Strings">Strings</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001746<SPAN class="link_button" id="link-Strings__button" name="link-Strings__button"><A href="?showone=Strings#Strings">
1747 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001748 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Strings')" name="Strings__button" id="Strings__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001749 <DIV style="display:inline;" class="">
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001750 Use the <code>format</code> method or the <code>%</code> operator for
1751 formatting strings, even when the parameters are all strings. Use your
1752 best judgement to decide between <code>+</code> and <code>%</code>
1753 (or <code>format</code>) though.
mmentovai9ec7bd62009-12-03 22:25:38 +00001754 </DIV>
1755 <DIV class=""><DIV class="stylepoint_body" name="Strings__body" id="Strings__body" style="display: none">
apicard@google.com424ad342012-09-18 23:16:02 +00001756
mmentovai9ec7bd62009-12-03 22:25:38 +00001757<DIV class=""><PRE>Yes: <span class="external"></span>x = a + b
apicard@google.comf900c2c2009-07-23 20:09:56 +00001758 <span class="external"></span>x = '%s, %s!' % (imperative, expletive)
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001759 <span class="external"></span>x = '{}, {}!'.format(imperative, expletive)
1760 <span class="external"></span>x = 'name: %s; score: %d' % (name, n)
1761 <span class="external"></span>x = 'name: {}; score: {}'.format(name, n)</PRE></DIV>
apicard@google.com424ad342012-09-18 23:16:02 +00001762<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 +00001763 <span class="external"></span>x = '{}{}'.format(a, b) # use + in this case
apicard@google.com424ad342012-09-18 23:16:02 +00001764 <span class="external"></span>x = imperative + ', ' + expletive + '!'
1765 <span class="external"></span>x = 'name: ' + name + '; score: ' + str(n)</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001766
1767 <p>
1768 Avoid using the <code>+</code> and <code>+=</code> operators to
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001769 accumulate a string within a loop. Since strings are immutable, this
apicard@google.comf900c2c2009-07-23 20:09:56 +00001770 creates unnecessary temporary objects and results in quadratic rather
mark@chromium.org5684bbc2013-07-12 18:53:13 +00001771 than linear running time. Instead, add each substring to a list
1772 and <code>''.join</code> the list after the loop terminates (or, write
1773 each substring to a <code>io.BytesIO</code> buffer).
apicard@google.comf900c2c2009-07-23 20:09:56 +00001774 </p>
1775
mmentovai9ec7bd62009-12-03 22:25:38 +00001776<DIV class=""><PRE>Yes: <span class="external"></span>items = ['&lt;table&gt;']
apicard@google.comf900c2c2009-07-23 20:09:56 +00001777 <span class="external"></span>for last_name, first_name in employee_list:
1778 <span class="external"> </span>items.append('&lt;tr&gt;&lt;td&gt;%s, %s&lt;/td&gt;&lt;/tr&gt;' % (last_name, first_name))
1779 <span class="external"></span>items.append('&lt;/table&gt;')
mmentovai9ec7bd62009-12-03 22:25:38 +00001780 <span class="external"></span>employee_table = ''.join(items)</PRE></DIV>
apicard@google.com424ad342012-09-18 23:16:02 +00001781<DIV class=""><PRE class="badcode">No: <span class="external"></span>employee_table = '&lt;table&gt;'
1782 <span class="external"></span>for last_name, first_name in employee_list:
1783 <span class="external"> </span>employee_table += '&lt;tr&gt;&lt;td&gt;%s, %s&lt;/td&gt;&lt;/tr&gt;' % (last_name, first_name)
1784 <span class="external"></span>employee_table += '&lt;/table&gt;'</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001785
1786 <p>
1787 Use <code>"""</code> for multi-line strings rather than
1788 <code>'''</code>. Note, however, that it is often cleaner to
1789 use implicit line joining since multi-line strings do
1790 not flow with the indentation of the rest of the program:
1791 </p>
1792
apicard@google.com424ad342012-09-18 23:16:02 +00001793<DIV class=""><PRE>Ye<span class="external"></span>s:
1794 <span class="external"></span>print ("This is much nicer.\n"
1795 <span class="external"></span> "Do it this way.\n")</PRE></DIV>
1796<DIV class=""><PRE class="badcode"> No<span class="external"></span>:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001797 <span class="external"></span>print """This is pretty ugly.
1798Don'<span class="external"></span>t do this.
1799"""<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001800</PRE></DIV>
apicard@google.com424ad342012-09-18 23:16:02 +00001801
1802 </DIV></DIV>
1803 </DIV>
1804 <DIV class="">
1805<H3><A name="Files_and_Sockets" id="Files_and_Sockets">Files and Sockets</A></H3>
1806<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">
1807 link
1808 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Files_and_Sockets')" name="Files_and_Sockets__button" id="Files_and_Sockets__button"></SPAN>
1809 <DIV style="display:inline;" class="">
1810 Explicitly close files and sockets when done with them.
1811 </DIV>
1812 <DIV class=""><DIV class="stylepoint_body" name="Files_and_Sockets__body" id="Files_and_Sockets__body" style="display: none">
1813 <p>
1814 Leaving files, sockets or other file-like objects open unnecessarily
1815 has many downsides, including:
1816
1817 <ul>
1818 <li>They may consume limited system resources, such as file
1819 descriptors. Code that deals with many such objects may exhaust
1820 those resources unnecessarily if they're not returned to the
1821 system promptly after use.</li>
1822 <li>Holding files open may prevent other actions being performed on
1823 them, such as moves or deletion.</li>
1824 <li>Files and sockets that are shared throughout a program may
1825 inadvertantly be read from or written to after logically being
1826 closed. If they are actually closed, attempts to read or write
1827 from them will throw exceptions, making the problem known
1828 sooner.</li>
1829 </ul>
1830 </p>
1831
1832 <p>
1833 Furthermore, while files and sockets are automatically closed when the
1834 file object is destructed, tying the life-time of the file object to
1835 the state of the file is poor practice, for several reasons:
1836
1837 <ul>
1838 <li>There are no guarantees as to when the runtime will actually run
1839 the file's destructor. Different Python implementations use
1840 different memory management techniques, such as delayed Garbage
1841 Collection, which may increase the object's lifetime arbitrarily
1842 and indefinitely.</li>
1843 <li>Unexpected references to the file may keep it around longer than
1844 intended (e.g. in tracebacks of exceptions, inside globals,
1845 etc).</li>
1846 </ul>
1847 </p>
1848
1849 <p>
1850 The preferred way to manage files is using the <a HREF="http://docs.python.org/reference/compound_stmts.html#the-with-statement">
1851 "with" statement</a>:
1852 </p>
1853
1854<DIV class=""><PRE>
1855<span class="external"></span>with open("hello.txt") as hello_file:
1856 <span class="external"> </span>for line in hello_file:
1857 <span class="external"> </span>print line</PRE></DIV>
1858
1859 <p>
1860 For file-like objects that do not support the "with" statement, use
1861 contextlib.closing():
1862 </p>
1863
1864<DIV class=""><PRE>
1865<span class="external"></span>import contextlib
1866
1867<span class="external"></span>with contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page:
1868 <span class="external"> </span>for line in front_page:
1869 <span class="external"> </span>print line</PRE></DIV>
1870
1871 <p>
1872 Legacy AppEngine code using Python 2.5 may enable the "with" statement
1873 using "from __future__ import with_statement".
1874 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001875 </DIV></DIV>
1876 </DIV>
1877 <DIV class="">
1878<H3><A name="TODO_Comments" id="TODO_Comments">TODO Comments</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001879<SPAN class="link_button" id="link-TODO_Comments__button" name="link-TODO_Comments__button"><A href="?showone=TODO_Comments#TODO_Comments">
1880 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001881 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('TODO_Comments')" name="TODO_Comments__button" id="TODO_Comments__button"></SPAN>
1882 <DIV style="display:inline;" class="">
1883 Use <code>TODO</code> comments for code that is temporary, a
1884 short-term solution, or good-enough but not perfect.
1885 </DIV>
1886 <DIV class=""><DIV class="stylepoint_body" name="TODO_Comments__body" id="TODO_Comments__body" style="display: none">
1887 <p>
1888 <code>TODO</code>s should include the string <code>TODO</code> in
1889 all caps, followed by the
1890
1891 name, e-mail address, or other
1892 identifier
1893 of the person who can best provide context about the problem
1894 referenced by the <code>TODO</code>,
1895 in parentheses. A colon is optional. A comment explaining what there
1896 is to do is required. The main purpose is to have
1897 a consistent <code>TODO</code> format that can be searched to find the
1898 person who can provide more details upon request. A
1899 <code>TODO</code> is not a commitment that the person referenced
1900 will fix the problem. Thus when you create a <code>TODO</code>, it is
1901 almost always your
1902
1903 name
1904 that is given.
1905 </p>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001906
mark@chromium.orge33361f2011-11-04 16:55:22 +00001907 <DIV class=""><PRE># TODO(kl@gmail.com): Use a "*" here for string repetition.
1908# TODO(Zeke) Change this to use relations.</PRE></DIV>
1909 <p>
1910 If your <code>TODO</code> is of the form "At a future date do
1911 something" make sure that you either include a very specific
1912 date ("Fix by November 2009") or a very specific event
1913 ("Remove this code when all clients can handle XML responses.").
1914 </p>
1915 </DIV></DIV>
1916 </DIV>
mmentovai9ec7bd62009-12-03 22:25:38 +00001917 <DIV class="">
1918<H3><A name="Imports_formatting" id="Imports_formatting">Imports formatting</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001919<SPAN class="link_button" id="link-Imports_formatting__button" name="link-Imports_formatting__button"><A href="?showone=Imports_formatting#Imports_formatting">
1920 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001921 </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 +00001922 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001923 Imports should be on separate lines.
mmentovai9ec7bd62009-12-03 22:25:38 +00001924 </DIV>
1925 <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 +00001926 <p>
1927 E.g.:
1928 </p>
1929
mmentovai9ec7bd62009-12-03 22:25:38 +00001930<DIV class=""><PRE>Yes: <span class="external"></span>import os
1931 <span class="external"></span>import sys</PRE></DIV>
1932<DIV class=""><PRE class="badcode">No: <span class="external"></span>import os, sys</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001933 <p>
1934 Imports are always put at the top of the file, just after any
1935 module comments and doc strings and before module globals and
1936 constants. Imports should be grouped with the order being most generic
1937 to least generic:
1938 </p>
1939 <ul>
1940 <li>standard library imports</li>
1941 <li>third-party imports</li>
1942
1943 <li>application-specific imports</li>
1944 </ul>
1945 <p>
1946 Within each grouping, imports should be sorted lexicographically,
1947 ignoring case, according to each module's full package path.
1948 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00001949 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001950<span class="external"></span>import foo
1951<span class="external"></span>from foo import bar
1952<span class="external"></span>from foo.bar import baz
1953<span class="external"></span>from foo.bar import Quux
mmentovai9ec7bd62009-12-03 22:25:38 +00001954<span class="external"></span>from Foob import ar</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00001955
1956
mmentovai9ec7bd62009-12-03 22:25:38 +00001957
1958 </DIV></DIV>
1959 </DIV>
1960 <DIV class="">
1961<H3><A name="Statements" id="Statements">Statements</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001962<SPAN class="link_button" id="link-Statements__button" name="link-Statements__button"><A href="?showone=Statements#Statements">
1963 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00001964 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Statements')" name="Statements__button" id="Statements__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00001965 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001966 Generally only one statement per line.
mmentovai9ec7bd62009-12-03 22:25:38 +00001967 </DIV>
1968 <DIV class=""><DIV class="stylepoint_body" name="Statements__body" id="Statements__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00001969 <p>
1970 However, you may put the
1971 result of a test on the same line as the test only if the entire
1972 statement fits on one line. In particular, you can never do so
1973 with <code>try</code>/<code>except</code> since the
1974 <code>try</code> and <code>except</code> can't both fit on the
1975 same line, and you can only do so with an <code>if</code> if
1976 there is no <code>else</code>.
1977 </p>
1978
mmentovai9ec7bd62009-12-03 22:25:38 +00001979 <DIV class=""><PRE>Ye<span class="external"></span>s:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001980
mmentovai9ec7bd62009-12-03 22:25:38 +00001981 <span class="external"></span>if foo: bar(foo)</PRE></DIV>
1982<DIV class=""><PRE class="badcode">No<span class="external"></span>:
apicard@google.comf900c2c2009-07-23 20:09:56 +00001983
1984 <span class="external"></span>if foo: bar(foo)
1985 <span class="external"></span>else: baz(foo)
1986
1987 <span class="external"></span>try: bar(foo)
1988 <span class="external"></span>except ValueError: baz(foo)
1989
1990 <span class="external"></span>try:
1991 <span class="external"> </span>bar(foo)
1992 <span class="external"></span>except ValueError: baz(foo)
1993<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00001994</PRE></DIV>
1995 </DIV></DIV>
1996 </DIV>
1997 <DIV class="">
1998<H3><A name="Access_Control" id="Access_Control">Access Control</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00001999<SPAN class="link_button" id="link-Access_Control__button" name="link-Access_Control__button"><A href="?showone=Access_Control#Access_Control">
2000 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00002001 </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 +00002002 <DIV style="display:inline;" class="">
apicard@google.comf900c2c2009-07-23 20:09:56 +00002003 If an accessor function would be trivial you should use public variables
apicard@google.com424ad342012-09-18 23:16:02 +00002004 instead of accessor functions to avoid the extra cost of function
2005 calls in Python. When more functionality is added you can use
apicard@google.comf900c2c2009-07-23 20:09:56 +00002006 <code>property</code> to keep the syntax consistent.
mmentovai9ec7bd62009-12-03 22:25:38 +00002007 </DIV>
2008 <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 +00002009 <p>
2010 On the other hand, if access is more complex, or the cost of accessing
2011 the variable is significant, you should use function calls (following the
2012 <a HREF="#naming">Naming</a> guidelines) such as <code>get_foo()</code>
2013 and <code>set_foo()</code>. If the past behavior allowed access through a
2014 property, do not bind the new accessor functions to the property. Any
2015 code still attempting to access the variable by the old method should
2016 break visibly so they are made aware of the change in complexity.
2017 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00002018 </DIV></DIV>
2019 </DIV>
2020 <DIV class="">
2021<H3><A name="Naming" id="Naming">Naming</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00002022<SPAN class="link_button" id="link-Naming__button" name="link-Naming__button"><A href="?showone=Naming#Naming">
2023 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00002024 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Naming')" name="Naming__button" id="Naming__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00002025 <DIV style="display:inline;" class="">
mark@chromium.orge33361f2011-11-04 16:55:22 +00002026 <code>module_name, package_name, ClassName,
2027 method_name, ExceptionName,
2028 function_name, GLOBAL_CONSTANT_NAME,
2029 global_var_name, instance_var_name, function_parameter_name,
2030 local_var_name.</code>
mmentovai9ec7bd62009-12-03 22:25:38 +00002031 </DIV>
2032 <DIV class=""><DIV class="stylepoint_body" name="Naming__body" id="Naming__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00002033 <P class="">
2034<SPAN class="stylepoint_subsection">Names to Avoid</SPAN>
2035
2036 <ul>
2037 <li>single character names except for counters or iterators</li>
2038 <li>dashes (<code>-</code>) in any package/module name</li>
2039 <li>
apicard@google.com424ad342012-09-18 23:16:02 +00002040<code>__double_leading_and_trailing_underscore__</code> names
apicard@google.comf900c2c2009-07-23 20:09:56 +00002041 (reserved by Python)</li>
2042 </ul>
2043
2044 </P>
2045 <P class="">
2046<SPAN class="stylepoint_subsection">Naming Convention</SPAN>
2047
2048 <ul>
2049 <li>
2050 "Internal" means internal to a module or protected
2051 or private within a class.</li>
2052 <li>
2053 Prepending a single underscore (<code>_</code>) has some
2054 support for protecting module variables and functions (not included
2055 with <code>import * from</code>). Prepending a double underscore
2056 (<code>__</code>) to an instance variable or method
2057 effectively serves to make the variable or method private to its class
2058 (using name mangling).</li>
2059 <li>
apicard@google.com424ad342012-09-18 23:16:02 +00002060 Place related classes and top-level functions together in a
apicard@google.comf900c2c2009-07-23 20:09:56 +00002061 module. Unlike Java,
2062 there is no need to limit yourself to one class per module.</li>
2063 <li>
2064 Use CapWords for class names, but lower_with_under.py for module names.
2065 Although there are many existing modules named CapWords.py, this is now
apicard@google.com424ad342012-09-18 23:16:02 +00002066 discouraged because it's confusing when the module happens to be
2067 named after a class. ("wait -- did I write
apicard@google.comf900c2c2009-07-23 20:09:56 +00002068 <code>import StringIO</code> or <code>from StringIO import
2069 StringIO</code>?")</li>
2070 </ul>
2071
2072 </P>
2073 <P class="">
2074<SPAN class="stylepoint_subsection">Guidelines derived from Guido's Recommendations</SPAN>
2075
2076 <table rules="all" border="1" cellspacing="2" cellpadding="2">
2077
2078 <tr>
2079 <th>Type</th>
2080 <th>Public</th>
2081 <th>Internal</th>
2082 </tr>
2083
2084
2085
2086 <tr>
2087 <td>Packages</td>
2088 <td><code>lower_with_under</code></td>
2089 <td></td>
2090 </tr>
2091
2092 <tr>
2093 <td>Modules</td>
2094 <td><code>lower_with_under</code></td>
2095 <td><code>_lower_with_under</code></td>
2096 </tr>
2097
2098 <tr>
2099 <td>Classes</td>
2100 <td><code>CapWords</code></td>
2101 <td><code>_CapWords</code></td>
2102 </tr>
2103
2104 <tr>
2105 <td>Exceptions</td>
2106 <td><code>CapWords</code></td>
2107 <td></td>
2108 </tr>
2109
2110
2111
2112 <tr>
2113 <td>Functions</td>
2114 <td><code>lower_with_under()</code></td>
2115 <td><code>_lower_with_under()</code></td>
2116 </tr>
2117
2118 <tr>
2119 <td>Global/Class Constants</td>
2120 <td><code>CAPS_WITH_UNDER</code></td>
2121 <td><code>_CAPS_WITH_UNDER</code></td>
2122 </tr>
2123
2124 <tr>
2125 <td>Global/Class Variables</td>
2126 <td><code>lower_with_under</code></td>
2127 <td><code>_lower_with_under</code></td>
2128 </tr>
2129
2130 <tr>
2131 <td>Instance Variables</td>
2132 <td><code>lower_with_under</code></td>
2133 <td><code>_lower_with_under (protected) or __lower_with_under (private)</code></td>
2134 </tr>
2135
2136
2137
2138 <tr>
2139 <td>Method Names</td>
2140 <td><code>lower_with_under()</code></td>
2141 <td><code>_lower_with_under() (protected) or __lower_with_under() (private)</code></td>
2142 </tr>
2143
2144 <tr>
2145 <td>Function/Method Parameters</td>
2146 <td><code>lower_with_under</code></td>
2147 <td></td>
2148 </tr>
2149
2150 <tr>
2151 <td>Local Variables</td>
2152 <td><code>lower_with_under</code></td>
2153 <td></td>
2154 </tr>
2155
2156
2157 </table>
2158
2159
2160 </P>
mmentovai9ec7bd62009-12-03 22:25:38 +00002161 </DIV></DIV>
2162 </DIV>
2163 <DIV class="">
2164<H3><A name="Main" id="Main">Main</A></H3>
mmentovai8411f0c2010-08-04 17:46:16 +00002165<SPAN class="link_button" id="link-Main__button" name="link-Main__button"><A href="?showone=Main#Main">
2166 link
mark@chromium.orge33361f2011-11-04 16:55:22 +00002167 </A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Main')" name="Main__button" id="Main__button"></SPAN>
mmentovai9ec7bd62009-12-03 22:25:38 +00002168 <DIV style="display:inline;" class="">
apicard@google.com424ad342012-09-18 23:16:02 +00002169 Even a file meant to be used as a script should be importable and a
2170 mere import should not have the side effect of executing the script's
2171 main functionality. The main functionality should be in a main()
apicard@google.comf900c2c2009-07-23 20:09:56 +00002172 function.
mmentovai9ec7bd62009-12-03 22:25:38 +00002173 </DIV>
2174 <DIV class=""><DIV class="stylepoint_body" name="Main__body" id="Main__body" style="display: none">
apicard@google.comf900c2c2009-07-23 20:09:56 +00002175 <p>
2176 In Python,
2177 <code>pychecker</code>, <code>pydoc</code>, and unit tests
2178 require modules to be importable. Your code should always check
2179 <code>if __name__ == '__main__'</code> before executing your
2180 main program so that the main program is not executed when the
apicard@google.com424ad342012-09-18 23:16:02 +00002181 module is imported.
apicard@google.comf900c2c2009-07-23 20:09:56 +00002182
2183 </p>
2184
2185
2186
2187
2188
2189
2190
mmentovai9ec7bd62009-12-03 22:25:38 +00002191 <DIV class=""><PRE>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002192<span class="external"></span>def main():
2193 <span class="external"> </span>...
2194
2195<span class="external"></span>if __name__ == '__main__':
2196 <span class="external"> </span>main()
2197<span class="external"></span>
mmentovai9ec7bd62009-12-03 22:25:38 +00002198</PRE></DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002199
2200 <p>
2201 All code at the top level will be executed when the module is
2202 imported. Be careful not to call functions, create objects, or
2203 perform other operations that should not be executed when the
2204 file is being <code>pycheck</code>ed or <code>pydoc</code>ed.
2205 </p>
mmentovai9ec7bd62009-12-03 22:25:38 +00002206 </DIV></DIV>
2207 </DIV>
2208 </DIV>
apicard@google.comf900c2c2009-07-23 20:09:56 +00002209
2210<H2>Parting Words</H2>
2211 <p>
2212 <em>BE CONSISTENT</em>.
2213 </p>
2214
2215 <p>
2216 If you're editing code, take a few minutes to look at the code
2217 around you and determine its style. If they use spaces around
2218 all their arithmetic operators, you should too. If their
2219 comments have little boxes of hash marks around them, make your
2220 comments have little boxes of hash marks around them too.
2221 </p>
2222
2223 <p>
2224 The point of having style guidelines is to have a common vocabulary
2225 of coding so people can concentrate on what you're saying rather
2226 than on how you're saying it. We present global style rules here so
2227 people know the vocabulary, but local style is also important. If
2228 code you add to a file looks drastically different from the existing
2229 code around it, it throws readers out of their rhythm when they go to
2230 read it. Avoid this.
2231 </p>
2232
2233
2234
2235<p align="right">
mark@chromium.org5684bbc2013-07-12 18:53:13 +00002236Revision 2.54
apicard@google.comf900c2c2009-07-23 20:09:56 +00002237</p>
2238
2239
2240<address>
2241 Amit Patel<br>
2242 Antoine Picard<br>
2243 Eugene Jhong<br>
2244 Jeremy Hylton<br>
2245 Matt Smart<br>
2246 Mike Shields<br>
2247</address>
2248</BODY>
2249</HTML>