SlideShare a Scribd company logo
Zen and the Art of Python 
Clayton Parker - Pythology 101 
Zen and the Art of Python - Clayton Parker - Pythology 101
Who am I? 
Director of Engineering at Six Feet Up 
claytron on the internets
The Zen of Python 
and 
The Python Style Guide 
(PEP8)
The Zen of Python 
$ python -m this 
>>> import this
The Zen of Python 
$ python -m this 
The Zen of Python, by Tim Peters 
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. 
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!
Beautiful is better than ugly
Readability Counts
PEP 8 
We have a set of rules for that!
PEP 8 
Prevailing style wins
Comments 
# Comments start with a space after the comment symbol. Use complete 
# sentences and proper grammar when writing comments. Comments should 
# be in English unless you are certain the readers will *not* be 
# English speaking. 
# Long flowing text should be kept to under 72 columns like above. 
x = 5 # Use inline comments sparingly.
Indentation 
4 space indents 
Tabs only if the prevailing style 
Never mix tabs and spaces!
Whitespace
important_var = 5 
awesome_var = 15 
awesome_var+=10 
my_dict ={ 'spam':'eggs','ham':'parrot'} 
my_list=[3, 2,1] 
another_list = [8, 4,5,6 ] 
extra_list=my_list+another_list 
sorted ( combined_list,reverse = True)
important_var = 5 
awesome_var = 15 
awesome_var += 10 
my_dict = {'spam': 'eggs', 'ham': 'parrot'} 
my_list = [3, 2, 1] 
another_list = [8, 4, 5, 6] 
extra_list = my_list + another_list 
sorted(combined_list, reverse=True)
Max Line Length 
A hotly debated subject!
things = ['overwrite', 'photobathic', 'tranquillization', 'resiny', 'runt', 'Siganus'] 
extra_special_things = [thing for thing in extra_shiny_things if thing == 'elpidite'] 
################################################################ 79 columns --|
################################################################ 79 columns --| 
things = [ 
'overwrite', 
'photobathic', 
'tranquillization', 
'resiny', 
'runt', 
'Siganus', 
] 
extra_special_things = [ 
thing 
for thing in extra_shiny_things 
if thing == 'elpidite' 
]
################################################################ 79 columns --| 
if event.new_state.id == 'offline' and (state == 'published' or state == 'external'): 
workflow.doActionFor(obj, 'reject', workflow='custom_workflow', comment='Reject')
################################################################ 79 columns --| 
offline = event.new_state.id == 'offline' 
published = state in ['published', 'external'] 
if offline and published: 
workflow.doActionFor( 
obj, 
'reject', 
workflow='custom_workflow', 
comment='Reject content automatically', 
)
################################################################ 79 columns --| 
long_string = "Lorem ipsum dolor sit amet, consectetur adipiscing. Cras cursus elit."
################################################################ 79 columns --| 
long_string = ( 
"Lorem ipsum dolor sit amet, consectetur adipiscing." 
"Cras cursus elit." 
)
Explicit is better than implicit
import os, sys 
from my.package import *
import os 
import sys 
from my.package import Octopus, Blowfish
There should be one-- and 
preferably only one --obvious 
way to do it
# Bad 
type(obj) is type(1) 
# Good 
isinstance(obj, int)
# Bad 
my_variable == None 
# Good 
my_variable is None
# Bad 
not len(my_list) > 0 
# Good 
not my_list
# Bad 
boolean_value == False 
# Good 
not boolean_value
Flat is better than nested
for item in items: 
if some_check(item): 
# do some magic 
if another_check(item): 
# more magic 
operate_on(item)
for item in items: 
if not some_check(item): 
continue 
if not another_check(item): 
continue 
# do some magic 
# more magic 
operate_on(item)
aws_region = None 
for k,v in query_response.items(): 
if k == 'entry_list': 
for i in v: 
for k, v2 in i.items(): 
if k == 'name_value_list': 
if isinstance(v2, dict): 
for k2, v3 in v2.items(): 
if k2 == 'aws_region': 
aws_region = v3['value']
aws_region = None 
entries = query_response.get('entry_list', {}) 
values = entries.get('name_value_list', {}) 
if isinstance(values, dict): 
aws_region = values.get('aws_region', {}).get('value', None)
Tools 
flake8 - Combination of pep8 and pyflakes 
PyLint / Frosted - More in-depth linting of code 
autopep8 - Automatic PEP8 conformance
Links 
The Zen of Python - PEP 20 
Zen discussed on Stackoverflow 
The Python Style Guide - PEP 8 
Writing Idiomatic Python Book
Questions?

More Related Content

Viewers also liked

Viewers also liked (14)

01 existentialism & mans search for meaning
01  existentialism & mans search for meaning01  existentialism & mans search for meaning
01 existentialism & mans search for meaning
 
Django - The Web framework for perfectionists with deadlines
Django - The Web framework  for perfectionists with deadlinesDjango - The Web framework  for perfectionists with deadlines
Django - The Web framework for perfectionists with deadlines
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1
 
Website optimization
Website optimizationWebsite optimization
Website optimization
 
Vim for Mere Mortals
Vim for Mere MortalsVim for Mere Mortals
Vim for Mere Mortals
 
EuroDjangoCon 2009 - Ein Rückblick
EuroDjangoCon 2009 - Ein RückblickEuroDjangoCon 2009 - Ein Rückblick
EuroDjangoCon 2009 - Ein Rückblick
 
라이트닝 토크 2015 파이콘
라이트닝 토크 2015 파이콘라이트닝 토크 2015 파이콘
라이트닝 토크 2015 파이콘
 
2016 py con2016_lightingtalk_php to python
2016 py con2016_lightingtalk_php to python2016 py con2016_lightingtalk_php to python
2016 py con2016_lightingtalk_php to python
 
PythonBrasil[8] closing
PythonBrasil[8] closingPythonBrasil[8] closing
PythonBrasil[8] closing
 
Django - The Web framework for perfectionists with deadlines
Django - The Web framework for perfectionists with deadlinesDjango - The Web framework for perfectionists with deadlines
Django - The Web framework for perfectionists with deadlines
 
User-centered open source
User-centered open sourceUser-centered open source
User-centered open source
 
Digesting jQuery
Digesting jQueryDigesting jQuery
Digesting jQuery
 
Rabbitmq & Postgresql
Rabbitmq & PostgresqlRabbitmq & Postgresql
Rabbitmq & Postgresql
 
The Django Book, Chapter 16: django.contrib
The Django Book, Chapter 16: django.contribThe Django Book, Chapter 16: django.contrib
The Django Book, Chapter 16: django.contrib
 

Similar to Zen and the Art of Python

Python for scientific computing
Python for scientific computingPython for scientific computing
Python for scientific computing
Go Asgard
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School Programmers
Siva Arunachalam
 
Learn python
Learn pythonLearn python
Learn python
mocninja
 

Similar to Zen and the Art of Python (20)

Code with Style - PyOhio
Code with Style - PyOhioCode with Style - PyOhio
Code with Style - PyOhio
 
Code with style
Code with styleCode with style
Code with style
 
Code Like Pythonista
Code Like PythonistaCode Like Pythonista
Code Like Pythonista
 
Brogramming - Python, Bash for Data Processing, and Git
Brogramming - Python, Bash for Data Processing, and GitBrogramming - Python, Bash for Data Processing, and Git
Brogramming - Python, Bash for Data Processing, and Git
 
Python for scientific computing
Python for scientific computingPython for scientific computing
Python for scientific computing
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
Class 4: For and while
Class 4: For and whileClass 4: For and while
Class 4: For and while
 
PEP 498: The Monologue
PEP 498: The MonologuePEP 498: The Monologue
PEP 498: The Monologue
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School Programmers
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
 
Learn python
Learn pythonLearn python
Learn python
 
Python Basic
Python BasicPython Basic
Python Basic
 
Python slide
Python slidePython slide
Python slide
 
Python Peculiarities
Python PeculiaritiesPython Peculiarities
Python Peculiarities
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
python.pdf
python.pdfpython.pdf
python.pdf
 
Class 3: if/else
Class 3: if/elseClass 3: if/else
Class 3: if/else
 
C# to python
C# to pythonC# to python
C# to python
 
Erlang Concurrency
Erlang ConcurrencyErlang Concurrency
Erlang Concurrency
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 

More from Clayton Parker

Pioneer a Strategic Change in Content Organization with Plone
Pioneer a Strategic Change in Content Organization with PlonePioneer a Strategic Change in Content Organization with Plone
Pioneer a Strategic Change in Content Organization with Plone
Clayton Parker
 

More from Clayton Parker (17)

Customizing Your Shell With Dotfiles
Customizing Your Shell With DotfilesCustomizing Your Shell With Dotfiles
Customizing Your Shell With Dotfiles
 
Fuzzy Feelings for Fuzzy Matching
Fuzzy Feelings for Fuzzy MatchingFuzzy Feelings for Fuzzy Matching
Fuzzy Feelings for Fuzzy Matching
 
Exploring Code with Pry!
Exploring Code with Pry!Exploring Code with Pry!
Exploring Code with Pry!
 
So you think you can pdb?
So you think you can pdb?So you think you can pdb?
So you think you can pdb?
 
Managing Chaos: Merging 120 Sites into a single Plone Multisite Solution
Managing Chaos: Merging 120 Sites into a single Plone Multisite SolutionManaging Chaos: Merging 120 Sites into a single Plone Multisite Solution
Managing Chaos: Merging 120 Sites into a single Plone Multisite Solution
 
Current State of Python Packaging
Current State of Python PackagingCurrent State of Python Packaging
Current State of Python Packaging
 
Notre Dame Seamless Syndication with Lineage
Notre Dame Seamless Syndication with LineageNotre Dame Seamless Syndication with Lineage
Notre Dame Seamless Syndication with Lineage
 
Pioneer a Strategic Change in Content Organization with Plone
Pioneer a Strategic Change in Content Organization with PlonePioneer a Strategic Change in Content Organization with Plone
Pioneer a Strategic Change in Content Organization with Plone
 
Using Buildout, GenericSetup and a Policy Package to Rule the World
Using Buildout, GenericSetup and a Policy Package to Rule the WorldUsing Buildout, GenericSetup and a Policy Package to Rule the World
Using Buildout, GenericSetup and a Policy Package to Rule the World
 
Make Plone Search Act Like Google Using Solr
Make Plone Search Act Like Google Using SolrMake Plone Search Act Like Google Using Solr
Make Plone Search Act Like Google Using Solr
 
Migrating from drupal to plone with transmogrifier
Migrating from drupal to plone with transmogrifierMigrating from drupal to plone with transmogrifier
Migrating from drupal to plone with transmogrifier
 
Buildout for the Future
Buildout for the FutureBuildout for the Future
Buildout for the Future
 
Laying Pipe with Transmogrifier
Laying Pipe with TransmogrifierLaying Pipe with Transmogrifier
Laying Pipe with Transmogrifier
 
LDAP and Active Directory Authentication in Plone
LDAP and Active Directory Authentication in PloneLDAP and Active Directory Authentication in Plone
LDAP and Active Directory Authentication in Plone
 
Generic Setup De-Mystified
Generic Setup De-MystifiedGeneric Setup De-Mystified
Generic Setup De-Mystified
 
Buildout: Fostering Repeatability
Buildout: Fostering RepeatabilityBuildout: Fostering Repeatability
Buildout: Fostering Repeatability
 
Getting Plone Ready For The Prom
Getting Plone Ready For The PromGetting Plone Ready For The Prom
Getting Plone Ready For The Prom
 

Recently uploaded

Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 

Recently uploaded (20)

Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
iGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by SkilrockiGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by Skilrock
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning Framework
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdf
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
 

Zen and the Art of Python

  • 1. Zen and the Art of Python Clayton Parker - Pythology 101 Zen and the Art of Python - Clayton Parker - Pythology 101
  • 2. Who am I? Director of Engineering at Six Feet Up claytron on the internets
  • 3. The Zen of Python and The Python Style Guide (PEP8)
  • 4. The Zen of Python $ python -m this >>> import this
  • 5. The Zen of Python $ python -m this The Zen of Python, by Tim Peters 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. 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!
  • 8. PEP 8 We have a set of rules for that!
  • 9. PEP 8 Prevailing style wins
  • 10. Comments # Comments start with a space after the comment symbol. Use complete # sentences and proper grammar when writing comments. Comments should # be in English unless you are certain the readers will *not* be # English speaking. # Long flowing text should be kept to under 72 columns like above. x = 5 # Use inline comments sparingly.
  • 11. Indentation 4 space indents Tabs only if the prevailing style Never mix tabs and spaces!
  • 13. important_var = 5 awesome_var = 15 awesome_var+=10 my_dict ={ 'spam':'eggs','ham':'parrot'} my_list=[3, 2,1] another_list = [8, 4,5,6 ] extra_list=my_list+another_list sorted ( combined_list,reverse = True)
  • 14. important_var = 5 awesome_var = 15 awesome_var += 10 my_dict = {'spam': 'eggs', 'ham': 'parrot'} my_list = [3, 2, 1] another_list = [8, 4, 5, 6] extra_list = my_list + another_list sorted(combined_list, reverse=True)
  • 15. Max Line Length A hotly debated subject!
  • 16. things = ['overwrite', 'photobathic', 'tranquillization', 'resiny', 'runt', 'Siganus'] extra_special_things = [thing for thing in extra_shiny_things if thing == 'elpidite'] ################################################################ 79 columns --|
  • 17. ################################################################ 79 columns --| things = [ 'overwrite', 'photobathic', 'tranquillization', 'resiny', 'runt', 'Siganus', ] extra_special_things = [ thing for thing in extra_shiny_things if thing == 'elpidite' ]
  • 18. ################################################################ 79 columns --| if event.new_state.id == 'offline' and (state == 'published' or state == 'external'): workflow.doActionFor(obj, 'reject', workflow='custom_workflow', comment='Reject')
  • 19. ################################################################ 79 columns --| offline = event.new_state.id == 'offline' published = state in ['published', 'external'] if offline and published: workflow.doActionFor( obj, 'reject', workflow='custom_workflow', comment='Reject content automatically', )
  • 20. ################################################################ 79 columns --| long_string = "Lorem ipsum dolor sit amet, consectetur adipiscing. Cras cursus elit."
  • 21. ################################################################ 79 columns --| long_string = ( "Lorem ipsum dolor sit amet, consectetur adipiscing." "Cras cursus elit." )
  • 22. Explicit is better than implicit
  • 23. import os, sys from my.package import *
  • 24. import os import sys from my.package import Octopus, Blowfish
  • 25. There should be one-- and preferably only one --obvious way to do it
  • 26. # Bad type(obj) is type(1) # Good isinstance(obj, int)
  • 27. # Bad my_variable == None # Good my_variable is None
  • 28. # Bad not len(my_list) > 0 # Good not my_list
  • 29. # Bad boolean_value == False # Good not boolean_value
  • 30. Flat is better than nested
  • 31. for item in items: if some_check(item): # do some magic if another_check(item): # more magic operate_on(item)
  • 32. for item in items: if not some_check(item): continue if not another_check(item): continue # do some magic # more magic operate_on(item)
  • 33. aws_region = None for k,v in query_response.items(): if k == 'entry_list': for i in v: for k, v2 in i.items(): if k == 'name_value_list': if isinstance(v2, dict): for k2, v3 in v2.items(): if k2 == 'aws_region': aws_region = v3['value']
  • 34. aws_region = None entries = query_response.get('entry_list', {}) values = entries.get('name_value_list', {}) if isinstance(values, dict): aws_region = values.get('aws_region', {}).get('value', None)
  • 35. Tools flake8 - Combination of pep8 and pyflakes PyLint / Frosted - More in-depth linting of code autopep8 - Automatic PEP8 conformance
  • 36. Links The Zen of Python - PEP 20 Zen discussed on Stackoverflow The Python Style Guide - PEP 8 Writing Idiomatic Python Book