the zen of python

22
The Zen of Python Sorina CHIRILĂ www.bitopedia.wordpress.com

Upload: sorina-chirila

Post on 12-Apr-2017

1.296 views

Category:

Education


3 download

TRANSCRIPT

Page 1: THE ZEN OF PYTHON

The Zen of Python

Sorina CHIRILĂwww.bitopedia.wordpress.com

Page 2: THE ZEN OF PYTHON

Summary1. History2. The Zen of Python 3. Meaning of some of the aphorisms in The Zen of Python4. Resources5. Contact

Page 3: THE ZEN OF PYTHON

pep 20 -- the zen of pythonAuthor: Tim Peters

[email protected]

Created : 19-Aug-2004

Post history: 22-Aug-2004

Long time Pythoneer Tim Peters succinctly channels the BDFL’s guiding principles for Python’s design into 20 aphorisms, only 19 of which have been written down.

Page 4: THE ZEN OF PYTHON

the zen of python -1Beautiful 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.

Page 5: THE ZEN OF PYTHON

the zen of python - 2There 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.

Page 6: THE ZEN OF PYTHON

beautiful is better than uglyLogical 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':

Page 7: THE ZEN OF PYTHON

explicit is better than implicit - 1Every 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 os2 print os.getcwd()

insted of this

1 from os import *2 print getcwd()

Page 8: THE ZEN OF PYTHON

explicit is better than implicit - 2Another 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.php5 15%

( The % result of me not adding a new line to the end of the echo statement)

(continue next slide)

Page 9: THE ZEN OF PYTHON

explicit is better than implicit - 3This 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 * 33 '555'

You’ll also see because Guido decided to override that particular operator. Adding them, however,1 >>> foo+32 Traceback (most recent call last):3 File "<input>", line 1, in <module>4 TypeError: cannot concatenate 'str' and 'int' objectsproduces an exception.

Page 10: THE ZEN OF PYTHON

explicit is better than implicit - 4If you really want to do so, then you need to tell Python that, you want an integer.

1 >>>int(foo)+32 8

Page 11: THE ZEN OF PYTHON

sparse is better than denseTo 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 03 else: return 1j * sqrt(-i)

versus

1 if i > 0:2 return sqrt(i)3 elif i == 0:4 return 05 else:6 return 1j * sqrt(-i)

Page 12: THE ZEN OF PYTHON

readability counts 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!"

Page 13: THE ZEN OF PYTHON

errors should never pass silentlyA case for this aphorism. 1 try:

2 import this3 except ImportError:4 print 'this is not available'

Page 14: THE ZEN OF PYTHON

unless explicitly silencedAn example for this case. 1 try:

2 v = d[k]3 except KeyError:4 v = d[k] = default

Page 15: THE ZEN OF PYTHON

in the face of ambiguity, refuse the temptation to guess - 1Consider:

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

Page 16: THE ZEN OF PYTHON

in the face of ambiguity, refuse the temptation to guess -2This 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.

Page 17: THE ZEN OF PYTHON

there should be one-and preferably only one-obvious way to do it.(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.

Page 18: THE ZEN OF PYTHON

although that way may not be obvious at first unless you’re dutchOk 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.

Page 19: THE ZEN OF PYTHON

now is better than never -1Never:

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')

Page 20: THE ZEN OF PYTHON

now is better than never -2In 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.

Page 22: THE ZEN OF PYTHON

contactE-mail:

zambetsoare at gmail.com