forked from RobotLocomotion/styleguide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pyguide.html
2310 lines (2092 loc) · 108 KB
/
pyguide.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<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">
<HEAD>
<TITLE>Google Python Style Guide</TITLE>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<LINK HREF="https://www.google.com/favicon.ico" type="image/x-icon" rel="shortcut icon">
<LINK HREF="styleguide.css" type="text/css" rel="stylesheet">
<SCRIPT language="javascript" type="text/javascript">
function GetElementsByName(name) {
// Workaround a bug on old versions of opera.
if (document.getElementsByName) {
return document.getElementsByName(name);
} else {
return [document.getElementById(name)];
}
}
/**
* @param {string} namePrefix The prefix of the body name.
* @param {function(boolean): boolean} getVisibility Computes the new
* visibility state, given the current one.
*/
function ChangeVisibility(namePrefix, getVisibility) {
var bodyName = namePrefix + '__body';
var buttonName = namePrefix + '__button';
var bodyElements = GetElementsByName(bodyName);
var linkElement = GetElementsByName('link-' + buttonName)[0];
if (bodyElements.length != 1) {
throw Error('ShowHideByName() got the wrong number of bodyElements: ' +
bodyElements.length);
} else {
var bodyElement = bodyElements[0];
var buttonElement = GetElementsByName(buttonName)[0];
var isVisible = bodyElement.style.display != "none";
if (getVisibility(isVisible)) {
bodyElement.style.display = "inline";
linkElement.style.display = "block";
buttonElement.innerHTML = '▽';
} else {
bodyElement.style.display = "none";
linkElement.style.display = "none";
buttonElement.innerHTML = '▶';
}
}
}
function ShowHideByName(namePrefix) {
ChangeVisibility(namePrefix, function(old) { return !old; });
}
function ShowByName(namePrefix) {
ChangeVisibility(namePrefix, function() { return true; });
}
function ShowHideAll() {
var allButton = GetElementsByName("show_hide_all_button")[0];
if (allButton.innerHTML == '▽') {
allButton.innerHTML = '▶';
SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "none", '▶');
} else {
allButton.innerHTML = '▽';
SetHiddenState(document.getElementsByTagName("body")[0].childNodes, "inline", '▽');
}
}
// Recursively sets state of all children
// of a particular node.
function SetHiddenState(root, newState, newButton) {
for (var i = 0; i != root.length; i++) {
SetHiddenState(root[i].childNodes, newState, newButton);
if (root[i].className == 'showhide_button') {
root[i].innerHTML = newButton;
}
if (root[i].className == 'stylepoint_body' ||
root[i].className == 'link_button') {
root[i].style.display = newState;
}
}
}
function EndsWith(str, suffix) {
var l = str.length - suffix.length;
return l >= 0 && str.indexOf(suffix, l) == l;
}
function RefreshVisibilityFromHashParam() {
var hashRegexp = new RegExp('#([^&#]*)$');
var hashMatch = hashRegexp.exec(window.location.href);
var anchor = hashMatch && GetElementsByName(hashMatch[1])[0];
var node = anchor;
var suffix = '__body';
while (node) {
var id = node.id;
var matched = id && EndsWith(id, suffix);
if (matched) {
var len = id.length - suffix.length;
ShowByName(id.substring(0, len));
if (anchor.scrollIntoView) {
anchor.scrollIntoView();
}
return;
}
node = node.parentNode;
}
}
window.onhashchange = RefreshVisibilityFromHashParam;
window.onload = function() {
// if the URL contains "?showall=y", expand the details of all children
var showHideAllRegex = new RegExp("[\\?&](showall)=([^&#]*)");
var showHideAllValue = showHideAllRegex.exec(window.location.href);
if (showHideAllValue != null) {
if (showHideAllValue[2] == "y") {
SetHiddenState(document.getElementsByTagName("body")[0].childNodes,
"inline", '▽');
} else {
SetHiddenState(document.getElementsByTagName("body")[0].childNodes,
"none", '▶');
}
}
var showOneRegex = new RegExp("[\\?&](showone)=([^&#]*)");
var showOneValue = showOneRegex.exec(window.location.href);
if (showOneValue) {
ShowHideByName(showOneValue[2]);
}
RefreshVisibilityFromHashParam();
}
</SCRIPT>
</HEAD>
<BODY>
<H1>Google Python Style Guide</H1>
<p align="right">
Revision 2.59
</p>
<address>
Amit Patel<br>
Antoine Picard<br>
Eugene Jhong<br>
Jeremy Hylton<br>
Matt Smart<br>
Mike Shields<br>
</address>
<DIV style="margin-left: 50%; font-size: 75%;">
<P>
Each style point has a summary for which additional information is available
by toggling the accompanying arrow button that looks this way:
<SPAN class="showhide_button" style="margin-left: 0; float: none">▶</SPAN>.
You may toggle all summaries with the big arrow button:
</P>
<DIV style=" font-size: larger; margin-left: +2em;">
<SPAN class="showhide_button" style="font-size: 180%; float: none" onclick="javascript:ShowHideAll()" name="show_hide_all_button" id="show_hide_all_button">▶</SPAN>
Toggle all summaries
</DIV>
</DIV>
<DIV class="toc">
<DIV class="toc_title">Table of Contents</DIV>
<TABLE>
<TR valign="top" class="">
<TD><DIV class="toc_category"><A href="#Python_Language_Rules">Python Language Rules</A></DIV></TD>
<TD><DIV class="toc_stylepoint">
<SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Lint">Lint</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Imports">Imports</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Packages">Packages</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Exceptions">Exceptions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Global_variables">Global variables</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Nested/Local/Inner_Classes_and_Functions">Nested/Local/Inner Classes and Functions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#List_Comprehensions">List Comprehensions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Default_Iterators_and_Operators">Default Iterators and Operators</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Generators">Generators</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Lambda_Functions">Lambda Functions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Conditional_Expressions">Conditional Expressions</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Default_Argument_Values">Default Argument Values</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Properties">Properties</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#True/False_evaluations">True/False evaluations</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Deprecated_Language_Features">Deprecated Language Features</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Lexical_Scoping">Lexical Scoping</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Function_and_Method_Decorators">Function and Method Decorators</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Threading">Threading</A></SPAN> <SPAN style="padding-right: 1em; white-space:nowrap;" class=""><A href="#Power_Features">Power Features</A></SPAN> </DIV></TD>
</TR>
<TR valign="top" class="">
<TD><DIV class="toc_category"><A href="#Python_Style_Rules">Python Style Rules</A></DIV></TD>
<TD><DIV class="toc_stylepoint">
<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>
</TR>
</TABLE>
</DIV>
<DIV class="">
<H2 name="Important_Note" id="Important_Note">Important Note</H2>
<DIV class="">
<H3><A name="Displaying_Hidden_Details_in_this_Guide" id="Displaying_Hidden_Details_in_this_Guide">Displaying Hidden Details in this Guide</A></H3>
<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">
link
</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>
<DIV style="display:inline;" class="">
This style guide contains many details that are initially
hidden from view. They are marked by the triangle icon, which you
see here on your left. Click it now.
You should see "Hooray" appear below.
</DIV>
<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">
<p>
Hooray! Now you know you can expand points to get more
details. Alternatively, there's a "toggle all" at the
top of this document.
</p>
</DIV></DIV>
</DIV>
</DIV>
<DIV class="">
<H2 name="Background" id="Background">Background</H2>
<p>
Python is the main scripting language used at Google. This
style guide is a list of <em>do</em>s and <em>don't</em>s for Python
programs.
</p>
<p>
To help you format code correctly, we've created a <a href="google_python_style.vim">settings
file for Vim</a>. For Emacs, the default settings should be fine.
</p>
</DIV>
<DIV class="">
<H2 name="Python_Language_Rules" id="Python_Language_Rules">Python Language Rules</H2>
<DIV class="">
<H3><A name="Lint" id="Lint">Lint</A></H3>
<SPAN class="link_button" id="link-Lint__button" name="link-Lint__button"><A href="?showone=Lint#Lint">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Lint')" name="Lint__button" id="Lint__button">▶</SPAN>
<DIV style="display:inline;" class="">
Run <code>pylint</code> over your code.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Lint__body" id="Lint__body" style="display: none">
<P class="">
<SPAN class="stylepoint_section">Definition: </SPAN>
pylint
is a tool for finding bugs and style problems in Python source
code. It finds
problems that are typically caught by a compiler for less dynamic
languages like C and C++.
Because of the
dynamic nature of Python, some warnings may be incorrect; however,
spurious warnings should be fairly infrequent.
</P>
<P class="">
<SPAN class="stylepoint_section">Pros: </SPAN>
Catches easy-to-miss errors like typos, using-vars-before-assignment, etc.
</P>
<P class="">
<SPAN class="stylepoint_section">Cons: </SPAN>
<code>pylint</code>
isn't perfect. To take advantage of it, we'll need to sometimes:
a) Write around it b) Suppress its warnings or c) Improve it.
</P>
<P class="">
<SPAN class="stylepoint_section">Decision: </SPAN>
Make sure you run <code>pylint</code> on your code.
Suppress warnings if they are inappropriate so that other issues are
not hidden.
</P>
<p>
To suppress warnings, you can set a line-level comment:
</p>
<DIV class=""><PRE>
<span class="external"></span>dict = 'something awful' # Bad Idea... pylint: disable=redefined-builtin</PRE></DIV>
<p>
pylint
warnings are each identified by a alphanumeric code
(<code>C0112</code>) and a symbolic name
(<code>empty-docstring</code>). Prefer the symbolic
names in new code or when updating existing code.
</p>
<p>
If the reason for the suppression is not clear from the symbolic name,
add an explanation.
</p>
<p>
Suppressing in this way has the advantage that we can easily search
for suppressions and revisit them.
</p>
<p>
You can get a list of
pylint
warnings by doing
<code>pylint --list-msgs</code>.
To get more information on a particular message, use
<code>pylint --help-msg=C6409</code>.
</p>
<p>
Prefer <code>pylint: disable</code> to the deprecated older form
<code>pylint: disable-msg</code>.
</p>
<p>
Unused argument warnings can be suppressed by using `_' as the
identifier for the unused argument or prefixing the argument name with
`unused_'. In situations where changing the argument names is
infeasible, you can mention them at the beginning of the function.
For example:
</p>
<DIV class=""><PRE>
<span class="external"></span>def foo(a, unused_b, unused_c, d=None, e=None):
<span class="external"> </span>_ = d, e
<span class="external"> </span>return a
<span class="external"></span>
</PRE></DIV>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Imports" id="Imports">Imports</A></H3>
<SPAN class="link_button" id="link-Imports__button" name="link-Imports__button"><A href="?showone=Imports#Imports">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Imports')" name="Imports__button" id="Imports__button">▶</SPAN>
<DIV style="display:inline;" class="">
Use <code>import</code>s for packages and modules only.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Imports__body" id="Imports__body" style="display: none">
<P class="">
<SPAN class="stylepoint_section">Definition: </SPAN>
Reusability mechanism for sharing code from one module to another.
</P>
<P class="">
<SPAN class="stylepoint_section">Pros: </SPAN>
The namespace management convention is simple. The source of each
identifier is indicated in a consistent way; <code>x.Obj</code> says
that object <code>Obj</code> is defined in module <code>x</code>.
</P>
<P class="">
<SPAN class="stylepoint_section">Cons: </SPAN> Module names can still collide. Some module names are
inconveniently long.
</P>
<P class="">
<SPAN class="stylepoint_section">Decision: </SPAN>
Use <code>import x</code> for importing packages and modules.
<br>
Use <code>from x import y</code> where <code>x</code> is
the package prefix and <code>y</code> is the module name with no
prefix.
<br>
Use <code>from x import y as z</code> if two modules named
<code>y</code> are to be imported or if <code>y</code> is an
inconveniently long name.
</P>
For example the module
<code>sound.effects.echo</code> may be imported as follows:
<DIV class=""><PRE>
<span class="external"></span>from sound.effects import echo
<span class="external"></span>...
<span class="external"></span>echo.EchoFilter(input, output, delay=0.7, atten=4)
<span class="external"></span>
</PRE></DIV>
<p>
Do not use relative names in imports. Even if the module is in the
same package, use the full package name. This helps prevent
unintentionally importing a package twice.
</p>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Packages" id="Packages">Packages</A></H3>
<SPAN class="link_button" id="link-Packages__button" name="link-Packages__button"><A href="?showone=Packages#Packages">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Packages')" name="Packages__button" id="Packages__button">▶</SPAN>
<DIV style="display:inline;" class="">
Import each module using the full pathname location of the module.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Packages__body" id="Packages__body" style="display: none">
<P class="">
<SPAN class="stylepoint_section">Pros: </SPAN>
Avoids conflicts in module names. Makes it easier to find modules.
</P>
<P class="">
<SPAN class="stylepoint_section">Cons: </SPAN>
Makes it harder to deploy code because you have to replicate the
package hierarchy.
</P>
<P class="">
<SPAN class="stylepoint_section">Decision: </SPAN>
All new code should import each module by its full package name.
</P>
<p>
Imports should be as follows:
</p>
<DIV class=""><PRE># Reference in code with complete name.
import sound.effects.echo
# Reference in code with just module name (preferred).
from sound.effects import echo
</PRE></DIV>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Exceptions" id="Exceptions">Exceptions</A></H3>
<SPAN class="link_button" id="link-Exceptions__button" name="link-Exceptions__button"><A href="?showone=Exceptions#Exceptions">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Exceptions')" name="Exceptions__button" id="Exceptions__button">▶</SPAN>
<DIV style="display:inline;" class="">
Exceptions are allowed but must be used carefully.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Exceptions__body" id="Exceptions__body" style="display: none">
<P class="">
<SPAN class="stylepoint_section">Definition: </SPAN>
Exceptions are a means of breaking out of the normal flow of control
of a code block to handle errors or other exceptional conditions.
</P>
<P class="">
<SPAN class="stylepoint_section">Pros: </SPAN>
The control flow of normal operation code is not cluttered by
error-handling code. It also allows the control flow to skip multiple
frames when a certain condition occurs, e.g., returning from N
nested functions in one step instead of having to carry-through
error codes.
</P>
<P class="">
<SPAN class="stylepoint_section">Cons: </SPAN>
May cause the control flow to be confusing. Easy to miss error
cases when making library calls.
</P>
<P class="">
<SPAN class="stylepoint_section">Decision: </SPAN>
Exceptions must follow certain conditions:
<ul>
<li>Raise exceptions like this: <code>raise MyException('Error
message')</code> or <code>raise MyException</code>. Do not
use the two-argument form (<code>raise MyException, 'Error
message'</code>) or deprecated string-based exceptions
(<code>raise 'Error message'</code>).</li>
<li>Modules or packages should define their own domain-specific
base exception class, which should inherit from the built-in
Exception class. The base exception for a module should be called
<code>Error</code>.
<DIV class=""><PRE>
<span class="external"></span>class Error(Exception):
<span class="external"> </span>pass</PRE></DIV>
</li>
<li>Never use catch-all <code>except:</code> statements, or
catch <code>Exception</code> or <code>StandardError</code>,
unless you are re-raising the exception or in the outermost
block in your thread (and printing an error message). Python
is very tolerant in this regard and <code>except:</code> will
really catch everything including misspelled names, sys.exit()
calls, Ctrl+C interrupts, unittest failures and all kinds of
other exceptions that you simply don't want to catch.</li>
<li>Minimize the amount of code in a
<code>try</code>/<code>except</code> block. The larger the
body of the <code>try</code>, the more likely that an
exception will be raised by a line of code that you didn't
expect to raise an exception. In those cases,
the <code>try</code>/<code>except</code> block hides a real
error.</li>
<li>Use the <code>finally</code> clause to execute code whether
or not an exception is raised in the <code>try</code> block.
This is often useful for cleanup, i.e., closing a file.</li>
<li>When capturing an exception, use <code>as</code> rather than
a comma. For example:
<DIV class=""><PRE>
<span class="external"></span>try:
<span class="external"> </span>raise Error
<span class="external"></span>except Error as error:
<span class="external"> </span>pass</PRE></DIV>
</li>
</ul>
</P>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Global_variables" id="Global_variables">Global variables</A></H3>
<SPAN class="link_button" id="link-Global_variables__button" name="link-Global_variables__button"><A href="?showone=Global_variables#Global_variables">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Global_variables')" name="Global_variables__button" id="Global_variables__button">▶</SPAN>
<DIV style="display:inline;" class="">
Avoid global variables.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Global_variables__body" id="Global_variables__body" style="display: none">
<P class="">
<SPAN class="stylepoint_section">Definition: </SPAN>
Variables that are declared at the module level.
</P>
<P class="">
<SPAN class="stylepoint_section">Pros: </SPAN>
Occasionally useful.
</P>
<P class="">
<SPAN class="stylepoint_section">Cons: </SPAN>
Has the potential to change module behavior during the import,
because assignments to module-level variables are done when the
module is imported.
</P>
<P class="">
<SPAN class="stylepoint_section">Decision: </SPAN>
Avoid global variables in favor of class variables. Some
exceptions are:
<ul>
<li>Default options for scripts.</li>
<li>Module-level constants. For example: <code>PI = 3.14159</code>.
Constants should be named using all caps with underscores;
see <a HREF="#Naming">Naming</a> below.</li>
<li>It is sometimes useful for globals to cache values needed
or returned by functions.</li>
<li>If needed, globals should be made internal to the module
and accessed through public module level functions;
see <a HREF="#Naming">Naming</a> below.</li>
</ul>
</P>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Nested/Local/Inner_Classes_and_Functions" id="Nested/Local/Inner_Classes_and_Functions">Nested/Local/Inner Classes and Functions</A></H3>
<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">
link
</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>
<DIV style="display:inline;" class="">
Nested/local/inner classes and functions are fine.
</DIV>
<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">
<P class="">
<SPAN class="stylepoint_section">Definition: </SPAN>
A class can be defined inside of a method, function, or class. A
function can be defined inside a method or function. Nested functions
have read-only access to variables defined in enclosing scopes.
</P>
<P class="">
<SPAN class="stylepoint_section">Pros: </SPAN>
Allows definition of utility classes and functions that are only
used inside of a very limited scope. Very <a HREF="https://en.wikipedia.org/wiki/Abstract_data_type">ADT</a>-y.
</P>
<P class="">
<SPAN class="stylepoint_section">Cons: </SPAN>
Instances of nested or local classes cannot be pickled.
</P>
<P class="">
<SPAN class="stylepoint_section">Decision: </SPAN>
They are fine.
</P>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="List_Comprehensions" id="List_Comprehensions">List Comprehensions</A></H3>
<SPAN class="link_button" id="link-List_Comprehensions__button" name="link-List_Comprehensions__button"><A href="?showone=List_Comprehensions#List_Comprehensions">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('List_Comprehensions')" name="List_Comprehensions__button" id="List_Comprehensions__button">▶</SPAN>
<DIV style="display:inline;" class="">
Okay to use for simple cases.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="List_Comprehensions__body" id="List_Comprehensions__body" style="display: none">
<P class="">
<SPAN class="stylepoint_section">Definition: </SPAN>
List comprehensions and generator expressions provide a concise
and efficient way to create lists and iterators without
resorting to the use of <code>map()</code>,
<code>filter()</code>, or <code>lambda</code>.
</P>
<P class="">
<SPAN class="stylepoint_section">Pros: </SPAN>
Simple list comprehensions can be clearer and simpler than
other list creation techniques. Generator expressions can be
very efficient, since they avoid the creation of a list
entirely.
</P>
<P class="">
<SPAN class="stylepoint_section">Cons: </SPAN>
Complicated list comprehensions or generator expressions can be
hard to read.
</P>
<P class="">
<SPAN class="stylepoint_section">Decision: </SPAN>
Okay to use for simple cases. Each portion must fit on one line:
mapping expression, <code>for</code> clause, filter expression.
Multiple <code>for</code> clauses or filter expressions are not
permitted. Use loops instead when things get more complicated.
</P>
<DIV class=""><PRE>Ye<span class="external"></span>s:
<span class="external"></span>result = []
<span class="external"></span>for x in range(10):
<span class="external"> </span>for y in range(5):
<span class="external"> </span>if x * y > 10:
<span class="external"> </span>result.append((x, y))
<span class="external"></span>for x in xrange(5):
<span class="external"> </span>for y in xrange(5):
<span class="external"> </span>if x != y:
<span class="external"> </span>for z in xrange(5):
<span class="external"> </span>if y != z:
<span class="external"> </span>yield (x, y, z)
<span class="external"></span>return ((x, complicated_transform(x))
<span class="external"></span> for x in long_generator_function(parameter)
<span class="external"></span> if x is not None)
<span class="external"></span>squares = [x * x for x in range(10)]
<span class="external"></span>eat(jelly_bean for jelly_bean in jelly_beans
<span class="external"></span> if jelly_bean.color == 'black')</PRE></DIV>
<DIV class=""><PRE class="badcode">No<span class="external"></span>:
<span class="external"></span>result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]
<span class="external"></span>return ((x, y, z)
<span class="external"></span> for x in xrange(5)
<span class="external"></span> for y in xrange(5)
<span class="external"></span> if x != y
<span class="external"></span> for z in xrange(5)
<span class="external"></span> if y != z)</PRE></DIV>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Default_Iterators_and_Operators" id="Default_Iterators_and_Operators">Default Iterators and Operators</A></H3>
<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">
link
</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>
<DIV style="display:inline;" class="">
Use default iterators and operators for types that support them,
like lists, dictionaries, and files.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Default_Iterators_and_Operators__body" id="Default_Iterators_and_Operators__body" style="display: none">
<P class="">
<SPAN class="stylepoint_section">Definition: </SPAN>
Container types, like dictionaries and lists, define default
iterators and membership test operators ("in" and "not in").
</P>
<P class="">
<SPAN class="stylepoint_section">Pros: </SPAN>
The default iterators and operators are simple and efficient.
They express the operation directly, without extra method calls.
A function that uses default operators is generic. It can be
used with any type that supports the operation.
</P>
<P class="">
<SPAN class="stylepoint_section">Cons: </SPAN>
You can't tell the type of objects by reading the method names
(e.g. has_key() means a dictionary). This is also an advantage.
</P>
<P class="">
<SPAN class="stylepoint_section">Decision: </SPAN> Use default iterators and operators for types
that support them, like lists, dictionaries, and files. The
built-in types define iterator methods, too. Prefer these
methods to methods that return lists, except that you should not
mutate a container while iterating over it.
<DIV class=""><PRE>Yes: <span class="external"></span>for key in adict: ...
<span class="external"></span>if key not in adict: ...
<span class="external"></span>if obj in alist: ...
<span class="external"></span>for line in afile: ...
<span class="external"></span>for k, v in dict.iteritems(): ...</PRE></DIV>
<DIV class=""><PRE class="badcode">No: <span class="external"></span>for key in adict.keys(): ...
<span class="external"></span>if not adict.has_key(key): ...
<span class="external"></span>for line in afile.readlines(): ...</PRE></DIV>
</P>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Generators" id="Generators">Generators</A></H3>
<SPAN class="link_button" id="link-Generators__button" name="link-Generators__button"><A href="?showone=Generators#Generators">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Generators')" name="Generators__button" id="Generators__button">▶</SPAN>
<DIV style="display:inline;" class="">
Use generators as needed.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Generators__body" id="Generators__body" style="display: none">
<P class="">
<SPAN class="stylepoint_section">Definition: </SPAN>
A generator function returns an iterator that yields a value each
time it executes a yield statement. After it yields a value, the
runtime state of the generator function is suspended until the
next value is needed.
</P>
<P class="">
<SPAN class="stylepoint_section">Pros: </SPAN>
Simpler code, because the state of local variables and control flow
are preserved for each call. A generator uses less memory than a
function that creates an entire list of values at once.
</P>
<P class="">
<SPAN class="stylepoint_section">Cons: </SPAN>
None.
</P>
<P class="">
<SPAN class="stylepoint_section">Decision: </SPAN>
Fine. Use "Yields:" rather than "Returns:" in the
doc string for generator functions.
</P>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Lambda_Functions" id="Lambda_Functions">Lambda Functions</A></H3>
<SPAN class="link_button" id="link-Lambda_Functions__button" name="link-Lambda_Functions__button"><A href="?showone=Lambda_Functions#Lambda_Functions">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Lambda_Functions')" name="Lambda_Functions__button" id="Lambda_Functions__button">▶</SPAN>
<DIV style="display:inline;" class="">
Okay for one-liners.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Lambda_Functions__body" id="Lambda_Functions__body" style="display: none">
<P class="">
<SPAN class="stylepoint_section">Definition: </SPAN>
Lambdas define anonymous functions in an expression, as
opposed to a statement. They are often used to define callbacks or
operators for higher-order functions like <code>map()</code> and
<code>filter()</code>.
</P>
<P class="">
<SPAN class="stylepoint_section">Pros: </SPAN>
Convenient.
</P>
<P class="">
<SPAN class="stylepoint_section">Cons: </SPAN> Harder to read and debug than local functions. The
lack of names means stack traces are more difficult to
understand. Expressiveness is limited because the function may
only contain an expression.
</P>
<P class="">
<SPAN class="stylepoint_section">Decision: </SPAN>
Okay to use them for one-liners. If the code inside the lambda
function is any longer than 60–80 chars, it's probably better to
define it as a regular (nested) function.
<p>
For common operations like multiplication, use the functions from the
<code>operator</code> module instead of lambda functions. For
example, prefer <code>operator.mul</code> to <code>lambda
x, y: x * y</code>.
</p>
</P>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Conditional_Expressions" id="Conditional_Expressions">Conditional Expressions</A></H3>
<SPAN class="link_button" id="link-Conditional_Expressions__button" name="link-Conditional_Expressions__button"><A href="?showone=Conditional_Expressions#Conditional_Expressions">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Conditional_Expressions')" name="Conditional_Expressions__button" id="Conditional_Expressions__button">▶</SPAN>
<DIV style="display:inline;" class="">
Okay for one-liners.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Conditional_Expressions__body" id="Conditional_Expressions__body" style="display: none">
<P class="">
<SPAN class="stylepoint_section">Definition: </SPAN>
Conditional expressions are mechanisms that provide a shorter syntax
for if statements. For example:
<code>x = 1 if cond else 2</code>.
</P>
<P class="">
<SPAN class="stylepoint_section">Pros: </SPAN>
Shorter and more convenient than an if statement.
</P>
<P class="">
<SPAN class="stylepoint_section">Cons: </SPAN>
May be harder to read than an if statement. The condition may be difficult
to locate if the expression is long.
</P>
<P class="">
<SPAN class="stylepoint_section">Decision: </SPAN>
Okay to use for one-liners. In other cases prefer to use a complete if
statement.
</P>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Default_Argument_Values" id="Default_Argument_Values">Default Argument Values</A></H3>
<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">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Default_Argument_Values')" name="Default_Argument_Values__button" id="Default_Argument_Values__button">▶</SPAN>
<DIV style="display:inline;" class="">
Okay in most cases.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Default_Argument_Values__body" id="Default_Argument_Values__body" style="display: none">
<P class="">
<SPAN class="stylepoint_section">Definition: </SPAN>
You can specify values for variables at the end of a function's
parameter list, e.g., <code>def foo(a, b=0):</code>. If
<code>foo</code> is called with only one argument,
<code>b</code> is set to 0. If it is called with two arguments,
<code>b</code> has the value of the second argument.
</P>
<P class="">
<SPAN class="stylepoint_section">Pros: </SPAN>
Often you have a function that uses lots of default values,
but—rarely—you want to override the
defaults. Default argument values provide an easy way to do this,
without having to define lots of functions for the rare
exceptions. Also, Python does not support overloaded
methods/functions and default arguments are an easy way of
"faking" the overloading behavior.
</P>
<P class="">
<SPAN class="stylepoint_section">Cons: </SPAN>
Default arguments are evaluated once at module load
time. This may cause problems if the argument is a mutable
object such as a list or a dictionary. If the function modifies
the object (e.g., by appending an item to a list), the default
value is modified.
</P>
<P class="">
<SPAN class="stylepoint_section">Decision: </SPAN>
Okay to use with the following caveat:
<p>
Do not use mutable objects as default values in the function or method
definition.
</p>
<DIV class=""><PRE>Yes: <span class="external"></span>def foo(a, b=None):
<span class="external"> </span>if b is None:
<span class="external"> </span>b = []</PRE></DIV>
<DIV class=""><PRE class="badcode">No: <span class="external"></span>def foo(a, b=[]):
<span class="external"> </span>...
No: <span class="external"></span>def foo(a, b=time.time()): # The time the module was loaded???
<span class="external"> </span>...
No: <span class="external"></span>def foo(a, b=FLAGS.my_thing): # sys.argv has not yet been parsed...
<span class="external"> </span>...</PRE></DIV>
</P>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Properties" id="Properties">Properties</A></H3>
<SPAN class="link_button" id="link-Properties__button" name="link-Properties__button"><A href="?showone=Properties#Properties">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Properties')" name="Properties__button" id="Properties__button">▶</SPAN>
<DIV style="display:inline;" class="">
Use properties for accessing or setting data where you would
normally have used simple, lightweight accessor or setter methods.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="Properties__body" id="Properties__body" style="display: none">
<P class="">
<SPAN class="stylepoint_section">Definition: </SPAN> A way to wrap method calls for getting and
setting an attribute as a standard attribute access when the
computation is lightweight.
</P>
<P class="">
<SPAN class="stylepoint_section">Pros: </SPAN> Readability is increased by eliminating explicit
get and set method calls for simple attribute access. Allows
calculations to be lazy. Considered the Pythonic way to
maintain the interface of a class. In terms of performance,
allowing properties bypasses needing trivial accessor methods
when a direct variable access is reasonable. This also allows
accessor methods to be added in the future without breaking the
interface.
</P>
<P class="">
<SPAN class="stylepoint_section">Cons: </SPAN> Properties are specified after the getter and
setter methods are declared, requiring one to notice they are
used for properties farther down in the code (except for readonly
properties created with the <code>@property</code> decorator - see
below). Must inherit from
<code>object</code>. Can hide side-effects much like operator
overloading. Can be confusing for subclasses.
</P>
<P class="">
<SPAN class="stylepoint_section">Decision: </SPAN> Use properties in new code to access or
set data where you would normally have used simple, lightweight
accessor or setter methods. Read-only properties should be created
with the <code>@property</code>
<a HREF="#Function_and_Method_Decorators">decorator</a>.
<p><a id="properties-template-dp">
Inheritance with properties can be non-obvious if the property itself is
not overridden. Thus one must make sure that accessor methods are
called indirectly to ensure methods overridden in subclasses are called
by the property (using the Template Method DP).
</a></p>
<DIV class=""><PRE>Yes: <span class="external"></span>import math
<span class="external"></span>class Square(object):
<span class="external"> </span>"""A square with two properties: a writable area and a read-only perimeter.
<span class="external"> </span>To use:
<span class="external"> </span>>>> sq = Square(3)
<span class="external"> </span>>>> sq.area
<span class="external"> </span>9
<span class="external"> </span>>>> sq.perimeter
<span class="external"> </span>12
<span class="external"> </span>>>> sq.area = 16
<span class="external"> </span>>>> sq.side
<span class="external"> </span>4
<span class="external"> </span>>>> sq.perimeter
<span class="external"> </span>16
<span class="external"> </span>"""
<span class="external"> </span>def __init__(self, side):
<span class="external"> </span>self.side = side
<span class="external"> </span>def __get_area(self):
<span class="external"> </span>"""Calculates the 'area' property."""
<span class="external"> </span>return self.side ** 2
<span class="external"> </span>def ___get_area(self):
<span class="external"> </span>"""Indirect accessor for 'area' property."""
<span class="external"> </span>return self.__get_area()
<span class="external"> </span>def __set_area(self, area):
<span class="external"> </span>"""Sets the 'area' property."""
<span class="external"> </span>self.side = math.sqrt(area)
<span class="external"> </span>def ___set_area(self, area):
<span class="external"> </span>"""Indirect setter for 'area' property."""
<span class="external"> </span>self.__set_area(area)
<span class="external"> </span>area = property(___get_area, ___set_area,
<span class="external"> </span> doc="""Gets or sets the area of the square.""")
<span class="external"> </span>@property
<span class="external"> </span>def perimeter(self):
<span class="external"> </span>return self.side * 4
<span class="external"></span>
</PRE></DIV>
</P>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="True/False_evaluations" id="True/False_evaluations">True/False evaluations</A></H3>
<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">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('True/False_evaluations')" name="True/False_evaluations__button" id="True/False_evaluations__button">▶</SPAN>
<DIV style="display:inline;" class="">
Use the "implicit" false if at all possible.
</DIV>
<DIV class=""><DIV class="stylepoint_body" name="True/False_evaluations__body" id="True/False_evaluations__body" style="display: none">
<P class="">
<SPAN class="stylepoint_section">Definition: </SPAN> Python evaluates certain values as <code>false</code>
when in a boolean context. A quick "rule of thumb" is that all
"empty" values are considered <code>false</code> so <code>0, None, [], {},
''</code> all evaluate as <code>false</code> in a boolean context.
</P>
<P class="">
<SPAN class="stylepoint_section">Pros: </SPAN> Conditions using Python booleans are easier to read
and less error-prone. In most cases, they're also faster.
</P>
<P class="">
<SPAN class="stylepoint_section">Cons: </SPAN>
May look strange to C/C++ developers.
</P>
<P class="">
<SPAN class="stylepoint_section">Decision: </SPAN>
Use the "implicit" false if at all possible, e.g., <code>if
foo:</code> rather than <code>if foo != []:</code>. There are a
few caveats that you should keep in mind though:
<ul>
<li>
Never use <code>==</code> or <code>!=</code> to compare
singletons like <code>None</code>. Use <code>is</code>
or <code>is not</code>.</li>
<li>Beware of writing <code>if x:</code> when you really mean
<code>if x is not None:</code>—e.g., when testing whether
a variable or argument that defaults to <code>None</code> was
set to some other value. The other value might be a value
that's false in a boolean context!</li>
<li>
Never compare a boolean variable to <code>False</code> using
<code>==</code>. Use <code>if not x:</code> instead. If
you need to distinguish <code>False</code> from
<code>None</code> then chain the expressions,
such as <code>if not x and x is not None:</code>.
</li>
<li>
For sequences (strings, lists, tuples), use the fact that
empty sequences are false, so <code>if not seq:</code> or
<code>if seq:</code> is preferable to <code>if
len(seq):</code> or <code>if not
len(seq):</code>.</li>
<li>
When handling integers, implicit false may involve more risk than
benefit (i.e., accidentally handling <code>None</code> as 0). You may
compare a value which is known to be an integer (and is not the
result of <code>len()</code>) against the integer 0.
<DIV class=""><PRE>Yes: <span class="external"></span>if not users:
<span class="external"> </span>print 'no users'
<span class="external"></span>if foo == 0:
<span class="external"> </span>self.handle_zero()
<span class="external"></span>if i % 10 == 0:
<span class="external"> </span>self.handle_multiple_of_ten()</PRE></DIV>
<DIV class=""><PRE class="badcode">No: <span class="external"></span>if len(users) == 0:
<span class="external"> </span>print 'no users'
<span class="external"></span>if foo is not None and not foo:
<span class="external"> </span>self.handle_zero()
<span class="external"></span>if not i % 10:
<span class="external"> </span>self.handle_multiple_of_ten()</PRE></DIV>
</li>
<li>
Note that <code>'0'</code> (i.e., <code>0</code> as string)
evaluates to true.</li>
</ul>
</P>
</DIV></DIV>
</DIV>
<DIV class="">
<H3><A name="Deprecated_Language_Features" id="Deprecated_Language_Features">Deprecated Language Features</A></H3>
<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">
link
</A></SPAN><SPAN class="showhide_button" onclick="javascript:ShowHideByName('Deprecated_Language_Features')" name="Deprecated_Language_Features__button" id="Deprecated_Language_Features__button">▶</SPAN>
<DIV style="display:inline;" class="">
Use string methods instead of the <code>string</code> module
where possible. Use function call syntax instead
of <code>apply</code>. Use list comprehensions
and <code>for</code> loops instead of <code>filter</code> and
<code>map</code> when the function argument would have been an
inlined lambda anyway. Use <code>for</code> loops instead of