SlideShare una empresa de Scribd logo
1 de 43
Descargar para leer sin conexión
Code With Style
       Clayton Parker
    Plone Symposium East 2010




         nowhere to go but
         open source
   sixfeetup.com/deploy2010
Who am I?


•   claytron on IRC
•   Python dev since 2003




                            sixfeetup.com/deploy2010
What will we learn?

•   Zen
•   PEP8
•   Tools




                      sixfeetup.com/deploy2010
Don’t dissapoint




       http://www.flickr.com/photos/docsearls/199700939/
                                                          sixfeetup.com/deploy2010
The Zen of Python
   >>> import 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!


                                                                 sixfeetup.com/deploy2010
Important Zen

•   Beautiful is better than ugly.
•   Readability counts.
•   Now is better than never.
•   Although never is often better than right now.




                                             sixfeetup.com/deploy2010
What is PEP8?


•   A style guide for Python
•   Common sense




                               sixfeetup.com/deploy2010
The importance of PEP8


•   Code is read more than it is written
•   Consistency




                                           sixfeetup.com/deploy2010
When to break the rules


•   Less readable
•   Be aware of your surroundings




                                    sixfeetup.com/deploy2010
Code layout

•   4 space indents
•   Never mix tabs and spaces!
•   Maximum line length 79 characters
•   Use blank lines sparingly




                                        sixfeetup.com/deploy2010
Examples


           sixfeetup.com/deploy2010
Maximum line length
                         BAD
# Example 1
things = ['overwrite', 'photobathic', 'tranquillization', 'resiny', 'runt', 'elpidite', 'Siganus', 'upplough', 'coed']
# This list comprehension is insane and should probably be split up into multiple statements
special_things = [special_thing for special_thing in special_things if special_thing == 'elpidite']

#                                                                 79 columns ->

# Example 2
if event.new_state.id == 'offline' and (state == 'published' or state == 'external'):
    workflow.doActionFor(content, 'reject', workflow='my_custom_workflow', comment='Rejecting content automatically')




                                                                                          sixfeetup.com/deploy2010
Maximum line length
          GOOD
# Example 1
things = [
    'overwrite',
    'photobathic',
    'tranquillization',
    'resiny',
    'runt',
    'elpidite',
    'Siganus',
    'upplough',
    'coed']


# Instead of using a list comprehension, we'll use the filter built-in
# to make the code have more clarity.
def my_checker(item):
    if item == "elpidite":
        return item


special_things = filter(my_checker, things)



                                                                    sixfeetup.com/deploy2010
Maximum line length
          GOOD

# Example 2
public_state = state in ['published', 'external']
if event.new_state.id == 'offline' and public_state:
    workflow.doActionFor(
        content,
        'reject',
        workflow='my_custom_workflow',
        comment='Rejecting content automatically')




                                                       sixfeetup.com/deploy2010
Blank lines
    import random

    ASCII_CAT1 = """
     /_/
    ( o.o )
     > ^ <
    """
    ASCII_CAT2 = """
      _ _/|
     'o.0'
     =(___)=
        U
    """
    CATS = [ASCII_CAT1, ASCII_CAT2]



    class CatMadness(object):
        """Cats are curious animals. This is a silly example"""

        def __init__(self, num_cats=0):
            self.num_cats = num_cats

        def make_it_rain(self):
            """Just cats, no dogs yet."""
            count = self.num_cats
            while count > 0:
                count -= 1
                print random.choice(CATS)

                                                                  sixfeetup.com/deploy2010
Imports
                  BAD
import os, sys
import config
from my.package.content import *




                 GOOD
import os
import sys
# explicit is better than implicit
from my.package import config
from my.package.content import Octopus, Blowfish




                                                   sixfeetup.com/deploy2010
Whitespace
               BAD
counter         =5
another_counter =15
more_cowbell= counter+10
my_dict ={'spam':'eggs','ham':'parrot'}



def complex (real, imag = 0.0):
    return magic(r = real, i = imag)



my_list=[1, 2,3]
another_list = [4,5,6]
combined_list=my_list+another_list


                                          sixfeetup.com/deploy2010
Whitespace
              GOOD
counter = 5
another_counter = 15
more_cowbell = counter + 10
my_dict = {'spam': 'eggs', 'ham': 'parrot'}



def complex(real, imag=0.0):
    return magic(r=real, i=imag)



my_list = [1, 2, 3]
another_list = [4, 5, 6]
combined_list = my_list + another_list


                                              sixfeetup.com/deploy2010
Guido taking a look




       http://www.flickr.com/photos/7901942@N04/3528995869/   sixfeetup.com/deploy2010
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 characters like above.

x = 5   # Use inline comments sparingly.




                                                                sixfeetup.com/deploy2010
Naming conventions
   # my/package/camelcase.py
   UPPERCASE_UNDERSCORES = "foo"



   class CamelCase(object):

       def separated_with_underscores(self):
           my_variable = "foo"
           pass

       def mixedCaseInPlone(self):
           pass

       def _private_method(self):
           pass




                                               sixfeetup.com/deploy2010
Recommendations
      BAD
if type(obj) is type(1)

if my_variable == None

if not len(my_list)

if boolean_value == True



                   GOOD
if isinstance(obj, int):

if my_variable is None

if not my_list

if boolean_value

                           sixfeetup.com/deploy2010
pep8.py


•   Check your code against PEP8
•   Brought back from the dead!




                                   sixfeetup.com/deploy2010
pep8.py

$ pep8 example-pep8.py
example-pep8.py:1:10: E401 multiple imports on one line
example-pep8.py:3:1: E302 expected 2 blank lines, found 1
example-pep8.py:4:80: E501 line too long (91 characters)
example-pep8.py:9:16: E225 missing whitespace around operator
example-pep8.py:10:5: E301 expected 1 blank line, found 0
example-pep8.py:10:35: E251 no spaces around keyword / parameter equals
example-pep8.py:11:26: W601 .has_key() is deprecated, use 'in'




                                                       sixfeetup.com/deploy2010
pep8.py

$ pep8 --ignore=W601,E301 example-pep8.py
example-pep8.py:1:10: E401 multiple imports on one line
example-pep8.py:3:1: E302 expected 2 blank lines, found 1
example-pep8.py:4:80: E501 line too long (91 characters)
example-pep8.py:9:16: E225 missing whitespace around operator
example-pep8.py:10:35: E251 no spaces around keyword / parameter equals




                                                       sixfeetup.com/deploy2010
Pyflakes


•   Fast
•   Catch common mistakes




                            sixfeetup.com/deploy2010
Pyflakes

   $ pyflakes example-pyflakes.py
   example-pyflakes.py:4: invalid syntax
   for directory in os.listdir('.')
                                    ^




                                           sixfeetup.com/deploy2010
Pylint


•   More in depth
•   Knows about your code




                            sixfeetup.com/deploy2010
Pylint
$ pylint example-pep8.py
************* Module example-pep8
C: 4: Line too long (91/80)
C: 1: Missing docstring
C: 1: Invalid name "example-pep8" (should match (([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$)
C: 9:WidgetMaker.__init__: Operator not preceded by a space
        whatzit=None
               ^
W: 9:WidgetMaker.__init__: Unused variable 'whatzit'
W: 8:WidgetMaker.__init__: Unused variable 'blerg'
C: 10:WidgetMaker.blerg_list: Missing docstring
E: 11:WidgetMaker.blerg_list: Instance of 'WidgetMaker' has no 'blerg' member
E: 12:WidgetMaker.blerg_list: 'continue' not properly in loop
E: 13:WidgetMaker.blerg_list: Instance of 'WidgetMaker' has no 'blerg' member
R: 3:WidgetMaker: Too few public methods (1/2)
W: 1: Unused import sys
W: 1: Unused import os

Report
======
10 statements analysed.

Global evaluation
-----------------
Your code has been rated at -15.00/10
                                                                         sixfeetup.com/deploy2010
Editor Integration


                 sixfeetup.com/deploy2010
Vim




      sixfeetup.com/deploy2010
Vim




      sixfeetup.com/deploy2010
Vim
•   pyflakes.vim
    •   http://www.vim.org/scripts/script.php?
        script_id=2441
•   pep8.vim
    •   http://www.vim.org/scripts/script.php?
        script_id=2914



                                                 sixfeetup.com/deploy2010
Emacs




        sixfeetup.com/deploy2010
Emacs

•   Pyflakes
    •   http://www.plope.com/Members/chrism/flymake-
        mode
•   I’m not an Emacs dude, better ways to do this?




                                             sixfeetup.com/deploy2010
TextMate




           sixfeetup.com/deploy2010
TextMate




           sixfeetup.com/deploy2010
TextMate

•   Zope.tmbundle (pyflakes on save)
    •   http://github.com/tomster/zope.tmbundle
•   PEP8 Bundle (requires python2.5+)
    •   http://github.com/ppierre/python-pep8-tmbundle




                                              sixfeetup.com/deploy2010
Buildout
   [buildout]
   ...
   parts =
       ...
       pylint

   [pylint]
   recipe = zc.recipe.egg
   eggs =
       pylint
       ${instance:eggs}
   entry-points = pylint=pylint.lint:Run
   scripts = pylint
   arguments = [
       '--output-format=colorized',
       '--zope=y',
       '--reports=no',
   # Suppress certain errors (interfaces missing __init__,
   invalid imports etc)
       '--disable-msg=E0611,F0401,W0232',
       ] + sys.argv[1:]


                                                        sixfeetup.com/deploy2010
What did we learn

•   Zen
•   PEP8
•   Style
•   Development workflow




                          sixfeetup.com/deploy2010
Happiness!




       http://www.flickr.com/photos/docsearls/199700290/   sixfeetup.com/deploy2010
Links

•   PEP8 - http://www.python.org/dev/peps/pep-0008/

•   Pyflakes - http://divmod.org/trac/wiki/DivmodPyflakes

•   pylint - http://www.logilab.org/857

•   pyflakes.vim - http://www.vim.org/scripts/script.php?script_id=2441

•   PEP8 and pyflakes in emacs - http://github.com/akaihola/flymake-python

•   TextMate Zope Bundle - http://github.com/tomster/zope.tmbundle




                                                                         sixfeetup.com/deploy2010
More info at:
sixfeetup.com/deploy2010




            sixfeetup.com/deploy2010

Más contenido relacionado

La actualidad más candente

Perl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim PerlchinaPerl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim PerlchinaLin Yo-An
 
ScotRuby - Dark side of ruby
ScotRuby - Dark side of rubyScotRuby - Dark side of ruby
ScotRuby - Dark side of rubyGautam Rege
 
Writing SOLID code (in practice)
Writing SOLID code (in practice)Writing SOLID code (in practice)
Writing SOLID code (in practice)Tomasz Wójcik
 
Reusando componentes Zope fuera de Zope
Reusando componentes Zope fuera de ZopeReusando componentes Zope fuera de Zope
Reusando componentes Zope fuera de Zopementtes
 
Making JavaScript Libraries More Approachable
Making JavaScript Libraries More ApproachableMaking JavaScript Libraries More Approachable
Making JavaScript Libraries More ApproachablePamela Fox
 
Perl Xpath Lightning Talk
Perl Xpath Lightning TalkPerl Xpath Lightning Talk
Perl Xpath Lightning Talkddn123456
 
BASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic InterpolationBASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic InterpolationWorkhorse Computing
 
The $path to knowledge: What little it take to unit-test Perl.
The $path to knowledge: What little it take to unit-test Perl.The $path to knowledge: What little it take to unit-test Perl.
The $path to knowledge: What little it take to unit-test Perl.Workhorse Computing
 
The bones of a nice Python script
The bones of a nice Python scriptThe bones of a nice Python script
The bones of a nice Python scriptsaniac
 
Descobrindo a linguagem Perl
Descobrindo a linguagem PerlDescobrindo a linguagem Perl
Descobrindo a linguagem Perlgarux
 
Synapseindia reviews sharing intro on php
Synapseindia reviews sharing intro on phpSynapseindia reviews sharing intro on php
Synapseindia reviews sharing intro on phpSynapseindiaComplaints
 
The Perl API for the Mortally Terrified (beta)
The Perl API for the Mortally Terrified (beta)The Perl API for the Mortally Terrified (beta)
The Perl API for the Mortally Terrified (beta)Mike Friedman
 
Metaprogramação em Python: Decorators e Metaclasses
Metaprogramação em Python: Decorators e MetaclassesMetaprogramação em Python: Decorators e Metaclasses
Metaprogramação em Python: Decorators e MetaclassesFelipe Volpone
 
Red Flags in Programming
Red Flags in ProgrammingRed Flags in Programming
Red Flags in ProgrammingxSawyer
 
Understanding Prototypal Inheritance
Understanding Prototypal InheritanceUnderstanding Prototypal Inheritance
Understanding Prototypal InheritanceGuy Royse
 

La actualidad más candente (20)

Perl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim PerlchinaPerl.Hacks.On.Vim Perlchina
Perl.Hacks.On.Vim Perlchina
 
ScotRuby - Dark side of ruby
ScotRuby - Dark side of rubyScotRuby - Dark side of ruby
ScotRuby - Dark side of ruby
 
Writing SOLID code (in practice)
Writing SOLID code (in practice)Writing SOLID code (in practice)
Writing SOLID code (in practice)
 
Dsl
DslDsl
Dsl
 
Reusando componentes Zope fuera de Zope
Reusando componentes Zope fuera de ZopeReusando componentes Zope fuera de Zope
Reusando componentes Zope fuera de Zope
 
Making JavaScript Libraries More Approachable
Making JavaScript Libraries More ApproachableMaking JavaScript Libraries More Approachable
Making JavaScript Libraries More Approachable
 
Perl Xpath Lightning Talk
Perl Xpath Lightning TalkPerl Xpath Lightning Talk
Perl Xpath Lightning Talk
 
Getting Testy With Perl6
Getting Testy With Perl6Getting Testy With Perl6
Getting Testy With Perl6
 
BASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic InterpolationBASH Variables Part 1: Basic Interpolation
BASH Variables Part 1: Basic Interpolation
 
The $path to knowledge: What little it take to unit-test Perl.
The $path to knowledge: What little it take to unit-test Perl.The $path to knowledge: What little it take to unit-test Perl.
The $path to knowledge: What little it take to unit-test Perl.
 
The bones of a nice Python script
The bones of a nice Python scriptThe bones of a nice Python script
The bones of a nice Python script
 
Descobrindo a linguagem Perl
Descobrindo a linguagem PerlDescobrindo a linguagem Perl
Descobrindo a linguagem Perl
 
Synapseindia reviews sharing intro on php
Synapseindia reviews sharing intro on phpSynapseindia reviews sharing intro on php
Synapseindia reviews sharing intro on php
 
The Perl API for the Mortally Terrified (beta)
The Perl API for the Mortally Terrified (beta)The Perl API for the Mortally Terrified (beta)
The Perl API for the Mortally Terrified (beta)
 
Cross platform php
Cross platform phpCross platform php
Cross platform php
 
Working with text, Regular expressions
Working with text, Regular expressionsWorking with text, Regular expressions
Working with text, Regular expressions
 
Lists and arrays
Lists and arraysLists and arrays
Lists and arrays
 
Metaprogramação em Python: Decorators e Metaclasses
Metaprogramação em Python: Decorators e MetaclassesMetaprogramação em Python: Decorators e Metaclasses
Metaprogramação em Python: Decorators e Metaclasses
 
Red Flags in Programming
Red Flags in ProgrammingRed Flags in Programming
Red Flags in Programming
 
Understanding Prototypal Inheritance
Understanding Prototypal InheritanceUnderstanding Prototypal Inheritance
Understanding Prototypal Inheritance
 

Destacado

IPython from 30,000 feet
IPython from 30,000 feetIPython from 30,000 feet
IPython from 30,000 feettakluyver
 
Effectively using Open Source with conda
Effectively using Open Source with condaEffectively using Open Source with conda
Effectively using Open Source with condaTravis Oliphant
 
Django mongodb -djangoday_
Django mongodb -djangoday_Django mongodb -djangoday_
Django mongodb -djangoday_WEBdeBS
 
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.contribTzu-ping Chung
 
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 pythonJiho Lee
 
Overview of Testing Talks at Pycon
Overview of Testing Talks at PyconOverview of Testing Talks at Pycon
Overview of Testing Talks at PyconJacqueline Kazil
 
The Django Book Chapter 9 - Django Workshop - Taipei.py
The Django Book Chapter 9 - Django Workshop - Taipei.pyThe Django Book Chapter 9 - Django Workshop - Taipei.py
The Django Book Chapter 9 - Django Workshop - Taipei.pyTzu-ping Chung
 
라이트닝 토크 2015 파이콘
라이트닝 토크 2015 파이콘라이트닝 토크 2015 파이콘
라이트닝 토크 2015 파이콘Jiho Lee
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1Ke Wei Louis
 
Rabbitmq & Postgresql
Rabbitmq & PostgresqlRabbitmq & Postgresql
Rabbitmq & PostgresqlLucio Grenzi
 
2007 - 应用系统脆弱性概论
2007 - 应用系统脆弱性概论 2007 - 应用系统脆弱性概论
2007 - 应用系统脆弱性概论 Na Lee
 
NoSql Day - Chiusura
NoSql Day - ChiusuraNoSql Day - Chiusura
NoSql Day - ChiusuraWEBdeBS
 
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 deadlinesMarkus Zapke-Gründemann
 
Authentication & Authorization in ASPdotNet MVC
Authentication & Authorization in ASPdotNet MVCAuthentication & Authorization in ASPdotNet MVC
Authentication & Authorization in ASPdotNet MVCMindfire Solutions
 

Destacado (20)

IPython from 30,000 feet
IPython from 30,000 feetIPython from 30,000 feet
IPython from 30,000 feet
 
Effectively using Open Source with conda
Effectively using Open Source with condaEffectively using Open Source with conda
Effectively using Open Source with conda
 
Django mongodb -djangoday_
Django mongodb -djangoday_Django mongodb -djangoday_
Django mongodb -djangoday_
 
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
 
Django-Queryset
Django-QuerysetDjango-Queryset
Django-Queryset
 
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
 
Overview of Testing Talks at Pycon
Overview of Testing Talks at PyconOverview of Testing Talks at Pycon
Overview of Testing Talks at Pycon
 
Html5 History-API
Html5 History-APIHtml5 History-API
Html5 History-API
 
The Django Book Chapter 9 - Django Workshop - Taipei.py
The Django Book Chapter 9 - Django Workshop - Taipei.pyThe Django Book Chapter 9 - Django Workshop - Taipei.py
The Django Book Chapter 9 - Django Workshop - Taipei.py
 
라이트닝 토크 2015 파이콘
라이트닝 토크 2015 파이콘라이트닝 토크 2015 파이콘
라이트닝 토크 2015 파이콘
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1
 
User-centered open source
User-centered open sourceUser-centered open source
User-centered open source
 
Rabbitmq & Postgresql
Rabbitmq & PostgresqlRabbitmq & Postgresql
Rabbitmq & Postgresql
 
Bottle - Python Web Microframework
Bottle - Python Web MicroframeworkBottle - Python Web Microframework
Bottle - Python Web Microframework
 
Website optimization
Website optimizationWebsite optimization
Website optimization
 
PyClab.__init__(self)
PyClab.__init__(self)PyClab.__init__(self)
PyClab.__init__(self)
 
2007 - 应用系统脆弱性概论
2007 - 应用系统脆弱性概论 2007 - 应用系统脆弱性概论
2007 - 应用系统脆弱性概论
 
NoSql Day - Chiusura
NoSql Day - ChiusuraNoSql Day - Chiusura
NoSql Day - Chiusura
 
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
 
Authentication & Authorization in ASPdotNet MVC
Authentication & Authorization in ASPdotNet MVCAuthentication & Authorization in ASPdotNet MVC
Authentication & Authorization in ASPdotNet MVC
 

Similar a Code with style

Zen and the Art of Python
Zen and the Art of PythonZen and the Art of Python
Zen and the Art of PythonClayton Parker
 
Code Like Pythonista
Code Like PythonistaCode Like Pythonista
Code Like PythonistaChiyoung Song
 
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 GitRon Reiter
 
Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Qiangning Hong
 
Write your Ruby in Style
Write your Ruby in StyleWrite your Ruby in Style
Write your Ruby in StyleBhavin Javia
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanWei-Yuan Chang
 
Secure Programming Practices in C++ (NDC Oslo 2018)
Secure Programming Practices in C++ (NDC Oslo 2018)Secure Programming Practices in C++ (NDC Oslo 2018)
Secure Programming Practices in C++ (NDC Oslo 2018)Patricia Aas
 
Python Tricks That You Can't Live Without
Python Tricks That You Can't Live WithoutPython Tricks That You Can't Live Without
Python Tricks That You Can't Live WithoutAudrey Roy
 
TYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase frameworkTYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase frameworkChristian Trabold
 
Questioning the status quo
Questioning the status quoQuestioning the status quo
Questioning the status quoIvano Pagano
 
Good practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimizationGood practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimizationPrestaShop
 
Drupal 8: A story of growing up and getting off the island
Drupal 8: A story of growing up and getting off the islandDrupal 8: A story of growing up and getting off the island
Drupal 8: A story of growing up and getting off the islandAngela Byron
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018Mike Harris
 

Similar a Code with style (20)

Zen and the Art of Python
Zen and the Art of PythonZen and the Art of Python
Zen and the Art of Python
 
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于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Php extensions
Php extensionsPhp extensions
Php extensions
 
Write your Ruby in Style
Write your Ruby in StyleWrite your Ruby in Style
Write your Ruby in Style
 
Intro
IntroIntro
Intro
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
 
Secure Programming Practices in C++ (NDC Oslo 2018)
Secure Programming Practices in C++ (NDC Oslo 2018)Secure Programming Practices in C++ (NDC Oslo 2018)
Secure Programming Practices in C++ (NDC Oslo 2018)
 
Php extensions
Php extensionsPhp extensions
Php extensions
 
Php extensions
Php extensionsPhp extensions
Php extensions
 
Python Tricks That You Can't Live Without
Python Tricks That You Can't Live WithoutPython Tricks That You Can't Live Without
Python Tricks That You Can't Live Without
 
TYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase frameworkTYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase framework
 
Questioning the status quo
Questioning the status quoQuestioning the status quo
Questioning the status quo
 
Good practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimizationGood practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimization
 
Drupal 8: A story of growing up and getting off the island
Drupal 8: A story of growing up and getting off the islandDrupal 8: A story of growing up and getting off the island
Drupal 8: A story of growing up and getting off the island
 
C# to python
C# to pythonC# to python
C# to python
 
Metadata-driven Testing
Metadata-driven TestingMetadata-driven Testing
Metadata-driven Testing
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
 

Más de Clayton Parker

Customizing Your Shell With Dotfiles
Customizing Your Shell With DotfilesCustomizing Your Shell With Dotfiles
Customizing Your Shell With DotfilesClayton Parker
 
Fuzzy Feelings for Fuzzy Matching
Fuzzy Feelings for Fuzzy MatchingFuzzy Feelings for Fuzzy Matching
Fuzzy Feelings for Fuzzy MatchingClayton Parker
 
Exploring Code with Pry!
Exploring Code with Pry!Exploring Code with Pry!
Exploring Code with Pry!Clayton Parker
 
So you think you can pdb?
So you think you can pdb?So you think you can pdb?
So you think you can pdb?Clayton Parker
 
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 SolutionClayton Parker
 
Current State of Python Packaging
Current State of Python PackagingCurrent State of Python Packaging
Current State of Python PackagingClayton Parker
 
Notre Dame Seamless Syndication with Lineage
Notre Dame Seamless Syndication with LineageNotre Dame Seamless Syndication with Lineage
Notre Dame Seamless Syndication with LineageClayton 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 PloneClayton Parker
 
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 WorldClayton Parker
 
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 SolrClayton Parker
 
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 transmogrifierClayton Parker
 
Buildout for the Future
Buildout for the FutureBuildout for the Future
Buildout for the FutureClayton Parker
 
Laying Pipe with Transmogrifier
Laying Pipe with TransmogrifierLaying Pipe with Transmogrifier
Laying Pipe with TransmogrifierClayton Parker
 
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 PloneClayton Parker
 
Using Buildout to Develop and Deploy Python Projects
Using Buildout to Develop and Deploy Python ProjectsUsing Buildout to Develop and Deploy Python Projects
Using Buildout to Develop and Deploy Python ProjectsClayton Parker
 
Generic Setup De-Mystified
Generic Setup De-MystifiedGeneric Setup De-Mystified
Generic Setup De-MystifiedClayton Parker
 
Buildout: Fostering Repeatability
Buildout: Fostering RepeatabilityBuildout: Fostering Repeatability
Buildout: Fostering RepeatabilityClayton Parker
 
Getting Plone Ready For The Prom
Getting Plone Ready For The PromGetting Plone Ready For The Prom
Getting Plone Ready For The PromClayton Parker
 

Más de Clayton Parker (20)

Customizing Your Shell With Dotfiles
Customizing Your Shell With DotfilesCustomizing Your Shell With Dotfiles
Customizing Your Shell With Dotfiles
 
Vim for Mere Mortals
Vim for Mere MortalsVim for Mere Mortals
Vim for Mere Mortals
 
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
 
Buildout future
Buildout futureBuildout future
Buildout 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
 
Using Buildout to Develop and Deploy Python Projects
Using Buildout to Develop and Deploy Python ProjectsUsing Buildout to Develop and Deploy Python Projects
Using Buildout to Develop and Deploy Python Projects
 
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

Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 

Último (20)

Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 

Code with style

  • 1. Code With Style Clayton Parker Plone Symposium East 2010 nowhere to go but open source sixfeetup.com/deploy2010
  • 2. Who am I? • claytron on IRC • Python dev since 2003 sixfeetup.com/deploy2010
  • 3. What will we learn? • Zen • PEP8 • Tools sixfeetup.com/deploy2010
  • 4. Don’t dissapoint http://www.flickr.com/photos/docsearls/199700939/ sixfeetup.com/deploy2010
  • 5. The Zen of Python >>> import 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! sixfeetup.com/deploy2010
  • 6. Important Zen • Beautiful is better than ugly. • Readability counts. • Now is better than never. • Although never is often better than right now. sixfeetup.com/deploy2010
  • 7. What is PEP8? • A style guide for Python • Common sense sixfeetup.com/deploy2010
  • 8. The importance of PEP8 • Code is read more than it is written • Consistency sixfeetup.com/deploy2010
  • 9. When to break the rules • Less readable • Be aware of your surroundings sixfeetup.com/deploy2010
  • 10. Code layout • 4 space indents • Never mix tabs and spaces! • Maximum line length 79 characters • Use blank lines sparingly sixfeetup.com/deploy2010
  • 11. Examples sixfeetup.com/deploy2010
  • 12. Maximum line length BAD # Example 1 things = ['overwrite', 'photobathic', 'tranquillization', 'resiny', 'runt', 'elpidite', 'Siganus', 'upplough', 'coed'] # This list comprehension is insane and should probably be split up into multiple statements special_things = [special_thing for special_thing in special_things if special_thing == 'elpidite'] # 79 columns -> # Example 2 if event.new_state.id == 'offline' and (state == 'published' or state == 'external'): workflow.doActionFor(content, 'reject', workflow='my_custom_workflow', comment='Rejecting content automatically') sixfeetup.com/deploy2010
  • 13. Maximum line length GOOD # Example 1 things = [ 'overwrite', 'photobathic', 'tranquillization', 'resiny', 'runt', 'elpidite', 'Siganus', 'upplough', 'coed'] # Instead of using a list comprehension, we'll use the filter built-in # to make the code have more clarity. def my_checker(item): if item == "elpidite": return item special_things = filter(my_checker, things) sixfeetup.com/deploy2010
  • 14. Maximum line length GOOD # Example 2 public_state = state in ['published', 'external'] if event.new_state.id == 'offline' and public_state: workflow.doActionFor( content, 'reject', workflow='my_custom_workflow', comment='Rejecting content automatically') sixfeetup.com/deploy2010
  • 15. Blank lines import random ASCII_CAT1 = """ /_/ ( o.o ) > ^ < """ ASCII_CAT2 = """ _ _/| 'o.0' =(___)= U """ CATS = [ASCII_CAT1, ASCII_CAT2] class CatMadness(object): """Cats are curious animals. This is a silly example""" def __init__(self, num_cats=0): self.num_cats = num_cats def make_it_rain(self): """Just cats, no dogs yet.""" count = self.num_cats while count > 0: count -= 1 print random.choice(CATS) sixfeetup.com/deploy2010
  • 16. Imports BAD import os, sys import config from my.package.content import * GOOD import os import sys # explicit is better than implicit from my.package import config from my.package.content import Octopus, Blowfish sixfeetup.com/deploy2010
  • 17. Whitespace BAD counter =5 another_counter =15 more_cowbell= counter+10 my_dict ={'spam':'eggs','ham':'parrot'} def complex (real, imag = 0.0): return magic(r = real, i = imag) my_list=[1, 2,3] another_list = [4,5,6] combined_list=my_list+another_list sixfeetup.com/deploy2010
  • 18. Whitespace GOOD counter = 5 another_counter = 15 more_cowbell = counter + 10 my_dict = {'spam': 'eggs', 'ham': 'parrot'} def complex(real, imag=0.0): return magic(r=real, i=imag) my_list = [1, 2, 3] another_list = [4, 5, 6] combined_list = my_list + another_list sixfeetup.com/deploy2010
  • 19. Guido taking a look http://www.flickr.com/photos/7901942@N04/3528995869/ sixfeetup.com/deploy2010
  • 20. 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 characters like above. x = 5 # Use inline comments sparingly. sixfeetup.com/deploy2010
  • 21. Naming conventions # my/package/camelcase.py UPPERCASE_UNDERSCORES = "foo" class CamelCase(object): def separated_with_underscores(self): my_variable = "foo" pass def mixedCaseInPlone(self): pass def _private_method(self): pass sixfeetup.com/deploy2010
  • 22. Recommendations BAD if type(obj) is type(1) if my_variable == None if not len(my_list) if boolean_value == True GOOD if isinstance(obj, int): if my_variable is None if not my_list if boolean_value sixfeetup.com/deploy2010
  • 23. pep8.py • Check your code against PEP8 • Brought back from the dead! sixfeetup.com/deploy2010
  • 24. pep8.py $ pep8 example-pep8.py example-pep8.py:1:10: E401 multiple imports on one line example-pep8.py:3:1: E302 expected 2 blank lines, found 1 example-pep8.py:4:80: E501 line too long (91 characters) example-pep8.py:9:16: E225 missing whitespace around operator example-pep8.py:10:5: E301 expected 1 blank line, found 0 example-pep8.py:10:35: E251 no spaces around keyword / parameter equals example-pep8.py:11:26: W601 .has_key() is deprecated, use 'in' sixfeetup.com/deploy2010
  • 25. pep8.py $ pep8 --ignore=W601,E301 example-pep8.py example-pep8.py:1:10: E401 multiple imports on one line example-pep8.py:3:1: E302 expected 2 blank lines, found 1 example-pep8.py:4:80: E501 line too long (91 characters) example-pep8.py:9:16: E225 missing whitespace around operator example-pep8.py:10:35: E251 no spaces around keyword / parameter equals sixfeetup.com/deploy2010
  • 26. Pyflakes • Fast • Catch common mistakes sixfeetup.com/deploy2010
  • 27. Pyflakes $ pyflakes example-pyflakes.py example-pyflakes.py:4: invalid syntax for directory in os.listdir('.') ^ sixfeetup.com/deploy2010
  • 28. Pylint • More in depth • Knows about your code sixfeetup.com/deploy2010
  • 29. Pylint $ pylint example-pep8.py ************* Module example-pep8 C: 4: Line too long (91/80) C: 1: Missing docstring C: 1: Invalid name "example-pep8" (should match (([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$) C: 9:WidgetMaker.__init__: Operator not preceded by a space whatzit=None ^ W: 9:WidgetMaker.__init__: Unused variable 'whatzit' W: 8:WidgetMaker.__init__: Unused variable 'blerg' C: 10:WidgetMaker.blerg_list: Missing docstring E: 11:WidgetMaker.blerg_list: Instance of 'WidgetMaker' has no 'blerg' member E: 12:WidgetMaker.blerg_list: 'continue' not properly in loop E: 13:WidgetMaker.blerg_list: Instance of 'WidgetMaker' has no 'blerg' member R: 3:WidgetMaker: Too few public methods (1/2) W: 1: Unused import sys W: 1: Unused import os Report ====== 10 statements analysed. Global evaluation ----------------- Your code has been rated at -15.00/10 sixfeetup.com/deploy2010
  • 30. Editor Integration sixfeetup.com/deploy2010
  • 31. Vim sixfeetup.com/deploy2010
  • 32. Vim sixfeetup.com/deploy2010
  • 33. Vim • pyflakes.vim • http://www.vim.org/scripts/script.php? script_id=2441 • pep8.vim • http://www.vim.org/scripts/script.php? script_id=2914 sixfeetup.com/deploy2010
  • 34. Emacs sixfeetup.com/deploy2010
  • 35. Emacs • Pyflakes • http://www.plope.com/Members/chrism/flymake- mode • I’m not an Emacs dude, better ways to do this? sixfeetup.com/deploy2010
  • 36. TextMate sixfeetup.com/deploy2010
  • 37. TextMate sixfeetup.com/deploy2010
  • 38. TextMate • Zope.tmbundle (pyflakes on save) • http://github.com/tomster/zope.tmbundle • PEP8 Bundle (requires python2.5+) • http://github.com/ppierre/python-pep8-tmbundle sixfeetup.com/deploy2010
  • 39. Buildout [buildout] ... parts = ... pylint [pylint] recipe = zc.recipe.egg eggs = pylint ${instance:eggs} entry-points = pylint=pylint.lint:Run scripts = pylint arguments = [ '--output-format=colorized', '--zope=y', '--reports=no', # Suppress certain errors (interfaces missing __init__, invalid imports etc) '--disable-msg=E0611,F0401,W0232', ] + sys.argv[1:] sixfeetup.com/deploy2010
  • 40. What did we learn • Zen • PEP8 • Style • Development workflow sixfeetup.com/deploy2010
  • 41. Happiness! http://www.flickr.com/photos/docsearls/199700290/ sixfeetup.com/deploy2010
  • 42. Links • PEP8 - http://www.python.org/dev/peps/pep-0008/ • Pyflakes - http://divmod.org/trac/wiki/DivmodPyflakes • pylint - http://www.logilab.org/857 • pyflakes.vim - http://www.vim.org/scripts/script.php?script_id=2441 • PEP8 and pyflakes in emacs - http://github.com/akaihola/flymake-python • TextMate Zope Bundle - http://github.com/tomster/zope.tmbundle sixfeetup.com/deploy2010
  • 43. More info at: sixfeetup.com/deploy2010 sixfeetup.com/deploy2010