4. thezenofpython-1
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough
to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse
the temptation to guess.
5. thezenofpython-2
There should be one -- and
preferably only one -- obvious way
to do it.
Although that way may not be
obvious at first unless you’re
Dutch.
Now is better than never.
Although never is often better than
*right* now.
If the implementation is hard to
explain, it’s a bad idea.
If the implementation is easy to
explain, it may be a good idea.
Namespaces are one honking great
idea -- let’s do more of those.
6. beautifulisbetterthanugly
Logical operators
Use of and, or instead of &&, ||
respectively.
Though it is subjective, code seems
more readable and beautiful this
way.
1 if (is_valid(a) && b == 0 || s == 'yes')
{
versus
1 if is_valid(a) and b == 0 or s == 'yes':
7. explicitisbetterthanimplicit-1
Every time you invoke a function
you should name its module
explicitly.
In case you forget this best
practice, let the last koan remind
it to you: Namespaces are one
honking great idea -- let’s do more
of those!
1 import os
2 print os.getcwd()
insted of this
1 from os import *
2 print getcwd()
8. explicitisbetterthanimplicit-2
Another example: the ‘self’
parameter in methods.
You always have to mention
explicitly what object you are
working with.
Here’s another example of Explicit
is better than implicit, applied to
the language itself.Whyle Python is
dynamically-typed, it is also
strongly-typed.
Several scripting languages allow
things like this:
1 <?php $foo = "5";
2 echo $foo * 3;
3 ?>
4 [$]> php test.php
5 15%
( The % result of me not adding a
new line to the end of the echo
statement)
(continue next slide)
9. explicitisbetterthanimplicit-3
This is known as type coercion .
You’ll also see it used frequently
in C, where programmers often take
advantage of the compiler’s lack of
caring to put bits in places they
don’t belong.
Now, in Python, multiplying a
string by an integer, will print
the string that many times.
1 >>> foo = "5"
2 >>> foo * 3
3 '555'
You’ll also see because Guido
decided to override that particular
operator. Adding them, however,
1 >>> foo+3
2 Traceback (most recent call last):
3 File "<input>", line 1, in <module>
4 TypeError: cannot concatenate 'str' and
'int' objects
produces an exception.
11. sparseisbetterthandense
To rephrase the dictum another way,
‘Don’t try to stick too much code
on one line ‘
1 if i>0: return sqrt(i)
2 elif i==0: return 0
3 else: return 1j * sqrt(-i)
versus
1 if i > 0:
2 return sqrt(i)
3 elif i == 0:
4 return 0
5 else:
6 return 1j * sqrt(-i)
12. readabilitycounts
The easy one: compare C and Python.
And what about indentation ? Well
indented code is more readable .
Thus, in Python it’s mandatory.
1 #include <stdio.h>
2 int main(void)
3 {
4 printf("Hello, world!n");
5 return(0);
6 }
versus
print "Hello world!"
15. inthefaceofambiguity,refusethetemptationtoguess-1
Consider:
1 if not a and b:
2 do something
What binds more tightly ‘not’ or
‘and’ ? The syntax is unambiguous ,
but my memory is not.
Could it be (no) ?
1 if not (a and b):
2 do something
If short-circuiting doesn’t matter
then I’d write it:
1 if b and not a:
2 do something
Or somewhat ugly but reliable if it
does:
1 if (not a) and b:
2 do something
16. inthefaceofambiguity,refusethetemptationtoguess -2
This is subjective because someone
may argue that you should expect
the reader of your code to know
Python and thus the priorities for
‘not’ and ‘and‘, and it is not
obscure enough to justify
parantheses.
17. thereshouldbeone-andpreferablyonlyone-obviouswaytodoit.
(The exact contrary to The Perl
Programming Language’s motto -
there’s more than one way to do
it.)
How many ways could you provide to
“iterate over a sequence “ in C++ ?
Iterating over an array with
integers or pointers; iterating
over STL vectors with various kinds
of iterators … etc.
If you want to be proficient in C++
(and be able to read other people’s
code), you must learn them all. In
Pyton you must learn only one:
for element in sequence:
And isn’t obvious ? There should be
one module for every need.
18. althoughthatwaymaynotbeobviousatfirstunlessyou’redutch
Ok this mostly refers to
Guido van Rossum.
The classic trinary if-then-else
operator
(it’s a = cond?expr1:expr2 in C)
was debated hotly.
Guido came up with this:
a = expr1 if cond else expr2
This is one way to do this, and it
isn’t obvious at first. One of the
sidebars for this is always the
observation that the condition is
evaluated first irrespective of the
left-to-right order of the
operands.
19. nowisbetterthannever-1
Never:
1 f = open('i_will_stay_open_for_ages.
txt', 'w')
2 f.write('every even number > 2 is the
sum of two primes')
3 assert not 'this sentence is false'
4 f.close()
Now:
1 with open('i_will_be_closed_right_away.txt',
'w') as f:
2 f.write('the sum of two primes > 2 is an
even number')
3 raise AssertionError('this sentence is
false')
20. nowisbetterthannever-2
In the first example, an exception
will bump you out of the codeblock
before the file can be closed.
In the second, python will politely
handle this for you with context
managers.
You could of course fix the first
case by using try: and finaly:
blocks, but beautiful is better
than ugly.