SlideShare a Scribd company logo
1 of 22
Download to read offline
TheZenofPython
Sorina CHIRILĂ
www.bitopedia.wordpress.com
Summary
1. History
2. The Zen of Python
3. Meaning of some of the aphorisms in The Zen of Python
4. Resources
5. Contact
pep20--thezenofpython
Author: Tim Peters
tim.peters@gmail.com
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.
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.
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.
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':
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()
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)
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.
explicitisbetterthanimplicit-4
If you really want to do so, then
you need to tell Python that, you
want an integer.
1 >>>int(foo)+3
2 8
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)
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!"
errorsshouldneverpasssilently
A case for this aphorism. 1 try:
2 import this
3 except ImportError:
4 print 'this is not available'
unlessexplicitlysilenced
An example for this case. 1 try:
2 v = d[k]
3 except KeyError:
4 v = d[k] = default
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
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.
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.
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.
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')
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.
resources
●
● https://www.python.
org/dev/peps/pep-0020/
●
● http://artifex.
org/~hblanks/talks/2011/pep20_b
y_example.html
●
● https://www.quora.com/What-do-
different-aphorisms-in-The-Zen-
of-Python-mean
contact
E-mail:
zambetsoare at gmail.com

More Related Content

Similar to THE ZEN OF PYTHON

Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts Pavan Babu .G
 
Celebrating 30-th anniversary of the first C++ compiler: let's find bugs in it.
Celebrating 30-th anniversary of the first C++ compiler: let's find bugs in it.Celebrating 30-th anniversary of the first C++ compiler: let's find bugs in it.
Celebrating 30-th anniversary of the first C++ compiler: let's find bugs in it.PVS-Studio
 
Python for Scientific Computing
Python for Scientific ComputingPython for Scientific Computing
Python for Scientific ComputingAlbert DeFusco
 
Building reusable libraries
Building reusable librariesBuilding reusable libraries
Building reusable librariesFelix Morgner
 
Python For Machine Learning
Python For Machine LearningPython For Machine Learning
Python For Machine LearningYounesCharfaoui
 
Code with Style - PyOhio
Code with Style - PyOhioCode with Style - PyOhio
Code with Style - PyOhioClayton Parker
 
Functional Programming in C# and F#
Functional Programming in C# and F#Functional Programming in C# and F#
Functional Programming in C# and F#Alfonso Garcia-Caro
 
C Best and Worst Practices in Embedded
C Best and Worst Practices in EmbeddedC Best and Worst Practices in Embedded
C Best and Worst Practices in EmbeddedGlobalLogic Ukraine
 
Simple is better than complex. ~私がPythonを愛する理由~
Simple is better than complex. ~私がPythonを愛する理由~Simple is better than complex. ~私がPythonを愛する理由~
Simple is better than complex. ~私がPythonを愛する理由~cocodrips
 
mooc_presentataion_mayankmanral on the subject puthon
mooc_presentataion_mayankmanral on the subject puthonmooc_presentataion_mayankmanral on the subject puthon
mooc_presentataion_mayankmanral on the subject puthongarvitbisht27
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & styleKevlin Henney
 
Threading Is Not A Model
Threading Is Not A ModelThreading Is Not A Model
Threading Is Not A Modelguest2a5acfb
 
Learn python – for beginners
Learn python – for beginnersLearn python – for beginners
Learn python – for beginnersRajKumar Rampelli
 

Similar to THE ZEN OF PYTHON (20)

Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts
 
Os Goodger
Os GoodgerOs Goodger
Os Goodger
 
Celebrating 30-th anniversary of the first C++ compiler: let's find bugs in it.
Celebrating 30-th anniversary of the first C++ compiler: let's find bugs in it.Celebrating 30-th anniversary of the first C++ compiler: let's find bugs in it.
Celebrating 30-th anniversary of the first C++ compiler: let's find bugs in it.
 
Python for Scientific Computing
Python for Scientific ComputingPython for Scientific Computing
Python for Scientific Computing
 
Doing the Impossible
Doing the ImpossibleDoing the Impossible
Doing the Impossible
 
Building reusable libraries
Building reusable librariesBuilding reusable libraries
Building reusable libraries
 
Python For Machine Learning
Python For Machine LearningPython For Machine Learning
Python For Machine Learning
 
Code with style
Code with styleCode with style
Code with style
 
ForLoops.pptx
ForLoops.pptxForLoops.pptx
ForLoops.pptx
 
Code with Style - PyOhio
Code with Style - PyOhioCode with Style - PyOhio
Code with Style - PyOhio
 
Functional Programming in C# and F#
Functional Programming in C# and F#Functional Programming in C# and F#
Functional Programming in C# and F#
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
C Best and Worst Practices in Embedded
C Best and Worst Practices in EmbeddedC Best and Worst Practices in Embedded
C Best and Worst Practices in Embedded
 
Simple is better than complex. ~私がPythonを愛する理由~
Simple is better than complex. ~私がPythonを愛する理由~Simple is better than complex. ~私がPythonを愛する理由~
Simple is better than complex. ~私がPythonを愛する理由~
 
mooc_presentataion_mayankmanral on the subject puthon
mooc_presentataion_mayankmanral on the subject puthonmooc_presentataion_mayankmanral on the subject puthon
mooc_presentataion_mayankmanral on the subject puthon
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & style
 
Threading Is Not A Model
Threading Is Not A ModelThreading Is Not A Model
Threading Is Not A Model
 
Learn python – for beginners
Learn python – for beginnersLearn python – for beginners
Learn python – for beginners
 

More from Sorina Chirilă

Electronic commerce and Data Warehouses
Electronic commerce and Data WarehousesElectronic commerce and Data Warehouses
Electronic commerce and Data WarehousesSorina Chirilă
 
Object-Oriented Analysis And Design With Applications Grady Booch
Object-Oriented Analysis And Design With Applications Grady BoochObject-Oriented Analysis And Design With Applications Grady Booch
Object-Oriented Analysis And Design With Applications Grady BoochSorina Chirilă
 
Introducing CHAOS - A graphic guide
Introducing CHAOS - A graphic guideIntroducing CHAOS - A graphic guide
Introducing CHAOS - A graphic guideSorina Chirilă
 
SNAS - CGS - MobilPRO2016
SNAS - CGS - MobilPRO2016SNAS - CGS - MobilPRO2016
SNAS - CGS - MobilPRO2016Sorina Chirilă
 
A5-Security misconfiguration-OWASP 2013
A5-Security misconfiguration-OWASP 2013   A5-Security misconfiguration-OWASP 2013
A5-Security misconfiguration-OWASP 2013 Sorina Chirilă
 
RIPS - static code analyzer for vulnerabilities in PHP
RIPS - static code analyzer for vulnerabilities in PHPRIPS - static code analyzer for vulnerabilities in PHP
RIPS - static code analyzer for vulnerabilities in PHPSorina Chirilă
 

More from Sorina Chirilă (9)

Electronic commerce and Data Warehouses
Electronic commerce and Data WarehousesElectronic commerce and Data Warehouses
Electronic commerce and Data Warehouses
 
Object-Oriented Analysis And Design With Applications Grady Booch
Object-Oriented Analysis And Design With Applications Grady BoochObject-Oriented Analysis And Design With Applications Grady Booch
Object-Oriented Analysis And Design With Applications Grady Booch
 
Introducing CHAOS - A graphic guide
Introducing CHAOS - A graphic guideIntroducing CHAOS - A graphic guide
Introducing CHAOS - A graphic guide
 
SNAS - CGS - MobilPRO2016
SNAS - CGS - MobilPRO2016SNAS - CGS - MobilPRO2016
SNAS - CGS - MobilPRO2016
 
Scan
ScanScan
Scan
 
Nikto
NiktoNikto
Nikto
 
Nikto
NiktoNikto
Nikto
 
A5-Security misconfiguration-OWASP 2013
A5-Security misconfiguration-OWASP 2013   A5-Security misconfiguration-OWASP 2013
A5-Security misconfiguration-OWASP 2013
 
RIPS - static code analyzer for vulnerabilities in PHP
RIPS - static code analyzer for vulnerabilities in PHPRIPS - static code analyzer for vulnerabilities in PHP
RIPS - static code analyzer for vulnerabilities in PHP
 

Recently uploaded

APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 

Recently uploaded (20)

APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 

THE ZEN OF PYTHON

  • 2. Summary 1. History 2. The Zen of Python 3. Meaning of some of the aphorisms in The Zen of Python 4. Resources 5. Contact
  • 3. pep20--thezenofpython Author: Tim Peters tim.peters@gmail.com 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.
  • 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.
  • 10. explicitisbetterthanimplicit-4 If you really want to do so, then you need to tell Python that, you want an integer. 1 >>>int(foo)+3 2 8
  • 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!"
  • 13. errorsshouldneverpasssilently A case for this aphorism. 1 try: 2 import this 3 except ImportError: 4 print 'this is not available'
  • 14. unlessexplicitlysilenced An example for this case. 1 try: 2 v = d[k] 3 except KeyError: 4 v = d[k] = default
  • 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.