SlideShare a Scribd company logo
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

More Related Content

PDF
Code with Style - PyOhio
PDF
Puppet Camp Paris 2015: Power of Puppet 4 (Beginner)
PDF
Your code sucks, let's fix it! - php|tek13
PDF
Perl.Hacks.On.Vim
PDF
Ruby 入門 第一次就上手
PDF
Good Evils In Perl
PDF
Perl.Hacks.On.Vim Perlchina
PPSX
Symfony2 meets propel 1.5
Code with Style - PyOhio
Puppet Camp Paris 2015: Power of Puppet 4 (Beginner)
Your code sucks, let's fix it! - php|tek13
Perl.Hacks.On.Vim
Ruby 入門 第一次就上手
Good Evils In Perl
Perl.Hacks.On.Vim Perlchina
Symfony2 meets propel 1.5

What's hot (20)

PDF
Perl.Hacks.On.Vim Perlchina
PDF
ScotRuby - Dark side of ruby
PDF
Writing SOLID code (in practice)
KEY
Dsl
PDF
Reusando componentes Zope fuera de Zope
PDF
Making JavaScript Libraries More Approachable
PPT
Perl Xpath Lightning Talk
PDF
Getting Testy With Perl6
PDF
BASH Variables Part 1: Basic Interpolation
PDF
The $path to knowledge: What little it take to unit-test Perl.
ODP
The bones of a nice Python script
PDF
Descobrindo a linguagem Perl
PPT
Synapseindia reviews sharing intro on php
PDF
The Perl API for the Mortally Terrified (beta)
PDF
Cross platform php
PDF
Working with text, Regular expressions
PDF
Metaprogramação em Python: Decorators e Metaclasses
ODP
Red Flags in Programming
PPTX
Understanding Prototypal Inheritance
Perl.Hacks.On.Vim Perlchina
ScotRuby - Dark side of ruby
Writing SOLID code (in practice)
Dsl
Reusando componentes Zope fuera de Zope
Making JavaScript Libraries More Approachable
Perl Xpath Lightning Talk
Getting Testy With Perl6
BASH Variables Part 1: Basic Interpolation
The $path to knowledge: What little it take to unit-test Perl.
The bones of a nice Python script
Descobrindo a linguagem Perl
Synapseindia reviews sharing intro on php
The Perl API for the Mortally Terrified (beta)
Cross platform php
Working with text, Regular expressions
Metaprogramação em Python: Decorators e Metaclasses
Red Flags in Programming
Understanding Prototypal Inheritance
Ad

Viewers also liked (20)

PDF
IPython from 30,000 feet
PDF
Effectively using Open Source with conda
PDF
Django mongodb -djangoday_
PDF
The Django Book, Chapter 16: django.contrib
PPT
Django-Queryset
PPTX
2016 py con2016_lightingtalk_php to python
KEY
Overview of Testing Talks at Pycon
PPT
Html5 History-API
PDF
The Django Book Chapter 9 - Django Workshop - Taipei.py
PDF
라이트닝 토크 2015 파이콘
PPTX
Super Advanced Python –act1
PDF
User-centered open source
ODP
Rabbitmq & Postgresql
PDF
Bottle - Python Web Microframework
PDF
Website optimization
PDF
PyClab.__init__(self)
PDF
2007 - 应用系统脆弱性概论
PDF
NoSql Day - Chiusura
PDF
Django - The Web framework for perfectionists with deadlines
ODP
Authentication & Authorization in ASPdotNet MVC
IPython from 30,000 feet
Effectively using Open Source with conda
Django mongodb -djangoday_
The Django Book, Chapter 16: django.contrib
Django-Queryset
2016 py con2016_lightingtalk_php to python
Overview of Testing Talks at Pycon
Html5 History-API
The Django Book Chapter 9 - Django Workshop - Taipei.py
라이트닝 토크 2015 파이콘
Super Advanced Python –act1
User-centered open source
Rabbitmq & Postgresql
Bottle - Python Web Microframework
Website optimization
PyClab.__init__(self)
2007 - 应用系统脆弱性概论
NoSql Day - Chiusura
Django - The Web framework for perfectionists with deadlines
Authentication & Authorization in ASPdotNet MVC
Ad

Similar to Code with style (20)

PDF
Zen and the Art of Python
PPTX
Code Like Pythonista
PDF
Brogramming - Python, Bash for Data Processing, and Git
PDF
Python于Web 2.0网站的应用 - QCon Beijing 2010
PDF
Intro to Python
PPTX
Php extensions
PDF
Write your Ruby in Style
PDF
Python fundamentals - basic | WeiYuan
PDF
Secure Programming Practices in C++ (NDC Oslo 2018)
PDF
20_Python_Libraries_You_Aren't_Using_But_Should.pdf
PPTX
Php extensions
PPTX
Php extensions
PDF
Python Tricks That You Can't Live Without
PDF
TYPO3 Extension development using new Extbase framework
PDF
Questioning the status quo
PPTX
Good practices for PrestaShop code security and optimization
PDF
Drupal 8: A story of growing up and getting off the island
PPTX
C# to python
PDF
Metadata-driven Testing
Zen and the Art of Python
Code Like Pythonista
Brogramming - Python, Bash for Data Processing, and Git
Python于Web 2.0网站的应用 - QCon Beijing 2010
Intro to Python
Php extensions
Write your Ruby in Style
Python fundamentals - basic | WeiYuan
Secure Programming Practices in C++ (NDC Oslo 2018)
20_Python_Libraries_You_Aren't_Using_But_Should.pdf
Php extensions
Php extensions
Python Tricks That You Can't Live Without
TYPO3 Extension development using new Extbase framework
Questioning the status quo
Good practices for PrestaShop code security and optimization
Drupal 8: A story of growing up and getting off the island
C# to python
Metadata-driven Testing

More from Clayton Parker (20)

PDF
Customizing Your Shell With Dotfiles
PDF
Vim for Mere Mortals
PDF
Fuzzy Feelings for Fuzzy Matching
PDF
Exploring Code with Pry!
PDF
So you think you can pdb?
PDF
Managing Chaos: Merging 120 Sites into a single Plone Multisite Solution
PDF
Current State of Python Packaging
PDF
Notre Dame Seamless Syndication with Lineage
PDF
Pioneer a Strategic Change in Content Organization with Plone
PDF
Using Buildout, GenericSetup and a Policy Package to Rule the World
PDF
Make Plone Search Act Like Google Using Solr
PDF
Migrating from drupal to plone with transmogrifier
PDF
Buildout for the Future
PDF
Buildout future
PDF
Laying Pipe with Transmogrifier
PDF
LDAP and Active Directory Authentication in Plone
PDF
Using Buildout to Develop and Deploy Python Projects
PDF
Generic Setup De-Mystified
PDF
Buildout: Fostering Repeatability
PDF
Getting Plone Ready For The Prom
Customizing Your Shell With Dotfiles
Vim for Mere Mortals
Fuzzy Feelings for Fuzzy Matching
Exploring Code with Pry!
So you think you can pdb?
Managing Chaos: Merging 120 Sites into a single Plone Multisite Solution
Current State of Python Packaging
Notre Dame Seamless Syndication with Lineage
Pioneer a Strategic Change in Content Organization with Plone
Using Buildout, GenericSetup and a Policy Package to Rule the World
Make Plone Search Act Like Google Using Solr
Migrating from drupal to plone with transmogrifier
Buildout for the Future
Buildout future
Laying Pipe with Transmogrifier
LDAP and Active Directory Authentication in Plone
Using Buildout to Develop and Deploy Python Projects
Generic Setup De-Mystified
Buildout: Fostering Repeatability
Getting Plone Ready For The Prom

Recently uploaded (20)

PPT
Teaching material agriculture food technology
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Modernizing your data center with Dell and AMD
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Encapsulation theory and applications.pdf
PPTX
Cloud computing and distributed systems.
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Machine learning based COVID-19 study performance prediction
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
cuic standard and advanced reporting.pdf
Teaching material agriculture food technology
Digital-Transformation-Roadmap-for-Companies.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Empathic Computing: Creating Shared Understanding
Dropbox Q2 2025 Financial Results & Investor Presentation
Understanding_Digital_Forensics_Presentation.pptx
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Modernizing your data center with Dell and AMD
The Rise and Fall of 3GPP – Time for a Sabbatical?
Encapsulation theory and applications.pdf
Cloud computing and distributed systems.
Mobile App Security Testing_ A Comprehensive Guide.pdf
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Machine learning based COVID-19 study performance prediction
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Encapsulation_ Review paper, used for researhc scholars
Chapter 3 Spatial Domain Image Processing.pdf
cuic standard and advanced reporting.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