http://www.skillbrew.com
/Skillbrew
Talent brewed by the industry itself
Coding Style & Pep 8
Pavan Verma
@YinYangPavan
Founder, P3 InfoTech Solutions Pvt. Ltd.
1
Python Programming Essentials
© SkillBrew http://skillbrew.com
Contents
 Code layout
 Indentation, tabs and spaces
 Imports
 Blank lines
 Whitespace in expressions and statements
 Pep8
2
© SkillBrew http://skillbrew.com
Readability counts
One of Guido's key
insights is that code is
read much more often
than it is written.
"Readability counts"
3
© SkillBrew http://skillbrew.com
Code Layout
 Indentation
 Tabs or spaces
 Maximum length lines
 Blank lines
 imports
4
© SkillBrew http://skillbrew.com
Indentation
def get(self, request,
post_id, comment_id):
pass
my_list = [
1, 2, 3,
4, 5, 6,
]
def get(self, request,
post_id, comment_id):
pass
my_list = [
1, 2, 3,
4, 5, 6,]
5
© SkillBrew http://skillbrew.com
Tabs or spaces
Spaces are the preferred indentation method
Maximum Line Length
Limit all lines to maximum 79 characters
6
© SkillBrew http://skillbrew.com
Blank lines
def get_index(val):
pass
def get_value(index):
pass
class DoSomething():
def __init__(self):
pass
def do(self):
pass
• Separate top-level function and
class definitions with two blank
lines
• Method definitions inside a
class are separated by a single
blank line
7
© SkillBrew http://skillbrew.com
imports
Imports should usually be
on separate lines
import os
import sys
import sys, os
8
© SkillBrew http://skillbrew.com
imports
Recommended
from testapp.views import CreateView
Not Recommended
from .views import CreateView
Absolute imports are
recommended
Better readability
myproject
views.py utils.py models.py
testapp
utils.py
9
© SkillBrew http://skillbrew.com
Blank lines
def get_index(val):
pass
def get_value(index):
pass
class DoSomething():
def __init__(self):
pass
def do(self):
pass
• Separate top-level function and
class definitions with two blank
lines
• Method definitions inside a
class are separated by a single
blank line
10
© SkillBrew http://skillbrew.com
Whitespace in Expressions and Statements
Avoid extra whitespaces in following situations
spam(ham[1], {eggs: 2})
spam( ham[ 1 ], { eggs: 2 } )
Immediately inside parentheses, brackets or
braces
11
© SkillBrew http://skillbrew.com
Whitespace in Expressions and Statements (2)
Avoid extra whitespaces in following situations
if x == 4: print x, y; x, y = y, x
if x == 4 : print x , y ; x , y = y , x
Immediately before a comma, semicolon, or
colon
12
© SkillBrew http://skillbrew.com
Whitespace in Expressions and Statements (3)
Avoid extra whitespaces in following situations
spam(1)
spam (1)
Immediately before the open parenthesis
that starts the argument list of a function
call
13
© SkillBrew http://skillbrew.com
Whitespace in Expressions and Statements (4)
Avoid extra whitespaces in following situations
dict['key'] = list[index]
dict ['key'] = list [index]
Immediately before the open parenthesis
that starts an indexing or slicing
14
© SkillBrew http://skillbrew.com
Whitespace in Expressions and Statements (5)
Avoid extra whitespaces in following situations
x = 1
long_variable = 3
x = 1
long_variable = 3
More than one space around an assignment
(or other) operator to align it with another
15
© SkillBrew http://skillbrew.com
Whitespace in Expressions and Statements (6)
Avoid extra whitespaces in following situations
def complex(real, imag=0.0):
return magic(r=real, i=imag)
def complex(real, imag = 0.0):
return magic(r = real, i = imag)
Don't use spaces around the = sign when used to
indicate a keyword argument or a default
parameter value
16
© SkillBrew http://skillbrew.com
Documentation Strings
17
PEP 257: The """ that ends a multiline
docstring should be on a line by itself
"""Return a foobang
Optional plotz says to frobnicate the bizbaz first.
"""
© SkillBrew http://skillbrew.com
Naming Conventions
18
Class names should normally use the CapWords
convention. Eg. MyClass
Function names should be lowercase, with words
separated by underscores as necessary to improve
readability. Eg. this_is_a_function()
Constants are usually defined on a module level and
written in all capital letters with underscores separating
words. Eg. DEFAULT_SENDER_EMAIL
© SkillBrew http://skillbrew.com
Naming Conventions (2)
19
Always use self for the first argument to instance
methods.
Always use cls for the first argument to class
methods.
Public attributes should have no leading underscores.
© SkillBrew http://skillbrew.com
Naming Conventions (3)
20
Since module names are mapped to file names,
and some file systems are case insensitive and
truncate long names, it is important that module
names be chosen to be fairly short and
lowercase.
© SkillBrew http://skillbrew.com
Leading Underscores
21
__double_leading_and_trailing_underscore__:
"magic" objects or attributes that live in user-controlled
namespaces. E.g. __init__, __import__ or __file__.
Never invent such names; only use them as
documented.
_single_leading_underscore: weak "internal
use" indicator. E.g. from M import * does not import
objects whose name starts with an underscore.
single_trailing_underscore_: used by
convention to avoid conflicts with Python keyword. Eg.
Tkinter.Toplevel(master, class_='ClassName')
© SkillBrew http://skillbrew.com
Recommended
Please go through the pep 8 style guide
http://www.python.org/dev/peps/pep-
0008/.
Use this as a reference whenever in doubt.
22
© SkillBrew http://skillbrew.com
pep8 - Python style guide checker
pep8 is a tool to check your Python code against
some of the style conventions in PEP 8
$ pip install pep8
$ pip install --upgrade pep8
23
© SkillBrew http://skillbrew.com
pep8
$ pep8 myprogram.py
24
© SkillBrew http://skillbrew.com
pep8 (2)
l = [((y,x), x+y) for x in range(4) for y in range(4)]
print l
f = [((x,x),x+x) for x in range(3) ]
print f
pep8 –-first list_comp.py
list_comp.py:1:9: E231 missing whitespace after
','
list_comp.py:5:5: E124 closing bracket does not
match visual indentation
list_comp.py:7:1: W391 blank line at end of file
25
© SkillBrew http://skillbrew.com
pep8 --show-source list_comp.py
list_comp.py:1:9: E231 missing whitespace after ','
l = [((y,x), x+y) for x in range(4) for y in range(4)]
^
list_comp.py:4:9: E231 missing whitespace after ','
f = [((x,x),x+x) for x in range(3)
^
list_comp.py:4:12: E231 missing whitespace after ','
f = [((x,x),x+x) for x in range(3)
^
list_comp.py:5:5: E124 closing bracket does not match
visual indentation
]
^
list_comp.py:7:1: W391 blank line at end of file
^
pep8 (3)
26
© SkillBrew http://skillbrew.com
Important pep8 options
Option Description
--first show first occurrence of each error
--show-source show source code for each error
--show-pep8 show text of PEP 8 for each error
(implies --first)
--statistics count errors and warnings
--exclude=patterns exclude files or directories which
match these comma separated
patterns (default:
.svn,CVS,.bzr,.hg,.git)
--filename=patterns when parsing directories, only check
filenames matching these comma
separated patterns (default: *.py)
--benchmark measure processing speed
27
© SkillBrew http://skillbrew.com
Recommended
To know more about pep8 options type in :
$ pep8 –h
OR
Read the docs
http://pep8.readthedocs.org/en/latest/intro.html
28
© SkillBrew http://skillbrew.com
References
 http://pep8.readthedocs.org/en/latest/in
tro.html
 https://pypi.python.org/pypi/pep8
 http://www.python.org/dev/peps/pep-
0008/
29

Python Programming Essentials - M31 - PEP 8

  • 1.
    http://www.skillbrew.com /Skillbrew Talent brewed bythe industry itself Coding Style & Pep 8 Pavan Verma @YinYangPavan Founder, P3 InfoTech Solutions Pvt. Ltd. 1 Python Programming Essentials
  • 2.
    © SkillBrew http://skillbrew.com Contents Code layout  Indentation, tabs and spaces  Imports  Blank lines  Whitespace in expressions and statements  Pep8 2
  • 3.
    © SkillBrew http://skillbrew.com Readabilitycounts One of Guido's key insights is that code is read much more often than it is written. "Readability counts" 3
  • 4.
    © SkillBrew http://skillbrew.com CodeLayout  Indentation  Tabs or spaces  Maximum length lines  Blank lines  imports 4
  • 5.
    © SkillBrew http://skillbrew.com Indentation defget(self, request, post_id, comment_id): pass my_list = [ 1, 2, 3, 4, 5, 6, ] def get(self, request, post_id, comment_id): pass my_list = [ 1, 2, 3, 4, 5, 6,] 5
  • 6.
    © SkillBrew http://skillbrew.com Tabsor spaces Spaces are the preferred indentation method Maximum Line Length Limit all lines to maximum 79 characters 6
  • 7.
    © SkillBrew http://skillbrew.com Blanklines def get_index(val): pass def get_value(index): pass class DoSomething(): def __init__(self): pass def do(self): pass • Separate top-level function and class definitions with two blank lines • Method definitions inside a class are separated by a single blank line 7
  • 8.
    © SkillBrew http://skillbrew.com imports Importsshould usually be on separate lines import os import sys import sys, os 8
  • 9.
    © SkillBrew http://skillbrew.com imports Recommended fromtestapp.views import CreateView Not Recommended from .views import CreateView Absolute imports are recommended Better readability myproject views.py utils.py models.py testapp utils.py 9
  • 10.
    © SkillBrew http://skillbrew.com Blanklines def get_index(val): pass def get_value(index): pass class DoSomething(): def __init__(self): pass def do(self): pass • Separate top-level function and class definitions with two blank lines • Method definitions inside a class are separated by a single blank line 10
  • 11.
    © SkillBrew http://skillbrew.com Whitespacein Expressions and Statements Avoid extra whitespaces in following situations spam(ham[1], {eggs: 2}) spam( ham[ 1 ], { eggs: 2 } ) Immediately inside parentheses, brackets or braces 11
  • 12.
    © SkillBrew http://skillbrew.com Whitespacein Expressions and Statements (2) Avoid extra whitespaces in following situations if x == 4: print x, y; x, y = y, x if x == 4 : print x , y ; x , y = y , x Immediately before a comma, semicolon, or colon 12
  • 13.
    © SkillBrew http://skillbrew.com Whitespacein Expressions and Statements (3) Avoid extra whitespaces in following situations spam(1) spam (1) Immediately before the open parenthesis that starts the argument list of a function call 13
  • 14.
    © SkillBrew http://skillbrew.com Whitespacein Expressions and Statements (4) Avoid extra whitespaces in following situations dict['key'] = list[index] dict ['key'] = list [index] Immediately before the open parenthesis that starts an indexing or slicing 14
  • 15.
    © SkillBrew http://skillbrew.com Whitespacein Expressions and Statements (5) Avoid extra whitespaces in following situations x = 1 long_variable = 3 x = 1 long_variable = 3 More than one space around an assignment (or other) operator to align it with another 15
  • 16.
    © SkillBrew http://skillbrew.com Whitespacein Expressions and Statements (6) Avoid extra whitespaces in following situations def complex(real, imag=0.0): return magic(r=real, i=imag) def complex(real, imag = 0.0): return magic(r = real, i = imag) Don't use spaces around the = sign when used to indicate a keyword argument or a default parameter value 16
  • 17.
    © SkillBrew http://skillbrew.com DocumentationStrings 17 PEP 257: The """ that ends a multiline docstring should be on a line by itself """Return a foobang Optional plotz says to frobnicate the bizbaz first. """
  • 18.
    © SkillBrew http://skillbrew.com NamingConventions 18 Class names should normally use the CapWords convention. Eg. MyClass Function names should be lowercase, with words separated by underscores as necessary to improve readability. Eg. this_is_a_function() Constants are usually defined on a module level and written in all capital letters with underscores separating words. Eg. DEFAULT_SENDER_EMAIL
  • 19.
    © SkillBrew http://skillbrew.com NamingConventions (2) 19 Always use self for the first argument to instance methods. Always use cls for the first argument to class methods. Public attributes should have no leading underscores.
  • 20.
    © SkillBrew http://skillbrew.com NamingConventions (3) 20 Since module names are mapped to file names, and some file systems are case insensitive and truncate long names, it is important that module names be chosen to be fairly short and lowercase.
  • 21.
    © SkillBrew http://skillbrew.com LeadingUnderscores 21 __double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented. _single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore. single_trailing_underscore_: used by convention to avoid conflicts with Python keyword. Eg. Tkinter.Toplevel(master, class_='ClassName')
  • 22.
    © SkillBrew http://skillbrew.com Recommended Pleasego through the pep 8 style guide http://www.python.org/dev/peps/pep- 0008/. Use this as a reference whenever in doubt. 22
  • 23.
    © SkillBrew http://skillbrew.com pep8- Python style guide checker pep8 is a tool to check your Python code against some of the style conventions in PEP 8 $ pip install pep8 $ pip install --upgrade pep8 23
  • 24.
  • 25.
    © SkillBrew http://skillbrew.com pep8(2) l = [((y,x), x+y) for x in range(4) for y in range(4)] print l f = [((x,x),x+x) for x in range(3) ] print f pep8 –-first list_comp.py list_comp.py:1:9: E231 missing whitespace after ',' list_comp.py:5:5: E124 closing bracket does not match visual indentation list_comp.py:7:1: W391 blank line at end of file 25
  • 26.
    © SkillBrew http://skillbrew.com pep8--show-source list_comp.py list_comp.py:1:9: E231 missing whitespace after ',' l = [((y,x), x+y) for x in range(4) for y in range(4)] ^ list_comp.py:4:9: E231 missing whitespace after ',' f = [((x,x),x+x) for x in range(3) ^ list_comp.py:4:12: E231 missing whitespace after ',' f = [((x,x),x+x) for x in range(3) ^ list_comp.py:5:5: E124 closing bracket does not match visual indentation ] ^ list_comp.py:7:1: W391 blank line at end of file ^ pep8 (3) 26
  • 27.
    © SkillBrew http://skillbrew.com Importantpep8 options Option Description --first show first occurrence of each error --show-source show source code for each error --show-pep8 show text of PEP 8 for each error (implies --first) --statistics count errors and warnings --exclude=patterns exclude files or directories which match these comma separated patterns (default: .svn,CVS,.bzr,.hg,.git) --filename=patterns when parsing directories, only check filenames matching these comma separated patterns (default: *.py) --benchmark measure processing speed 27
  • 28.
    © SkillBrew http://skillbrew.com Recommended Toknow more about pep8 options type in : $ pep8 –h OR Read the docs http://pep8.readthedocs.org/en/latest/intro.html 28
  • 29.
    © SkillBrew http://skillbrew.com References http://pep8.readthedocs.org/en/latest/in tro.html  https://pypi.python.org/pypi/pep8  http://www.python.org/dev/peps/pep- 0008/ 29