1
<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">
3
<TITLE>Google Python Style Guide</TITLE>
4
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
5
<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">
9
function ShowHideByName(bodyName, buttonName) {
12
if (document.getElementsByName) {
13
bodyElements = document.getElementsByName(bodyName);
14
linkElement = document.getElementsByName('link-' + buttonName)[0];
16
bodyElements = [document.getElementById(bodyName)];
17
linkElement = document.getElementById('link-' + buttonName);
19
if (bodyElements.length != 1) {
20
alert("ShowHideByName() got the wrong number of bodyElements: " + bodyElements.length);
22
var bodyElement = bodyElements[0];
24
if (document.getElementsByName) {
25
var buttonElements = document.getElementsByName(buttonName);
26
buttonElement = buttonElements[0];
28
buttonElement = document.getElementById(buttonName);
30
if (bodyElement.style.display == "none" || bodyElement.style.display == "") {
31
bodyElement.style.display = "inline";
32
linkElement.style.display = "block";
33
buttonElement.innerHTML = '▽';
35
bodyElement.style.display = "none";
36
linkElement.style.display = "none";
37
buttonElement.innerHTML = '▶';
42
function ShowHideAll() {
44
if (document.getElementsByName) {
45
var allButtons = document.getElementsByName("show_hide_all_button");
46
allButton = allButtons[0];
48
allButton = document.getElementById("show_hide_all_button");
50
if (allButton.innerHTML == '▽') {
51
allButton.innerHTML = '▶';
52
SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "none", '▶');
54
allButton.innerHTML = '▽';
55
SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "inline", '▽');
59
// Recursively sets state of all children
60
// of a particular node.
61
function SetHiddenState(root, newState, newButton) {
62
for (var i = 0; i != root.length; i++) {
63
SetHiddenState(root[i].childNodes, newState, newButton);
64
if (root[i].className == 'showhide_button') {
65
root[i].innerHTML = newButton;
67
if (root[i].className == 'stylepoint_body' ||
68
root[i].className == 'link_button') {
69
root[i].style.display = newState;
75
window.onload = function() {
76
// if the URL contains "?showall=y", expand the details of all children
78
var showHideAllRegex = new RegExp("[\\?&](showall)=([^&#]*)");
79
var showHideAllValue = showHideAllRegex.exec(window.location.href);
80
if (showHideAllValue != null) {
81
if (showHideAllValue[2] == "y") {
82
SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "inline", '▽');
84
SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "none", '▶');
87
var showOneRegex = new RegExp("[\\?&](showone)=([^&#]*)");
88
var showOneValue = showOneRegex.exec(window.location.href);
89
if (showOneValue != null) {
90
var body_name = showOneValue[2] + '__body';
91
var button_name = showOneValue[2] + '__button';
92
ShowHideByName(body_name, button_name);
100
<H1>Google Python Style Guide</H1>
114
<DIV style="margin-left: 50%; font-size: 75%;">
116
Each style point has a summary for which additional information is available
117
by toggling the accompanying arrow button that looks this way:
118
<SPAN class="showhide_button" style="margin-left: 0; float: none">▶</SPAN>.
119
You may toggle all summaries with the big arrow button:
121
<DIV style=" font-size: larger; margin-left: +2em;">
122
<SPAN class="showhide_button" style="font-size: 180%; float: none" onclick="javascript:ShowHideAll()" name="show_hide_all_button" id="show_hide_all_button">▶</SPAN>
127
<DIV class="toc_title">Table of Contents</DIV>
129
<TR valign="top" class="">
130
<TD><DIV class="toc_category"><A href="#Python_Language_Rules">Python Language Rules</A></DIV></TD>
131
<TD><DIV class="toc_stylepoint">
132
<SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#pychecker">pychecker</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Imports">Imports</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Packages">Packages</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Exceptions">Exceptions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Global_variables">Global variables</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Nested/Local/Inner_Classes_and_Functions">Nested/Local/Inner Classes and Functions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#List_Comprehensions">List Comprehensions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Default_Iterators_and_Operators">Default Iterators and Operators</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Generators">Generators</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Lambda_Functions">Lambda Functions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Default_Argument_Values">Default Argument Values</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Properties">Properties</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#True/False_evaluations">True/False evaluations</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Deprecated_Language_Features">Deprecated Language Features</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Lexical_Scoping">Lexical Scoping</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Function_and_Method_Decorators">Function and Method Decorators</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Threading">Threading</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Power_Features">Power Features</A></SPAN> </DIV></TD>
134
<TR valign="top" class="">
135
<TD><DIV class="toc_category"><A href="#Python_Style_Rules">Python Style Rules</A></DIV></TD>
136
<TD><DIV class="toc_stylepoint">
137
<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="#Python_Interpreter">Python Interpreter</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Comments">Comments</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Classes">Classes</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Strings">Strings</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#TODO_Comments">TODO Comments</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Imports_formatting">Imports formatting</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Statements">Statements</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Access_Control">Access Control</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Naming">Naming</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Main">Main</A></SPAN> </DIV></TD>
142
<H2 name="Important_Note" id="Important_Note">Important Note</H2>
144
<H3><A name="Displaying_Hidden_Details_in_this_Guide" id="Displaying_Hidden_Details_in_this_Guide">Displaying Hidden Details in this Guide</A></H3>
145
<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">
147
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Displaying_Hidden_Details_in_this_Guide__body','Displaying_Hidden_Details_in_this_Guide__button')" name="Displaying_Hidden_Details_in_this_Guide__button" id="Displaying_Hidden_Details_in_this_Guide__button">▶</SPAN>
148
<DIV style="display:inline;" class="">
149
This style guide contains many details that are initially
150
hidden from view. They are marked by the triangle icon, which you
151
see here on your left. Click it now.
152
You should see "Hooray" appear below.
154
<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">
156
Hooray! Now you know you can expand points to get more
157
details. Alternatively, there's a "toggle all" at the
158
top of this document.
164
<H2 name="Background" id="Background">Background</H2>
166
Python is the main scripting language used at Google. This
167
style guide is a list of <em>do</em>s and <em>don't</em>s for Python
176
<H2 name="Python_Language_Rules" id="Python_Language_Rules">Python Language Rules</H2>
179
<H3><A name="pychecker" id="pychecker">pychecker</A></H3>
180
<SPAN class="link_button" id="link-pychecker__button" name="link-pychecker__button"><A href="?showone=pychecker#pychecker">
182
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('pychecker__body','pychecker__button')" name="pychecker__button" id="pychecker__button">▶</SPAN>
183
<DIV style="display:inline;" class="">
184
Run <code>pychecker</code> over your code.
186
<DIV class=""><DIV class="stylepoint_body" name="pychecker__body" id="pychecker__body" style="display: none">
188
<SPAN class="stylepoint_section">Definition: </SPAN>
189
PyChecker is a tool for finding bugs in Python source code. It finds
190
problems that are typically caught by a compiler for less dynamic
191
languages like C and C++. It is similar to lint. Because of the
192
dynamic nature of Python, some warnings may be incorrect; however,
193
spurious warnings should be fairly infrequent.
196
<SPAN class="stylepoint_section">Pros: </SPAN>
197
Catches easy-to-miss errors like typos, use-vars-before-assignment, etc.
200
<SPAN class="stylepoint_section">Cons: </SPAN>
201
<code>pychecker</code> isn't perfect. To take
202
advantage of it, we'll need to sometimes: a) Write around it b)
203
Suppress its warnings c) Improve it or d) Ignore it.
206
<SPAN class="stylepoint_section">Decision: </SPAN>
207
Make sure you run <code>pychecker</code> on your code.
211
For information on how to run <code>pychecker</code>, see the
212
<a HREF="http://pychecker.sourceforge.net">pychecker
216
To suppress warnings, you can set a module-level variable named
217
<code>__pychecker__</code> to suppress appropriate warnings.
221
<span class="external"></span>__pychecker__ = 'no-callinit no-classattr'</PRE></DIV>
223
Suppressing in this way has the advantage that we can easily search
224
for suppressions and revisit them.
227
You can get a list of pychecker warnings by doing
228
<code>pychecker --help</code>.
231
Unused argument warnings can be suppressed by using `_' as the
232
identifier for the unused argument or prefixing the argument name with
233
`unused_'. In situations where changing the argument names is
234
infeasible, you can mention them at the beginning of the function.
238
<span class="external"></span>def foo(a, unused_b, unused_c, d=None, e=None):
239
<span class="external"> </span>(d, e) = (d, e) # Silence pychecker
240
<span class="external"> </span>return a
241
<span class="external"></span>
244
Ideally, pychecker would be extended to ensure that such `unused
245
declarations' were true.
251
<H3><A name="Imports" id="Imports">Imports</A></H3>
252
<SPAN class="link_button" id="link-Imports__button" name="link-Imports__button"><A href="?showone=Imports#Imports">
254
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Imports__body','Imports__button')" name="Imports__button" id="Imports__button">▶</SPAN>
255
<DIV style="display:inline;" class="">
256
Use <code>import</code>s for packages and modules only.
258
<DIV class=""><DIV class="stylepoint_body" name="Imports__body" id="Imports__body" style="display: none">
260
<SPAN class="stylepoint_section">Definition: </SPAN>
261
Reusability mechanism for sharing code from one module to another.
264
<SPAN class="stylepoint_section">Pros: </SPAN>
265
Simplest and most commonly used way of sharing things.
268
<SPAN class="stylepoint_section">Cons: </SPAN> <code>from foo import *</code> or
269
<code>from foo import Bar</code> is
270
very nasty and can lead to serious maintenance issues because
271
it makes it hard to find module dependencies.
274
<SPAN class="stylepoint_section">Decision: </SPAN>
275
Use <code>import x</code> for importing packages and modules.
276
Use <code>from x import y</code> only when <code>x</code> is a
277
package and <code>y</code> is a module. This allows the
278
importer to refer to the module without specifying the full
279
package prefix. For example the module
280
<code>sound.effects.echo</code> may be imported as follows:
283
<span class="external"></span>from sound.effects import echo
284
<span class="external"></span>...
285
<span class="external"></span>echo.echofilter(input, output, delay=0.7, atten=4)
286
<span class="external"></span>
289
Even if the module is in the same package, do not directly import
290
the module without the full package name. This might cause the
291
package to be imported twice (with unintended side effects) when the
292
"main" module that is used to start an application lives inside a
293
package (and uses modules from that same package).
298
<H3><A name="Packages" id="Packages">Packages</A></H3>
299
<SPAN class="link_button" id="link-Packages__button" name="link-Packages__button"><A href="?showone=Packages#Packages">
301
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Packages__body','Packages__button')" name="Packages__button" id="Packages__button">▶</SPAN>
302
<DIV style="display:inline;" class="">
303
Import and refer to each module using the full pathname location of
306
<DIV class=""><DIV class="stylepoint_body" name="Packages__body" id="Packages__body" style="display: none">
308
<SPAN class="stylepoint_section">Pros: </SPAN>
309
Avoids conflicts in module names. Makes it easier to find modules.
312
<SPAN class="stylepoint_section">Cons: </SPAN>
313
Makes it harder to deploy code because you have to replicate the
317
<SPAN class="stylepoint_section">Decision: </SPAN>
318
All new code should refer to modules based on their package
322
Imports should be as follows:
326
<DIV class=""><PRE># Reference in code with complete name.
327
import sound.effects.echo
329
# Reference in code with just module name.
330
from sound.effects import echo
336
<H3><A name="Exceptions" id="Exceptions">Exceptions</A></H3>
337
<SPAN class="link_button" id="link-Exceptions__button" name="link-Exceptions__button"><A href="?showone=Exceptions#Exceptions">
339
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Exceptions__body','Exceptions__button')" name="Exceptions__button" id="Exceptions__button">▶</SPAN>
340
<DIV style="display:inline;" class="">
341
Exceptions are allowed but must be used carefully.
343
<DIV class=""><DIV class="stylepoint_body" name="Exceptions__body" id="Exceptions__body" style="display: none">
345
<SPAN class="stylepoint_section">Definition: </SPAN>
346
Exceptions are a means of breaking out of the normal flow of control
347
of a code block to handle errors or other exceptional conditions.
350
<SPAN class="stylepoint_section">Pros: </SPAN>
351
The control flow of normal operation code is not cluttered by
352
error-handling code. It also allows the control flow to skip multiple
353
frames when a certain condition occurs, e.g., returning from N
354
nested functions in one step instead of having to carry-through
358
<SPAN class="stylepoint_section">Cons: </SPAN>
359
May cause the control flow to be confusing. Easy to miss error
360
cases when making library calls.
363
<SPAN class="stylepoint_section">Decision: </SPAN>
366
Exceptions must follow certain conditions:
369
<li>Raise exceptions like this: <code>raise MyException("Error
370
message")</code> or <code>raise MyException</code>. Do not
371
use the two-argument form (<code>raise MyException, "Error
372
message"</code>) or deprecated string-based exceptions
373
(<code>raise "Error message"</code>).</li>
374
<li>Modules or packages should define their own domain-specific
375
base exception class, which should inherit from the built-in
376
Exception class. The base exception for a module should be called
379
<span class="external"></span>class Error(Exception):
380
<span class="external"> </span>pass</PRE></DIV>
382
<li>Never use catch-all <code>except:</code> statements, or
383
catch <code>Exception</code> or <code>StandardError</code>,
384
unless you are re-raising the exception or in the outermost
385
block in your thread (and printing an error message). Python
386
is very tolerant in this regard and <code>except:</code> will
387
really catch everything including Python syntax errors. It is
388
easy to hide real bugs using <code>except:</code>.</li>
389
<li>Minimize the amount of code in a
390
<code>try</code>/<code>except</code> block. The larger the
391
body of the <code>try</code>, the more likely that an
392
exception will be raised by a line of code that you didn't
393
expect to raise an exception. In those cases,
394
the <code>try</code>/<code>except</code> block hides a real
396
<li>Use the <code>finally</code> clause to execute code whether
397
or not an exception is raised in the <code>try</code> block.
398
This is often useful for cleanup, i.e., closing a file.</li>
404
<H3><A name="Global_variables" id="Global_variables">Global variables</A></H3>
405
<SPAN class="link_button" id="link-Global_variables__button" name="link-Global_variables__button"><A href="?showone=Global_variables#Global_variables">
407
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Global_variables__body','Global_variables__button')" name="Global_variables__button" id="Global_variables__button">▶</SPAN>
408
<DIV style="display:inline;" class="">
409
Avoid global variables.
411
<DIV class=""><DIV class="stylepoint_body" name="Global_variables__body" id="Global_variables__body" style="display: none">
413
<SPAN class="stylepoint_section">Definition: </SPAN>
414
Variables that are declared at the module level.
417
<SPAN class="stylepoint_section">Pros: </SPAN>
421
<SPAN class="stylepoint_section">Cons: </SPAN>
422
Has the potential to change module behavior during the import,
423
because assignments to module-level variables are done when the
427
<SPAN class="stylepoint_section">Decision: </SPAN>
428
Avoid global variables in favor of class variables. Some
431
<li>Default options for scripts.</li>
432
<li>Module-level constants. For example: <code>PI = 3.14159</code>.
433
Constants should be named using all caps with underscores;
434
see <a HREF="#Naming">Naming</a> below.</li>
435
<li>It is sometimes useful for globals to cache values needed
436
or returned by functions.</li>
437
<li>If needed, globals should be made internal to the module
438
and accessed through public module level functions;
439
see <a HREF="#Naming">Naming</a> below.</li>
445
<H3><A name="Nested/Local/Inner_Classes_and_Functions" id="Nested/Local/Inner_Classes_and_Functions">Nested/Local/Inner Classes and Functions</A></H3>
446
<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">
448
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Nested/Local/Inner_Classes_and_Functions__body','Nested/Local/Inner_Classes_and_Functions__button')" name="Nested/Local/Inner_Classes_and_Functions__button" id="Nested/Local/Inner_Classes_and_Functions__button">▶</SPAN>
449
<DIV style="display:inline;" class="">
450
Nested/local/inner classes and functions are fine.
452
<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">
454
<SPAN class="stylepoint_section">Definition: </SPAN>
455
A class can be defined inside of a method, function, or class. A
456
function can be defined inside a method or function. Nested functions
457
have read-only access to variables defined in enclosing scopes.
460
<SPAN class="stylepoint_section">Pros: </SPAN>
461
Allows definition of utility classes and functions that are only
462
used inside of a very limited scope. Very <a HREF="http://en.wikipedia.org/wiki/Abstract_data_type">ADT</a>-y.
465
<SPAN class="stylepoint_section">Cons: </SPAN>
466
Instances of nested or local classes cannot be pickled.
469
<SPAN class="stylepoint_section">Decision: </SPAN>
475
<H3><A name="List_Comprehensions" id="List_Comprehensions">List Comprehensions</A></H3>
476
<SPAN class="link_button" id="link-List_Comprehensions__button" name="link-List_Comprehensions__button"><A href="?showone=List_Comprehensions#List_Comprehensions">
478
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('List_Comprehensions__body','List_Comprehensions__button')" name="List_Comprehensions__button" id="List_Comprehensions__button">▶</SPAN>
479
<DIV style="display:inline;" class="">
480
Okay to use for simple cases.
482
<DIV class=""><DIV class="stylepoint_body" name="List_Comprehensions__body" id="List_Comprehensions__body" style="display: none">
484
<SPAN class="stylepoint_section">Definition: </SPAN>
485
List comprehensions and generator expressions provide a concise
486
and efficient way to create lists and iterators without
487
resorting to the use of <code>map()</code>,
488
<code>filter()</code>, or <code>lambda</code>.
491
<SPAN class="stylepoint_section">Pros: </SPAN>
492
Simple list comprehensions can be clearer and simpler than
493
other list creation techniques. Generator expressions can be
494
very efficient, since they avoid the creation of a list
498
<SPAN class="stylepoint_section">Cons: </SPAN>
499
Complicated list comprehensions or generator expressions can be
503
<SPAN class="stylepoint_section">Decision: </SPAN>
504
Okay to use for simple cases. Each portion must fit on one line:
505
mapping expression, <code>for</code> clause, filter expression.
506
Multiple <code>for</code> clauses or filter expressions are not
507
permitted. Use loops instead when things get more complicated.
510
<DIV class=""><PRE class="badcode">No<span class="external"></span>:
511
<span class="external"></span>result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]
513
<span class="external"></span>return ((x, y, z)
514
<span class="external"></span> for x in xrange(5)
515
<span class="external"></span> for y in xrange(5)
516
<span class="external"></span> if x != y
517
<span class="external"></span> for z in xrange(5)
518
<span class="external"></span> if y != z)</PRE></DIV>
519
<DIV class=""><PRE>Ye<span class="external"></span>s:
520
<span class="external"></span>result = []
521
<span class="external"></span>for x in range(10):
522
<span class="external"> </span>for y in range(5):
523
<span class="external"> </span>if x * y > 10:
524
<span class="external"> </span>result.append((x, y))
526
<span class="external"></span>for x in xrange(5):
527
<span class="external"> </span>for y in xrange(5):
528
<span class="external"> </span>if x != y:
529
<span class="external"> </span>for z in xrange(5):
530
<span class="external"> </span>if y != z:
531
<span class="external"> </span>yield (x, y, z)
533
<span class="external"></span>return ((x, complicated_transform(x))
534
<span class="external"></span> for x in long_generator_function(parameter)
535
<span class="external"></span> if x is not None)
537
<span class="external"></span>squares = [x * x for x in range(10)]
539
<span class="external"></span>eat(jelly_bean for jelly_bean in jelly_beans
540
<span class="external"></span> if jelly_bean.color == 'black')</PRE></DIV>
544
<H3><A name="Default_Iterators_and_Operators" id="Default_Iterators_and_Operators">Default Iterators and Operators</A></H3>
545
<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">
547
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Default_Iterators_and_Operators__body','Default_Iterators_and_Operators__button')" name="Default_Iterators_and_Operators__button" id="Default_Iterators_and_Operators__button">▶</SPAN>
548
<DIV style="display:inline;" class="">
549
Use default iterators and operators for types that support them,
550
like lists, dictionaries, and files.
552
<DIV class=""><DIV class="stylepoint_body" name="Default_Iterators_and_Operators__body" id="Default_Iterators_and_Operators__body" style="display: none">
554
<SPAN class="stylepoint_section">Definition: </SPAN>
555
Container types, like dictionaries and lists, define default
556
iterators and membership test operators ("in" and "not in").
559
<SPAN class="stylepoint_section">Pros: </SPAN>
560
The default iterators and operators are simple and efficient.
561
They express the operation directly, without extra method calls.
562
A function that uses default operators is generic. It can be
563
used with any type that supports the operation.
566
<SPAN class="stylepoint_section">Cons: </SPAN>
567
You can't tell the type of objects by reading the method names
568
(e.g. has_key() means a dictionary). This is also an advantage.
571
<SPAN class="stylepoint_section">Decision: </SPAN> Use default iterators and operators for types
572
that support them, like lists, dictionaries, and files. The
573
built-in types define iterator methods, too. Prefer these
574
methods to methods that return lists, except that you should not
575
mutate a container while iterating over it.
577
<DIV class=""><PRE>Yes: <span class="external"></span>for key in adict: ...
578
<span class="external"></span>if key not in adict: ...
579
<span class="external"></span>if obj in alist: ...
580
<span class="external"></span>for line in afile: ...
581
<span class="external"></span>for k, v in dict.iteritems(): ...</PRE></DIV>
582
<DIV class=""><PRE class="badcode">No: <span class="external"></span>for key in adict.keys(): ...
583
<span class="external"></span>if not adict.has_key(key): ...
584
<span class="external"></span>for line in afile.readlines(): ...</PRE></DIV>
589
<H3><A name="Generators" id="Generators">Generators</A></H3>
590
<SPAN class="link_button" id="link-Generators__button" name="link-Generators__button"><A href="?showone=Generators#Generators">
592
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Generators__body','Generators__button')" name="Generators__button" id="Generators__button">▶</SPAN>
593
<DIV style="display:inline;" class="">
594
Use generators as needed.
596
<DIV class=""><DIV class="stylepoint_body" name="Generators__body" id="Generators__body" style="display: none">
598
<SPAN class="stylepoint_section">Definition: </SPAN>
599
A generator function returns an iterator that yields a value each
600
time it executes a yield statement. After it yields a value, the
601
runtime state of the generator function is suspended until the
602
next value is needed.
605
<SPAN class="stylepoint_section">Pros: </SPAN>
606
Simpler code, because the state of local variables and control flow
607
are preserved for each call. A generator uses less memory than a
608
function that creates an entire list of values at once.
611
<SPAN class="stylepoint_section">Cons: </SPAN>
615
<SPAN class="stylepoint_section">Decision: </SPAN>
616
Fine. Use "Yields:" rather than "Returns:" in the
617
doc string for generator functions.
622
<H3><A name="Lambda_Functions" id="Lambda_Functions">Lambda Functions</A></H3>
623
<SPAN class="link_button" id="link-Lambda_Functions__button" name="link-Lambda_Functions__button"><A href="?showone=Lambda_Functions#Lambda_Functions">
625
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Lambda_Functions__body','Lambda_Functions__button')" name="Lambda_Functions__button" id="Lambda_Functions__button">▶</SPAN>
626
<DIV style="display:inline;" class="">
629
<DIV class=""><DIV class="stylepoint_body" name="Lambda_Functions__body" id="Lambda_Functions__body" style="display: none">
631
<SPAN class="stylepoint_section">Definition: </SPAN>
632
Lambdas define anonymous functions in an expression, as
633
opposed to a statement. They are often used to define callbacks or
634
operators for higher-order functions like <code>map()</code> and
635
<code>filter()</code>.
638
<SPAN class="stylepoint_section">Pros: </SPAN>
642
<SPAN class="stylepoint_section">Cons: </SPAN> Harder to read and debug than local functions. The
643
lack of names means stack traces are more difficult to
644
understand. Expressiveness is limited because the function may
645
only contain an expression.
648
<SPAN class="stylepoint_section">Decision: </SPAN>
649
Okay to use them for one-liners. If the code inside the lambda
650
function is any longer than 60–80 chars, it's probably better to
651
define it as a regular (nested) function.
653
For common operations like multiplication, use the functions from the
654
<code>operator</code> module instead of lambda functions. For
655
example, prefer <code>operator.mul</code> to <code>lambda
662
<H3><A name="Default_Argument_Values" id="Default_Argument_Values">Default Argument Values</A></H3>
663
<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">
665
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Default_Argument_Values__body','Default_Argument_Values__button')" name="Default_Argument_Values__button" id="Default_Argument_Values__button">▶</SPAN>
666
<DIV style="display:inline;" class="">
669
<DIV class=""><DIV class="stylepoint_body" name="Default_Argument_Values__body" id="Default_Argument_Values__body" style="display: none">
671
<SPAN class="stylepoint_section">Definition: </SPAN>
672
You can specify values for variables at the end of a function's
673
parameter list, e.g., <code>def foo(a, b=0):</code>. If
674
<code>foo</code> is called with only one argument,
675
<code>b</code> is set to 0. If it is called with two arguments,
676
<code>b</code> has the value of the second argument.
679
<SPAN class="stylepoint_section">Pros: </SPAN>
680
Often you have a function that uses lots of default values,
681
but—rarely—you want to override the
682
defaults. Default argument values provide an easy way to do this,
683
without having to define lots of functions for the rare
684
exceptions. Also, Python does not support overloaded
685
methods/functions and default arguments are an easy way of
686
"faking" the overloading behavior.
689
<SPAN class="stylepoint_section">Cons: </SPAN>
690
Default arguments are evaluated once at module load
691
time. This may cause problems if the argument is a mutable
692
object such as a list or a dictionary. If the function modifies
693
the object (e.g., by appending an item to a list), the default
697
<SPAN class="stylepoint_section">Decision: </SPAN>
698
Okay to use with the following caveats:
700
Do not use mutable objects as default values in the function or method
703
<DIV class=""><PRE>Yes: <span class="external"></span>def foo(a, b=None):
704
<span class="external"> </span>if b is None:
705
<span class="external"> </span>b = []</PRE></DIV>
706
<DIV class=""><PRE class="badcode">No: <span class="external"></span>def foo(a, b=[]):
707
<span class="external"> </span>...</PRE></DIV>
709
Calling code must use named values for arguments with a default value.
710
This helps document the code somewhat and helps prevent and detect
711
interface breakage when more arguments are added.
714
<span class="external"></span>def foo(a, b=1):
715
<span class="external"> </span>...</PRE></DIV>
716
<DIV class=""><PRE>Yes: <span class="external"></span>foo(1)
717
<span class="external"></span>foo(1, b=2)</PRE></DIV>
718
<DIV class=""><PRE class="badcode">No: <span class="external"></span>foo(1, 2)</PRE></DIV>
723
<H3><A name="Properties" id="Properties">Properties</A></H3>
724
<SPAN class="link_button" id="link-Properties__button" name="link-Properties__button"><A href="?showone=Properties#Properties">
726
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Properties__body','Properties__button')" name="Properties__button" id="Properties__button">▶</SPAN>
727
<DIV style="display:inline;" class="">
728
Use properties for accessing or setting data where you would
729
normally have used simple, lightweight accessor or setter methods.
731
<DIV class=""><DIV class="stylepoint_body" name="Properties__body" id="Properties__body" style="display: none">
733
<SPAN class="stylepoint_section">Definition: </SPAN> A way to wrap method calls for getting and
734
setting an attribute as a standard attribute access when the
735
computation is lightweight.
738
<SPAN class="stylepoint_section">Pros: </SPAN> Readability is increased by eliminating explicit
739
get and set method calls for simple attribute access. Allows
740
calculations to be lazy. Considered the Pythonic way to
741
maintain the interface of a class. In terms of performance,
742
allowing properties bypasses needing trivial accessor methods
743
when a direct variable access is reasonable. This also allows
744
accessor methods to be added in the future without breaking the
748
<SPAN class="stylepoint_section">Cons: </SPAN> Properties are specified after the getter and
749
setter methods are declared, requiring one to notice they are
750
used for properties farther down in the code (except for readonly
751
properties created with the <code>@property</code> decorator - see
752
below). Must inherit from
753
<code>object</code>. Can hide side-effects much like operator
754
overloading. Can be confusing for subclasses.
757
<SPAN class="stylepoint_section">Decision: </SPAN> Use properties in new code to access or
758
set data where you would normally have used simple, lightweight
759
accessor or setter methods. Read-only properties should be created
760
with the <code>@property</code>
761
<a HREF="#Function_and_Method_Decorators">decorator</a>.
763
<p><a id="properties-template-dp">
764
Inheritance with properties can be non-obvious if the property itself is
765
not overridden. Thus one must make sure that accessor methods are
766
called indirectly to ensure methods overridden in subclasses are called
767
by the property (using the Template Method DP).
770
<DIV class=""><PRE>Yes: <span class="external"></span>import math
772
<span class="external"></span>class Square(object):
773
<span class="external"> </span>"""A square with two properties: a writable area and a read-only perimeter.
775
<span class="external"> </span>To use:
776
<span class="external"> </span>>>> sq = Square(3)
777
<span class="external"> </span>>>> sq.area
778
<span class="external"> </span>9
779
<span class="external"> </span>>>> sq.perimeter
780
<span class="external"> </span>12
781
<span class="external"> </span>>>> sq.area = 16
782
<span class="external"> </span>>>> sq.side
783
<span class="external"> </span>4
784
<span class="external"> </span>>>> sq.perimeter
785
<span class="external"> </span>16
786
<span class="external"> </span>"""
788
<span class="external"> </span>def __init__(self, side):
789
<span class="external"> </span>self.side = side
791
<span class="external"> </span>def __get_area(self):
792
<span class="external"> </span>"""Calculates the 'area' property."""
793
<span class="external"> </span>return self.side ** 2
795
<span class="external"> </span>def ___get_area(self):
796
<span class="external"> </span>"""Indirect accessor for 'area' property."""
797
<span class="external"> </span>return self.__get_area()
799
<span class="external"> </span>def __set_area(self, area):
800
<span class="external"> </span>"""Sets the 'area' property."""
801
<span class="external"> </span>self.side = math.sqrt(area)
803
<span class="external"> </span>def ___set_area(self, area):
804
<span class="external"> </span>"""Indirect setter for 'area' property."""
805
<span class="external"> </span>self._SetArea(area)
807
<span class="external"> </span>area = property(___get_area, ___set_area,
808
<span class="external"> </span> doc="""Gets or sets the area of the square.""")
810
<span class="external"> </span>@property
811
<span class="external"> </span>def perimeter(self):
812
<span class="external"> </span>return self.side * 4
813
<span class="external"></span>
819
<H3><A name="True/False_evaluations" id="True/False_evaluations">True/False evaluations</A></H3>
820
<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">
822
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('True/False_evaluations__body','True/False_evaluations__button')" name="True/False_evaluations__button" id="True/False_evaluations__button">▶</SPAN>
823
<DIV style="display:inline;" class="">
824
Use the "implicit" false if at all possible.
826
<DIV class=""><DIV class="stylepoint_body" name="True/False_evaluations__body" id="True/False_evaluations__body" style="display: none">
828
<SPAN class="stylepoint_section">Definition: </SPAN> Python evaluates certain values as <code>false</code>
829
when in a boolean context. A quick "rule of thumb" is that all
830
"empty" values are considered <code>false</code> so <code>0, None, [], {},
831
""</code> all evaluate as <code>false</code> in a boolean context.
834
<SPAN class="stylepoint_section">Pros: </SPAN> Conditions using Python booleans are easier to read
835
and less error-prone. In most cases, they're also faster.
838
<SPAN class="stylepoint_section">Cons: </SPAN>
839
May look strange to C/C++ developers.
842
<SPAN class="stylepoint_section">Decision: </SPAN>
843
Use the "implicit" false if at all possible, e.g., <code>if
844
foo:</code> rather than <code>if foo != []:</code>. There are a
845
few caveats that you should keep in mind though:
848
Never use <code>==</code> or <code>!=</code> to compare
849
singletons like <code>None</code>. Use <code>is</code>
850
or <code>is not</code>.</li>
852
<li>Beware of writing <code>if x:</code> when you really mean
853
<code>if x is not None:</code>—e.g., when testing whether
854
a variable or argument that defaults to <code>None</code> was
855
set to some other value. The other value might be a value
856
that's false in a boolean context!</li>
859
Never compare a boolean variable to <code>False</code> using
860
<code>==</code>. Use <code>if not x:</code> instead. If
861
you need to distinguish <code>False</code> from
862
<code>None</code> then chain the expressions,
863
such as <code>if not x and x is not None:</code>.
867
For sequences (strings, lists, tuples), use the fact that
868
empty sequences are false, so <code>if not seq:</code> or
869
<code>if seq:</code> is preferable to <code>if
870
len(seq):</code> or <code>if not
871
len(seq):</code>.</li>
874
When handling integers, implicit false may involve more risk than
875
benefit (i.e., accidentally handling <code>None</code> as 0). You may
876
compare a value which is known to be an integer (and is not the
877
result of <code>len()</code>) against the integer 0.
878
<DIV class=""><PRE>Yes: <span class="external"></span>if not users:
879
<span class="external"> </span>print 'no users'
881
<span class="external"></span>if foo == 0:
882
<span class="external"> </span>self.handle_zero()
884
<span class="external"></span>if i % 10 == 0:
885
<span class="external"> </span>self.handle_multiple_of_ten()</PRE></DIV>
886
<DIV class=""><PRE class="badcode">No: <span class="external"></span>if len(users) == 0:
887
<span class="external"> </span>print 'no users'
889
<span class="external"></span>if foo is not None and not foo:
890
<span class="external"> </span>self.handle_zero()
892
<span class="external"></span>if not i % 10:
893
<span class="external"> </span>self.handle_multiple_of_ten()</PRE></DIV>
897
Note that <code>'0'</code> (i.e., <code>0</code> as string)
898
evaluates to true.</li>
904
<H3><A name="Deprecated_Language_Features" id="Deprecated_Language_Features">Deprecated Language Features</A></H3>
905
<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">
907
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Deprecated_Language_Features__body','Deprecated_Language_Features__button')" name="Deprecated_Language_Features__button" id="Deprecated_Language_Features__button">▶</SPAN>
908
<DIV style="display:inline;" class="">
909
Use string methods instead of the <code>string</code> module
910
where possible. Use function call syntax instead
911
of <code>apply</code>. Use list comprehensions
912
and <code>for</code> loops instead of <code>filter</code>,
913
<code>map</code>, and <code>reduce</code>.
915
<DIV class=""><DIV class="stylepoint_body" name="Deprecated_Language_Features__body" id="Deprecated_Language_Features__body" style="display: none">
917
<SPAN class="stylepoint_section">Definition: </SPAN>
918
Current versions of Python provide alternative constructs
919
that people find generally preferable.
922
<SPAN class="stylepoint_section">Decision: </SPAN>
923
We do not use any Python version which does not support
924
these features, so there is no reason not to use the new
926
<DIV class=""><PRE class="badcode">No: <span class="external"></span>words = string.split(foo, ':')
928
<span class="external"></span>map(lambda x: x[1], filter(lambda x: x[2] == 5, my_list))
930
<span class="external"></span>apply(fn, args, kwargs)</PRE></DIV>
931
<DIV class=""><PRE>Yes: <span class="external"></span>words = foo.split(':')
933
<span class="external"></span>[x[1] for x in my_list if x[2] == 5]
935
<span class="external"></span>fn(*args, **kwargs)</PRE></DIV>
940
<H3><A name="Lexical_Scoping" id="Lexical_Scoping">Lexical Scoping</A></H3>
941
<SPAN class="link_button" id="link-Lexical_Scoping__button" name="link-Lexical_Scoping__button"><A href="?showone=Lexical_Scoping#Lexical_Scoping">
943
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Lexical_Scoping__body','Lexical_Scoping__button')" name="Lexical_Scoping__button" id="Lexical_Scoping__button">▶</SPAN>
944
<DIV style="display:inline;" class="">
947
<DIV class=""><DIV class="stylepoint_body" name="Lexical_Scoping__body" id="Lexical_Scoping__body" style="display: none">
949
<SPAN class="stylepoint_section">Definition: </SPAN>
950
A nested Python function can refer to variables defined in
951
enclosing functions, but can not assign to them. Variable
952
bindings are resolved using lexical scoping, that is, based on
953
the static program text. Any assignment to a name in a block
954
will cause Python to treat all references to that name as a
955
local variable, even if the use precedes the assignment. If a
956
global declaration occurs, the name is treated as a global
960
An example of the use of this feature is:
964
<span class="external"></span>def get_adder(summand1):
965
<span class="external"> </span>"""Returns a function that adds numbers to a given number."""
966
<span class="external"> </span>def adder(summand2):
967
<span class="external"> </span>return summand1 + summand2
969
<span class="external"> </span>return adder
970
<span class="external"></span>
974
<SPAN class="stylepoint_section">Pros: </SPAN>
975
Often results in clearer, more elegant code. Especially comforting
976
to experienced Lisp and Scheme (and Haskell and ML and …)
980
<SPAN class="stylepoint_section">Cons: </SPAN>
981
Can lead to confusing bugs. Such as this example based on
982
<a HREF="http://www.python.org/dev/peps/pep-0227/">PEP-0227</a>:
983
<DIV class=""><PRE class="badcode">
984
<span class="external"></span>i = 4
985
<span class="external"></span>def foo(x):
986
<span class="external"> </span>def bar():
987
<span class="external"> </span>print i,
988
<span class="external"> </span># ...
989
<span class="external"> </span># A bunch of code here
990
<span class="external"> </span># ...
991
<span class="external"> </span>for i in x: # Ah, i *is* local to Foo, so this is what Bar sees
992
<span class="external"> </span>print i,
993
<span class="external"> </span>bar()</PRE></DIV>
995
So <code>foo([1, 2, 3])</code> will print <code>1 2 3 3</code>, not
996
<code>1 2 3 4</code>.
1000
<SPAN class="stylepoint_section">Decision: </SPAN>
1006
<H3><A name="Function_and_Method_Decorators" id="Function_and_Method_Decorators">Function and Method Decorators</A></H3>
1007
<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">
1009
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Function_and_Method_Decorators__body','Function_and_Method_Decorators__button')" name="Function_and_Method_Decorators__button" id="Function_and_Method_Decorators__button">▶</SPAN>
1010
<DIV style="display:inline;" class="">
1011
Use decorators judiciously when there is a clear advantage.
1013
<DIV class=""><DIV class="stylepoint_body" name="Function_and_Method_Decorators__body" id="Function_and_Method_Decorators__body" style="display: none">
1015
<SPAN class="stylepoint_section">Definition: </SPAN>
1017
<a HREF="http://www.python.org/doc/2.4.3/whatsnew/node6.html">Decorators
1018
for Functions and Methods</a>
1019
(a.k.a "the <code>@</code> notation").
1020
The most common decorators are <code>@classmethod</code> and
1021
<code>@staticmethod</code>, for converting ordinary methods to class or
1022
static methods. However, the decorator syntax allows for
1023
user-defined decorators as well. Specifically, for some function
1024
<code>my_decorator</code>, this:
1026
<span class="external"></span>class C(object):
1027
<span class="external"> </span>@my_decorator
1028
<span class="external"> </span>def method(self):
1029
<span class="external"> </span># method body ...
1030
<span class="external"></span>
1035
<span class="external"></span>class C(object):
1036
<span class="external"> </span>def method(self):
1037
<span class="external"> </span># method body ...
1038
<span class="external"> </span>method = my_decorator(method)
1039
<span class="external"></span>
1043
<SPAN class="stylepoint_section">Pros: </SPAN> Elegantly specifies some transformation on a method; the
1044
transformation might eliminate some repetitive code, enforce invariants,
1048
<SPAN class="stylepoint_section">Cons: </SPAN> Decorators can perform arbitrary operations on a
1049
function's arguments or return values, resulting in surprising
1051
Additionally, decorators execute at import time. Failures in decorator
1052
code are pretty much impossible to recover from.
1055
<SPAN class="stylepoint_section">Decision: </SPAN> Use decorators judiciously when there is a clear
1056
advantage. Decorators should follow the same import and naming
1057
guidelines as functions. Decorator pydoc should clearly state that the
1058
function is a decorator. Write unit tests for decorators.
1061
Avoid external dependencies in the decorator itself (e.g. don't rely on
1062
files, sockets, database connections, etc.), since they might not be
1063
available when the decorator runs (at import time, perhaps from
1064
<code>pychecker</code> or other tools). A decorator that is
1065
called with valid parameters should (as much as possible) be guaranteed
1066
to succeed in all cases.
1069
Decorators are a special case of "top level code" - see
1070
<a HREF="#Main">main</a> for more discussion.
1076
<H3><A name="Threading" id="Threading">Threading</A></H3>
1077
<SPAN class="link_button" id="link-Threading__button" name="link-Threading__button"><A href="?showone=Threading#Threading">
1079
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Threading__body','Threading__button')" name="Threading__button" id="Threading__button">▶</SPAN>
1080
<DIV style="display:inline;" class="">
1081
Do not rely on the atomicity of built-in types.
1083
<DIV class=""><DIV class="stylepoint_body" name="Threading__body" id="Threading__body" style="display: none">
1085
While Python's built-in data types such as dictionaries appear
1086
to have atomic operations, there are corner cases where they
1087
aren't atomic (e.g. if <code>__hash__</code> or
1088
<code>__eq__</code> are implemented as Python methods) and their
1089
atomicity should not be relied upon. Neither should you rely on
1090
atomic variable assignment (since this in turn depends on
1095
Use the Queue module's <code>Queue</code> data type as the preferred
1097
communicate data between threads. Otherwise, use the threading
1098
module and its locking primitives. Learn about the proper use
1099
of condition variables so you can use
1100
<code>threading.Condition</code> instead of using lower-level
1106
<H3><A name="Power_Features" id="Power_Features">Power Features</A></H3>
1107
<SPAN class="link_button" id="link-Power_Features__button" name="link-Power_Features__button"><A href="?showone=Power_Features#Power_Features">
1109
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Power_Features__body','Power_Features__button')" name="Power_Features__button" id="Power_Features__button">▶</SPAN>
1110
<DIV style="display:inline;" class="">
1111
Avoid these features.
1113
<DIV class=""><DIV class="stylepoint_body" name="Power_Features__body" id="Power_Features__body" style="display: none">
1115
<SPAN class="stylepoint_section">Definition: </SPAN> Python is an extremely flexible language and
1116
gives you many fancy features such as metaclasses, access to bytecode,
1117
on-the-fly compilation, dynamic inheritance, object reparenting,
1118
import hacks, reflection, modification of system internals,
1122
<SPAN class="stylepoint_section">Pros: </SPAN> These are powerful language features. They can
1123
make your code more compact.
1126
<SPAN class="stylepoint_section">Cons: </SPAN> It's very tempting to use these "cool" features
1127
when they're not absolutely necessary. It's harder to read,
1128
understand, and debug code that's using unusual features
1129
underneath. It doesn't seem that way at first (to the original
1130
author), but when revisiting the code, it tends to be more
1131
difficult than code that is longer but is straightforward.
1134
<SPAN class="stylepoint_section">Decision: </SPAN>
1135
Avoid these features in
1142
<H2 name="Python_Style_Rules" id="Python_Style_Rules">Python Style Rules</H2>
1144
<H3><A name="Semicolons" id="Semicolons">Semicolons</A></H3>
1145
<SPAN class="link_button" id="link-Semicolons__button" name="link-Semicolons__button"><A href="?showone=Semicolons#Semicolons">
1147
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Semicolons__body','Semicolons__button')" name="Semicolons__button" id="Semicolons__button">▶</SPAN>
1148
<DIV style="display:inline;" class="">
1149
Do not terminate your lines with semi-colons and do not use
1150
semi-colons to put two commands on the same line.
1152
<DIV class=""><DIV class="stylepoint_body" name="Semicolons__body" id="Semicolons__body" style="display: none">
1156
<H3><A name="Line_length" id="Line_length">Line length</A></H3>
1157
<SPAN class="link_button" id="link-Line_length__button" name="link-Line_length__button"><A href="?showone=Line_length#Line_length">
1159
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Line_length__body','Line_length__button')" name="Line_length__button" id="Line_length__button">▶</SPAN>
1160
<DIV style="display:inline;" class="">
1161
Maximum line length is <em>80 characters</em>.
1163
<DIV class=""><DIV class="stylepoint_body" name="Line_length__body" id="Line_length__body" style="display: none">
1165
Exception: lines importing modules may end up longer than 80
1166
characters only if using Python 2.4 or
1171
Make use of Python's
1173
<a HREF="http://www.python.org/doc/ref/implicit-joining.html">implicit
1174
line joining inside parentheses, brackets and braces</a>.
1175
If necessary, you can add an extra pair of parentheses around an
1180
<DIV class=""><PRE>Yes: foo_bar(self, width, height, color='black', design=None, x='foo',
1181
emphasis=None, highlight=0)
1183
if (width == 0 and height == 0 and
1184
color == 'red' and emphasis == 'strong'):</PRE></DIV>
1188
When a literal string won't fit on a single line, use parentheses for
1189
implicit line joining.
1193
<span class="external"></span>x = ('This will build a very long long '
1194
<span class="external"></span> 'long long long long long long string')</PRE></DIV>
1197
Make note of the indentation of the elements in the line
1198
continuation examples above; see the
1199
<a HREF="#indentation">indentation</a>
1200
section for explanation.
1205
<H3><A name="Parentheses" id="Parentheses">Parentheses</A></H3>
1206
<SPAN class="link_button" id="link-Parentheses__button" name="link-Parentheses__button"><A href="?showone=Parentheses#Parentheses">
1208
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Parentheses__body','Parentheses__button')" name="Parentheses__button" id="Parentheses__button">▶</SPAN>
1209
<DIV style="display:inline;" class="">
1210
Use parentheses sparingly.
1212
<DIV class=""><DIV class="stylepoint_body" name="Parentheses__body" id="Parentheses__body" style="display: none">
1214
Do not use them in return statements or conditional statements unless
1215
using parentheses for implied line continuation. (See above.)
1216
It is however fine to use parentheses around tuples.
1219
<DIV class=""><PRE>Yes: <span class="external"></span>if foo:
1220
<span class="external"> </span>bar()
1221
<span class="external"></span>while x:
1222
<span class="external"> </span>x = bar()
1223
<span class="external"></span>if x and y:
1224
<span class="external"> </span>bar()
1225
<span class="external"></span>if not x:
1226
<span class="external"> </span>bar()
1227
<span class="external"></span>return foo
1228
<span class="external"></span>for (x, y) in dict.items(): ...</PRE></DIV>
1229
<DIV class=""><PRE class="badcode">No: <span class="external"></span>if (x):
1230
<span class="external"> </span>bar()
1231
<span class="external"></span>if not(x):
1232
<span class="external"> </span>bar()
1233
<span class="external"></span>return (foo)</PRE></DIV>
1237
<H3><A name="Indentation" id="Indentation">Indentation</A></H3>
1238
<SPAN class="link_button" id="link-Indentation__button" name="link-Indentation__button"><A href="?showone=Indentation#Indentation">
1240
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Indentation__body','Indentation__button')" name="Indentation__button" id="Indentation__button">▶</SPAN>
1241
<DIV style="display:inline;" class="">
1242
Indent your code blocks with <em>4 spaces</em>.
1244
<DIV class=""><DIV class="stylepoint_body" name="Indentation__body" id="Indentation__body" style="display: none">
1246
Never use tabs or mix tabs and spaces.
1247
In cases of implied line continuation, you should align wrapped elements
1248
either vertically, as per the examples in the
1249
<a HREF="#Line_length">line length</a> section; or using a hanging
1250
indent of 4 spaces, in which case there should be no argument on
1255
<DIV class=""><PRE>Yes: # Aligned with opening delimiter
1256
foo = long_function_name(var_one, var_two,
1257
var_three, var_four)
1259
# 4-space hanging indent; nothing on first line
1260
foo = long_function_name(
1261
var_one, var_two, var_three,
1262
var_four)</PRE></DIV>
1263
<DIV class=""><PRE class="badcode">No: <span class="external"></span># Stuff on first line forbidden
1264
<span class="external"></span>foo = long_function_name(var_one, var_two,
1265
<span class="external"></span> var_three, var_four)
1267
<span class="external"></span># 2-space hanging indent forbidden
1268
<span class="external"></span>foo = long_function_name(
1269
<span class="external"></span> var_one, var_two, var_three,
1270
<span class="external"></span> var_four)</PRE></DIV>
1274
<H3><A name="Blank_Lines" id="Blank_Lines">Blank Lines</A></H3>
1275
<SPAN class="link_button" id="link-Blank_Lines__button" name="link-Blank_Lines__button"><A href="?showone=Blank_Lines#Blank_Lines">
1277
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Blank_Lines__body','Blank_Lines__button')" name="Blank_Lines__button" id="Blank_Lines__button">▶</SPAN>
1278
<DIV style="display:inline;" class="">
1279
Two blank lines between top-level definitions, one blank line
1280
between method definitions.
1282
<DIV class=""><DIV class="stylepoint_body" name="Blank_Lines__body" id="Blank_Lines__body" style="display: none">
1284
Two blank lines between top-level definitions, be they function
1285
or class definitions. One blank line between method definitions
1286
and between the <code>class</code> line and the first method.
1287
Use single blank lines as you judge appropriate within functions or
1293
<H3><A name="Whitespace" id="Whitespace">Whitespace</A></H3>
1294
<SPAN class="link_button" id="link-Whitespace__button" name="link-Whitespace__button"><A href="?showone=Whitespace#Whitespace">
1296
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Whitespace__body','Whitespace__button')" name="Whitespace__button" id="Whitespace__button">▶</SPAN>
1297
<DIV style="display:inline;" class="">
1298
Follow standard typographic rules for the use of spaces around
1301
<DIV class=""><DIV class="stylepoint_body" name="Whitespace__body" id="Whitespace__body" style="display: none">
1303
No whitespace inside parentheses, brackets or braces.
1305
<DIV class=""><PRE>Yes: <span class="external"></span>spam(ham[1], {eggs: 2}, [])</PRE></DIV>
1306
<DIV class=""><PRE class="badcode">No: <span class="external"></span>spam( ham[ 1 ], { eggs: 2 }, [ ] )</PRE></DIV>
1308
No whitespace before a comma, semicolon, or colon. Do use
1309
whitespace after a comma, semicolon, or colon except at the end
1312
<DIV class=""><PRE>Yes: <span class="external"></span>if x == 4:
1313
<span class="external"> </span>print x, y
1314
<span class="external"></span>x, y = y, x</PRE></DIV>
1315
<DIV class=""><PRE class="badcode">No: <span class="external"></span>if x == 4 :
1316
<span class="external"> </span>print x , y
1317
<span class="external"></span>x , y = y , x</PRE></DIV>
1319
No whitespace before the open paren/bracket that starts an argument list,
1320
indexing or slicing.
1322
<DIV class=""><PRE>Yes: <span class="external"></span>spam(1)</PRE></DIV>
1323
<DIV class=""><PRE class="badcode">No: <span class="external"></span>spam (1)</PRE></DIV>
1324
<DIV class=""><PRE>Yes: <span class="external"></span>dict['key'] = list[index]</PRE></DIV>
1325
<DIV class=""><PRE class="badcode">No: <span class="external"></span>dict ['key'] = list [index]</PRE></DIV>
1328
Surround binary operators with a single space on either side for
1329
assignment (<code>=</code>), comparisons (<code>==, <, >, !=,
1330
<>, <=, >=, in, not in, is, is not</code>), and Booleans
1331
(<code>and, or, not</code>). Use your better judgment for the
1332
insertion of spaces around arithmetic operators but always be
1333
consistent about whitespace on either side of a binary operator.
1335
<DIV class=""><PRE>Yes: <span class="external"></span>x == 1</PRE></DIV>
1336
<DIV class=""><PRE class="badcode">No: <span class="external"></span>x<1</PRE></DIV>
1338
Don't use spaces around the '=' sign when used to indicate a
1339
keyword argument or a default parameter value.
1341
<DIV class=""><PRE>Yes: <span class="external"></span>def complex(real, imag=0.0): return magic(r=real, i=imag)</PRE></DIV>
1342
<DIV class=""><PRE class="badcode">No: <span class="external"></span>def complex(real, imag = 0.0): return magic(r = real, i = imag)</PRE></DIV>
1345
Don't use spaces to vertically align tokens on consecutive lines, since it
1346
becomes a maintenance burden (applies to <code>:</code>, <code>#</code>,
1347
<code>=</code>, etc.):
1349
<DIV class=""><PRE>Yes:
1350
foo = 1000 # comment
1351
long_name = 2 # comment that should not be aligned
1357
<DIV class=""><PRE class="badcode">No:
1358
foo = 1000 # comment
1359
long_name = 2 # comment that should not be aligned
1370
<H3><A name="Python_Interpreter" id="Python_Interpreter">Python Interpreter</A></H3>
1371
<SPAN class="link_button" id="link-Python_Interpreter__button" name="link-Python_Interpreter__button"><A href="?showone=Python_Interpreter#Python_Interpreter">
1373
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Python_Interpreter__body','Python_Interpreter__button')" name="Python_Interpreter__button" id="Python_Interpreter__button">▶</SPAN>
1374
<DIV style="display:inline;" class="">
1375
Modules should begin with
1377
<code>#!/usr/bin/env python<version></code>
1379
<DIV class=""><DIV class="stylepoint_body" name="Python_Interpreter__body" id="Python_Interpreter__body" style="display: none">
1381
Modules should begin with a "shebang" line specifying the Python
1382
interpreter used to execute the program:
1386
<span class="external"></span>#!/usr/bin/env python2.4</PRE></DIV>
1389
Always use the most specific version you can use, e.g.,
1390
<code>/usr/bin/python2.4</code>, not
1391
<code>/usr/bin/python2</code>. This makes it easier to find
1394
upgrading to a different Python version
1395
and also avoids confusion and breakage during use. E.g., Does
1396
<code>/usr/bin/python2</code> mean Python 2.0.1 or Python
1403
<H3><A name="Comments" id="Comments">Comments</A></H3>
1404
<SPAN class="link_button" id="link-Comments__button" name="link-Comments__button"><A href="?showone=Comments#Comments">
1406
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Comments__body','Comments__button')" name="Comments__button" id="Comments__button">▶</SPAN>
1407
<DIV style="display:inline;" class="">
1408
Be sure to use the right style for module, function, method and in-line
1411
<DIV class=""><DIV class="stylepoint_body" name="Comments__body" id="Comments__body" style="display: none">
1414
<SPAN class="stylepoint_subsection">Doc Strings</SPAN>
1417
Python has a unique commenting style using doc strings. A doc
1418
string is a string that is the first statement in a package,
1419
module, class or function. These strings can be extracted
1420
automatically through the <code>__doc__</code> member of the
1421
object and are used by <code>pydoc</code>. (Try running
1422
<code>pydoc</code> on your module to see how it looks.) Our
1423
convention for doc strings is to use the three double-quote
1424
format for strings. A doc string should be organized as a
1425
summary line (one physical line) terminated by a period,
1426
question mark, or exclamation point, followed by a blank line,
1427
followed by the rest of the doc string starting at the same
1428
cursor position as the first quote of the first line. There are
1429
more formatting guidelines for doc strings below.
1434
<SPAN class="stylepoint_subsection">Modules</SPAN>
1439
Every file should contain the following items, in order:
1441
<li>a copyright statement (for example,
1442
<code>Copyright 2008 Google Inc.</code>)</li>
1443
<li>a license boilerplate. Choose the appropriate boilerplate
1444
for the license used by the project (for example, Apache 2.0, BSD,
1446
<li>an author line to identify the original author of the file</li>
1451
<SPAN class="stylepoint_subsection">Functions and Methods</SPAN>
1454
Any function or method which is not both obvious and very short
1455
needs a doc string. Additionally, any externally accessible
1456
function or method regardless of length or simplicity needs a
1457
doc string. The doc string should include what the function does
1458
and have detailed descriptions of the input and output. It
1459
should not, generally, describe how it does it unless it's some
1460
complicated algorithm. For tricky code block/inline comments
1461
within the code are more appropriate. The doc string should give
1462
enough information to write a call to the function without
1463
looking at a single line of the function's code. Args should be
1464
individually documented, an explanation following after a colon,
1465
and should use a uniform hanging indent of 2 or 4 spaces. The
1466
doc string should specify the expected types where specific types
1467
are required. A "Raises:" section should list all exceptions
1468
that can be raised by the function. The doc string for generator
1469
functions should use "Yields:" rather than "Returns:".
1473
<span class="external"></span>def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
1474
<span class="external"> </span>"""Fetches rows from a Bigtable.
1476
<span class="external"> </span>Retrieves rows pertaining to the given keys from the Table instance
1477
<span class="external"> </span>represented by big_table. Silly things may happen if
1478
<span class="external"> </span>other_silly_variable is not None.
1480
<span class="external"> </span>Args:
1481
<span class="external"> </span>big_table: An open Bigtable Table instance.
1482
<span class="external"> </span>keys: A sequence of strings representing the key of each table row
1483
<span class="external"> </span> to fetch.
1484
<span class="external"> </span>other_silly_variable: Another optional variable, that has a much
1485
<span class="external"> </span> longer name than the other args, and which does nothing.
1487
<span class="external"> </span>Returns:
1488
<span class="external"> </span>A dict mapping keys to the corresponding table row data
1489
<span class="external"> </span>fetched. Each row is represented as a tuple of strings. For
1490
<span class="external"> </span>example:
1492
<span class="external"> </span>{'Serak': ('Rigel VII', 'Preparer'),
1493
<span class="external"> </span> 'Zim': ('Irk', 'Invader'),
1494
<span class="external"> </span> 'Lrrr': ('Omicron Persei 8', 'Emperor')}
1496
<span class="external"> </span>If a key from the keys argument is missing from the dictionary,
1497
<span class="external"> </span>then that row was not found in the table.
1499
<span class="external"> </span>Raises:
1500
<span class="external"> </span>IOError: An error occurred accessing the bigtable.Table object.
1501
<span class="external"> </span>"""
1502
<span class="external"> </span>pass
1503
<span class="external"></span>
1507
<SPAN class="stylepoint_subsection">Classes</SPAN>
1510
Classes should have a doc string below the class definition describing
1511
the class. If your class has public attributes, they should be documented
1512
here in an Attributes section and follow the same formatting as a
1513
function's Args section.
1517
<span class="external"></span>class SampleClass(object):
1518
<span class="external"> </span>"""Summary of class here.
1520
<span class="external"> </span>Longer class information....
1521
<span class="external"> </span>Longer class information....
1523
<span class="external"> </span>Attributes:
1524
<span class="external"> </span>likes_spam: A boolean indicating if we like SPAM or not.
1525
<span class="external"> </span>eggs: An integer count of the eggs we have laid.
1526
<span class="external"> </span>"""
1528
<span class="external"> </span>def __init__(self, likes_spam=False):
1529
<span class="external"> </span>"""Inits SampleClass with blah."""
1530
<span class="external"> </span>self.likes_spam = likes_spam
1531
<span class="external"> </span>self.eggs = 0
1533
<span class="external"> </span>def public_method(self):
1534
<span class="external"> </span>"""Performs operation blah."""
1535
<span class="external"></span>
1540
<SPAN class="stylepoint_subsection">Block and Inline Comments</SPAN>
1543
The final place to have comments is in tricky parts of the
1544
code. If you're going to have to explain it at the next
1545
<a HREF="http://en.wikipedia.org/wiki/Code_review">code review</a>,
1546
you should comment it now. Complicated operations get a few lines of
1547
comments before the operations
1548
commence. Non-obvious ones get comments at the end of the line.
1552
<span class="external"></span># We use a weighted dictionary search to find out where i is in
1553
<span class="external"></span># the array. We extrapolate position based on the largest num
1554
<span class="external"></span># in the array and the array size and then do binary search to
1555
<span class="external"></span># get the exact number.
1557
<span class="external"></span>if i & (i-1) == 0: # true iff i is a power of 2
1558
<span class="external"></span>
1562
To improve legibility, these comments should be at least 2 spaces away
1567
On the other hand, never describe the code. Assume the person
1568
reading the code knows Python (though not what you're trying to
1569
do) better than you do.
1572
<DIV class=""><PRE class="badcode">
1573
<span class="external"></span># BAD COMMENT: Now go through the b array and make sure whenever i occurs
1574
<span class="external"></span># the next element is i+1
1575
<span class="external"></span>
1582
<H3><A name="Classes" id="Classes">Classes</A></H3>
1583
<SPAN class="link_button" id="link-Classes__button" name="link-Classes__button"><A href="?showone=Classes#Classes">
1585
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Classes__body','Classes__button')" name="Classes__button" id="Classes__button">▶</SPAN>
1586
<DIV style="display:inline;" class="">
1587
If a class inherits from no other base classes, explicitly inherit
1588
from <code>object</code>. This also applies to nested classes.
1590
<DIV class=""><DIV class="stylepoint_body" name="Classes__body" id="Classes__body" style="display: none">
1591
<DIV class=""><PRE class="badcode">No: <span class="external"></span>class SampleClass:
1592
<span class="external"> </span>pass
1595
<span class="external"></span>class OuterClass:
1597
<span class="external"> </span>class InnerClass:
1598
<span class="external"> </span>pass
1599
<span class="external"></span>
1602
<DIV class=""><PRE>Yes: <span class="external"></span>class SampleClass(object):
1603
<span class="external"> </span>pass
1606
<span class="external"></span>class OuterClass(object):
1608
<span class="external"> </span>class InnerClass(object):
1609
<span class="external"> </span>pass
1612
<span class="external"></span>class ChildClass(ParentClass):
1613
<span class="external"> </span>"""Explicitly inherits from another class already."""
1614
<span class="external"></span>
1617
<p>Inheriting from <code>object</code> is needed to make properties work
1618
properly, and it will protect your code from one particular potential
1619
incompatibility with Python 3000. It also defines
1620
special methods that implement the default semantics of objects including
1621
<code>__new__</code>, <code>__init__</code>, <code>__delattr__</code>,
1622
<code>__getattribute__</code>, <code>__setattr__</code>,
1623
<code>__hash__</code>, <code>__repr__</code>, and <code>__str__</code>.
1628
<H3><A name="Strings" id="Strings">Strings</A></H3>
1629
<SPAN class="link_button" id="link-Strings__button" name="link-Strings__button"><A href="?showone=Strings#Strings">
1631
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Strings__body','Strings__button')" name="Strings__button" id="Strings__button">▶</SPAN>
1632
<DIV style="display:inline;" class="">
1633
Use the <code>%</code> operator for formatting strings,
1634
even when the parameters are all strings. Use your best judgement
1635
to decide between <code>+</code> and <code>%</code> though.
1637
<DIV class=""><DIV class="stylepoint_body" name="Strings__body" id="Strings__body" style="display: none">
1638
<DIV class=""><PRE class="badcode">No: <span class="external"></span>x = '%s%s' % (a, b) # use + in this case
1639
<span class="external"></span>x = imperative + ', ' + expletive + '!'
1640
<span class="external"></span>x = 'name: ' + name + '; score: ' + str(n)</PRE></DIV>
1641
<DIV class=""><PRE>Yes: <span class="external"></span>x = a + b
1642
<span class="external"></span>x = '%s, %s!' % (imperative, expletive)
1643
<span class="external"></span>x = 'name: %s; score: %d' % (name, n)</PRE></DIV>
1646
Avoid using the <code>+</code> and <code>+=</code> operators to
1647
accumulate a string within a loop. Since strings are immutable, this
1648
creates unnecessary temporary objects and results in quadratic rather
1649
than linear running time. Instead, add each substring to a list and
1650
<code>''.join</code> the list after the loop terminates (or, write each
1651
substring to a <code>cStringIO.StringIO</code> buffer).
1654
<DIV class=""><PRE class="badcode">No: <span class="external"></span>employee_table = '<table>'
1655
<span class="external"></span>for last_name, first_name in employee_list:
1656
<span class="external"> </span>employee_table += '<tr><td>%s, %s</td></tr>' % (last_name, first_name)
1657
<span class="external"></span>employee_table += '</table>'</PRE></DIV>
1658
<DIV class=""><PRE>Yes: <span class="external"></span>items = ['<table>']
1659
<span class="external"></span>for last_name, first_name in employee_list:
1660
<span class="external"> </span>items.append('<tr><td>%s, %s</td></tr>' % (last_name, first_name))
1661
<span class="external"></span>items.append('</table>')
1662
<span class="external"></span>employee_table = ''.join(items)</PRE></DIV>
1665
Use <code>"""</code> for multi-line strings rather than
1666
<code>'''</code>. Note, however, that it is often cleaner to
1667
use implicit line joining since multi-line strings do
1668
not flow with the indentation of the rest of the program:
1671
<DIV class=""><PRE class="badcode"> No<span class="external"></span>:
1672
<span class="external"></span>print """This is pretty ugly.
1673
Don'<span class="external"></span>t do this.
1674
"""<span class="external"></span>
1676
<DIV class=""><PRE>Ye<span class="external"></span>s:
1677
<span class="external"></span>print ("This is much nicer.\n"
1678
<span class="external"></span> "Do it this way.\n")</PRE></DIV>
1682
<H3><A name="TODO_Comments" id="TODO_Comments">TODO Comments</A></H3>
1683
<SPAN class="link_button" id="link-TODO_Comments__button" name="link-TODO_Comments__button"><A href="?showone=TODO_Comments#TODO_Comments">
1685
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('TODO_Comments__body','TODO_Comments__button')" name="TODO_Comments__button" id="TODO_Comments__button">▶</SPAN>
1686
<DIV style="display:inline;" class="">
1687
Use <code>TODO</code> comments for code that is temporary, a
1688
short-term solution, or good-enough but not perfect.
1690
<DIV class=""><DIV class="stylepoint_body" name="TODO_Comments__body" id="TODO_Comments__body" style="display: none">
1692
<code>TODO</code>s should include the string <code>TODO</code> in
1693
all caps, followed by your
1695
name, e-mail address, or other
1697
in parentheses. A colon is optional. A comment explaining what there
1698
is to do is required. The main purpose is to have
1699
a consistent <code>TODO</code> format searchable by the person
1700
adding the comment (who can provide more details upon request). A
1701
<code>TODO</code> is not a commitment to provide the fix yourself.
1704
<DIV class=""><PRE># TODO(kl@gmail.com): Drop the use of "has_key".
1705
# TODO(Zeke) change this to use relations.</PRE></DIV>
1707
If your <code>TODO</code> is of the form "At a future date do
1708
something" make sure that you either include a very specific
1709
date ("Fix by November 2009") or a very specific event
1710
("Remove this code when all clients can handle XML responses.").
1715
<H3><A name="Imports_formatting" id="Imports_formatting">Imports formatting</A></H3>
1716
<SPAN class="link_button" id="link-Imports_formatting__button" name="link-Imports_formatting__button"><A href="?showone=Imports_formatting#Imports_formatting">
1718
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Imports_formatting__body','Imports_formatting__button')" name="Imports_formatting__button" id="Imports_formatting__button">▶</SPAN>
1719
<DIV style="display:inline;" class="">
1720
Imports should be on separate lines.
1722
<DIV class=""><DIV class="stylepoint_body" name="Imports_formatting__body" id="Imports_formatting__body" style="display: none">
1727
<DIV class=""><PRE>Yes: <span class="external"></span>import os
1728
<span class="external"></span>import sys</PRE></DIV>
1729
<DIV class=""><PRE class="badcode">No: <span class="external"></span>import os, sys</PRE></DIV>
1731
Imports are always put at the top of the file, just after any
1732
module comments and doc strings and before module globals and
1733
constants. Imports should be grouped with the order being most generic
1737
<li>standard library imports</li>
1738
<li>third-party imports</li>
1740
<li>application-specific imports</li>
1743
Within each grouping, imports should be sorted lexicographically,
1744
ignoring case, according to each module's full package path.
1747
<span class="external"></span>import foo
1748
<span class="external"></span>from foo import bar
1749
<span class="external"></span>from foo.bar import baz
1750
<span class="external"></span>from foo.bar import Quux
1751
<span class="external"></span>from Foob import ar</PRE></DIV>
1758
<H3><A name="Statements" id="Statements">Statements</A></H3>
1759
<SPAN class="link_button" id="link-Statements__button" name="link-Statements__button"><A href="?showone=Statements#Statements">
1761
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Statements__body','Statements__button')" name="Statements__button" id="Statements__button">▶</SPAN>
1762
<DIV style="display:inline;" class="">
1763
Generally only one statement per line.
1765
<DIV class=""><DIV class="stylepoint_body" name="Statements__body" id="Statements__body" style="display: none">
1767
However, you may put the
1768
result of a test on the same line as the test only if the entire
1769
statement fits on one line. In particular, you can never do so
1770
with <code>try</code>/<code>except</code> since the
1771
<code>try</code> and <code>except</code> can't both fit on the
1772
same line, and you can only do so with an <code>if</code> if
1773
there is no <code>else</code>.
1776
<DIV class=""><PRE>Ye<span class="external"></span>s:
1778
<span class="external"></span>if foo: bar(foo)</PRE></DIV>
1779
<DIV class=""><PRE class="badcode">No<span class="external"></span>:
1781
<span class="external"></span>if foo: bar(foo)
1782
<span class="external"></span>else: baz(foo)
1784
<span class="external"></span>try: bar(foo)
1785
<span class="external"></span>except ValueError: baz(foo)
1787
<span class="external"></span>try:
1788
<span class="external"> </span>bar(foo)
1789
<span class="external"></span>except ValueError: baz(foo)
1790
<span class="external"></span>
1795
<H3><A name="Access_Control" id="Access_Control">Access Control</A></H3>
1796
<SPAN class="link_button" id="link-Access_Control__button" name="link-Access_Control__button"><A href="?showone=Access_Control#Access_Control">
1798
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Access_Control__body','Access_Control__button')" name="Access_Control__button" id="Access_Control__button">▶</SPAN>
1799
<DIV style="display:inline;" class="">
1800
If an accessor function would be trivial you should use public variables
1801
instead of accessor functions to avoid the extra cost of function
1802
calls in Python. When more functionality is added you can use
1803
<code>property</code> to keep the syntax consistent.
1805
<DIV class=""><DIV class="stylepoint_body" name="Access_Control__body" id="Access_Control__body" style="display: none">
1807
On the other hand, if access is more complex, or the cost of accessing
1808
the variable is significant, you should use function calls (following the
1809
<a HREF="#naming">Naming</a> guidelines) such as <code>get_foo()</code>
1810
and <code>set_foo()</code>. If the past behavior allowed access through a
1811
property, do not bind the new accessor functions to the property. Any
1812
code still attempting to access the variable by the old method should
1813
break visibly so they are made aware of the change in complexity.
1818
<H3><A name="Naming" id="Naming">Naming</A></H3>
1819
<SPAN class="link_button" id="link-Naming__button" name="link-Naming__button"><A href="?showone=Naming#Naming">
1821
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Naming__body','Naming__button')" name="Naming__button" id="Naming__button">▶</SPAN>
1822
<DIV style="display:inline;" class="">
1823
<code>module_name, package_name, ClassName, method_name, ExceptionName,
1824
function_name, GLOBAL_VAR_NAME, instance_var_name,
1825
function_parameter_name, local_var_name.</code>
1827
<DIV class=""><DIV class="stylepoint_body" name="Naming__body" id="Naming__body" style="display: none">
1829
<SPAN class="stylepoint_subsection">Names to Avoid</SPAN>
1832
<li>single character names except for counters or iterators</li>
1833
<li>dashes (<code>-</code>) in any package/module name</li>
1835
<code>__double_leading_and_trailing_underscore__</code> names
1836
(reserved by Python)</li>
1841
<SPAN class="stylepoint_subsection">Naming Convention</SPAN>
1845
"Internal" means internal to a module or protected
1846
or private within a class.</li>
1848
Prepending a single underscore (<code>_</code>) has some
1849
support for protecting module variables and functions (not included
1850
with <code>import * from</code>). Prepending a double underscore
1851
(<code>__</code>) to an instance variable or method
1852
effectively serves to make the variable or method private to its class
1853
(using name mangling).</li>
1855
Place related classes and top-level functions together in a
1856
module. Unlike Java,
1857
there is no need to limit yourself to one class per module.</li>
1859
Use CapWords for class names, but lower_with_under.py for module names.
1860
Although there are many existing modules named CapWords.py, this is now
1861
discouraged because it's confusing when the module happens to be
1862
named after a class. ("wait -- did I write
1863
<code>import StringIO</code> or <code>from StringIO import
1864
StringIO</code>?")</li>
1869
<SPAN class="stylepoint_subsection">Guidelines derived from Guido's Recommendations</SPAN>
1871
<table rules="all" border="1" cellspacing="2" cellpadding="2">
1883
<td><code>lower_with_under</code></td>
1889
<td><code>lower_with_under</code></td>
1890
<td><code>_lower_with_under</code></td>
1895
<td><code>CapWords</code></td>
1896
<td><code>_CapWords</code></td>
1901
<td><code>CapWords</code></td>
1909
<td><code>lower_with_under()</code></td>
1910
<td><code>_lower_with_under()</code></td>
1914
<td>Global/Class Constants</td>
1915
<td><code>CAPS_WITH_UNDER</code></td>
1916
<td><code>_CAPS_WITH_UNDER</code></td>
1920
<td>Global/Class Variables</td>
1921
<td><code>lower_with_under</code></td>
1922
<td><code>_lower_with_under</code></td>
1926
<td>Instance Variables</td>
1927
<td><code>lower_with_under</code></td>
1928
<td><code>_lower_with_under (protected) or __lower_with_under (private)</code></td>
1934
<td>Method Names</td>
1935
<td><code>lower_with_under()</code></td>
1936
<td><code>_lower_with_under() (protected) or __lower_with_under() (private)</code></td>
1940
<td>Function/Method Parameters</td>
1941
<td><code>lower_with_under</code></td>
1946
<td>Local Variables</td>
1947
<td><code>lower_with_under</code></td>
1959
<H3><A name="Main" id="Main">Main</A></H3>
1960
<SPAN class="link_button" id="link-Main__button" name="link-Main__button"><A href="?showone=Main#Main">
1962
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Main__body','Main__button')" name="Main__button" id="Main__button">▶</SPAN>
1963
<DIV style="display:inline;" class="">
1964
Even a file meant to be used as a script should be importable and a
1965
mere import should not have the side effect of executing the script's
1966
main functionality. The main functionality should be in a main()
1969
<DIV class=""><DIV class="stylepoint_body" name="Main__body" id="Main__body" style="display: none">
1972
<code>pychecker</code>, <code>pydoc</code>, and unit tests
1973
require modules to be importable. Your code should always check
1974
<code>if __name__ == '__main__'</code> before executing your
1975
main program so that the main program is not executed when the
1987
<span class="external"></span>def main():
1988
<span class="external"> </span>...
1990
<span class="external"></span>if __name__ == '__main__':
1991
<span class="external"> </span>main()
1992
<span class="external"></span>
1996
All code at the top level will be executed when the module is
1997
imported. Be careful not to call functions, create objects, or
1998
perform other operations that should not be executed when the
1999
file is being <code>pycheck</code>ed or <code>pydoc</code>ed.
2005
<H2>Parting Words</H2>
2007
<em>BE CONSISTENT</em>.
2011
If you're editing code, take a few minutes to look at the code
2012
around you and determine its style. If they use spaces around
2013
all their arithmetic operators, you should too. If their
2014
comments have little boxes of hash marks around them, make your
2015
comments have little boxes of hash marks around them too.
2019
The point of having style guidelines is to have a common vocabulary
2020
of coding so people can concentrate on what you're saying rather
2021
than on how you're saying it. We present global style rules here so
2022
people know the vocabulary, but local style is also important. If
2023
code you add to a file looks drastically different from the existing
2024
code around it, it throws readers out of their rhythm when they go to
2025
read it. Avoid this.