SlideShare uma empresa Scribd logo
1 de 37
Baixar para ler offline
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?

Mais conteúdo relacionado

Destaque

Destaque (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
 

Semelhante a 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
 

Semelhante a 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
 

Mais de 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
 

Mais de 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
 

Último

%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Último (20)

Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 

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