SlideShare a Scribd company logo
1 of 45
Download to read offline
Audrey Roy
                          audreyr@cartwheelweb.com
                         http://www.audreymroy.com
                                          @audreyr
PYCON PHILIPPINES 2012




PYTHON TRICKS THAT
YOU CAN’T LIVE
WITHOUT
ABOUT ME

• Principal at Cartwheel Web
• Massachusetts Institute of
  Technology EECS    (winter 2005)


• Filipina-American and very
  proud to be here


                                     flickr.com/photos/chrisjrn/6102009780/
I ♥ PYTHON
• OpenComparison core dev, and contributor to
    various open-source projects

• Co-founded PyLadies
• Helped organize #pyconph
• Python Software Foundation member
•   I even met my fiancé Daniel Greenfeld at PyCon!
•   I even met my fiancé Daniel Greenfeld at PyCon!
•
                                                                                Audrey Roy
                                                                                 @audreyr

                         http://www.flickr.com/photos/47628826@N05/4374285165/
OVERVIEW


• Code readability
• Linters and code checkers
• Where to find free reusable Python libraries
• How to package your code for reuse

                                            Audrey Roy
                                             @audreyr
CODE READABILITY
The #1 trick to being a great Python developer is
      writing clear, understandable code.
CODE READABILITY


• The best Python code is compact, but not
  too compact

• Write self-documenting code
 • And document it anyway :)

                                         Audrey Roy
                                          @audreyr
CODE READABILITY
Can this be made cleaner?
def is_even(x):
    if x % 2 == 0:
        return True
    else:
        return False
CODE READABILITY
Can this be made even cleaner?
def is_even(x):
    if x % 2 == 0:
        return True
    return False
CODE READABILITY
That’s better, but what’s missing?
def is_even(x):
    return x % 2 == 0
CODE READABILITY
Don’t forget your docstrings
def is_even(x):
    """ Returns True if x is even, and
        False if x is odd. """

    return x % 2 == 0
ZEN OF PYTHON
Keep in mind Python’s philosophy as you code.

>>> 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.
...
PEP8


• Python style guide
 • 4 spaces. No tabs!
 • Blank lines between function & class defs
 • Much more...

                                          Audrey Roy
                                           @audreyr
TOOLS FOR CODE
  READABILITY
Kind of like spell check, but for code
SUBLIME TEXT 2 + PLUGINS
SublimeLinter

Highlights lines of
code that are not
PEP8-compliant.

Catches potential
style issues or errors.



(also for CSS, JS, PHP,
Ruby, etc.)
SUBLIME TEXT 2 + PLUGINS

  By the way, Sublime Text 2 plugins are
  simple Python files



  To write a plugin, you put a Python file in
  Sublime’s “Packages” directory
PEP8.PY
         A command-line PEP8 checker.


$ pep8 test2.py
test2.py:13:1: E302 expected 2 blank lines, found 1
test2.py:20:1: W391 blank line at end of file




               http://pypi.python.org/pypi/pep8
PYLINT
        Advanced Python source code analyzer.
$ pylint test2.py
No config file found, using default configuration
************* Module test2
C: 1,0: Missing docstring
F: 1,0: Unable to import 'django.db.models'
C: 3,0: Invalid name "compa2lookup" (should match (([A-Z_][A-
Z0-9_]*)|(__.*__))$)
C: 13,0:p_expression_ID: Invalid name "p_expression_ID" (should
match [a-z_][a-z0-9_]{2,30}$)
C: 13,0:p_expression_ID: Invalid name "p" (should match [a-z_][a-
z0-9_]{2,30}$)
C: 13,20:p_expression_ID: Invalid name "p" (should match [a-z_][a-
z0-9_]{2,30}$)
C: 18,4:p_expression_ID: Invalid name "d" (should match [a-z_][a-
z0-9_]{2,30}$)
W: 19,11:p_expression_ID: Used * or ** magic


                   http://pypi.python.org/pypi/pylint
PYLINT
        Advanced Python source code analyzer.
Report
======
8 statements analysed.

Messages by category
--------------------
+-----------+-------+---------+-----------+
|type       |number |previous |difference |
+===========+=======+=========+===========+
|convention |6       |NC      |NC         |
+-----------+-------+---------+-----------+
|refactor   |0       |NC      |NC         |
+-----------+-------+---------+-----------+
|warning    |1       |NC      |NC         |
+-----------+-------+---------+-----------+

                   http://pypi.python.org/pypi/pylint
FINDING PYTHON
    LIBRARIES
 “Free stuff for Python developers!”
FINDING CODE TO REUSE
Where to get FREE reusable Python libraries:
  1. Python Standard Library
   •   Many great essentials, already on your system!

   •   http://docs.python.org/library/index.html

  2. Python Package Index
   •   21,000+ packages to download!

   •   http://pypi.python.org/


                                                   Audrey Roy
                                                    @audreyr
WHY REUSE CODE?



• Python helps you avoid reinventing the
  wheel

 • “Not Invented Here” syndrome

                                           Audrey Roy
                                            @audreyr
MORE ABOUT THE
    PYTHON STDLIB

A collection of highly useful modules

• No need to install
• Just import and start using them!


                                        Audrey Roy
                                         @audreyr
STDLIB EXAMPLE: MATH
>>> import math
>>> math.ceil(2.03)
3.0
>>> math.floor(2.99)
2.0
>>> math.log(32,2)
5.0
>>> math.erf(0.5)
0.5204998778130465



Mathematical functions defined by the C standard
STDLIB EXAMPLE: RANDOM
>>> import random
>>> random.random()
0.12863367604888531
>>> random.uniform(0,100)
25.374019279313988
>>> math.floor(random.uniform(0,100))
77.0
>>> random.randrange(0,100)
69
MORE ABOUT PYPI


• PyPI is “Python Package Index”
• 21,000+ packages
 • All created by community members like you
• http://pypi.python.org

                                        Audrey Roy
                                         @audreyr
PYPI EXAMPLES


• You saw some great examples already
  from PyPI (Python Package Index)

 • pep8: Simple PEP8 syntax checker
 • pylint: Advanced source code analyzer

                                           Audrey Roy
                                            @audreyr
STDLIB VS. PYPI


• The stdlib is conservative
 • Few additions/changes/deprecations
• On PyPI, anything goes!

                                        Audrey Roy
                                         @audreyr
STDLIB VS. PYPI


• Sometimes PyPI packages are better than
  the equivalent stdlib ones

 • e.g. requests is better than urllib2
• If in doubt, ask around

                                          Audrey Roy
                                           @audreyr
INSTALLING
PYTHON PACKAGES
  The wrong way, and the right way
THE WRONG WAY



• Systemwide installation of Python
  libraries is generally bad

• You can make a mess of your system
                                       Audrey Roy
                                        @audreyr
THE RIGHT WAY

You really should be using these 2 tools:

• pip - a good package installer
• virtualenv - create isolated Python envs

I strongly recommend virtualenvwrapper too.


                                            Audrey Roy
                                             @audreyr
THE RIGHT WAY:
          VIRTUALENV
Create isolated virtualenvs for different projects.

$ workon consumer_io
(consumer_io) $ cd consumer_io/proj/
(consumer_io) $ python manage.py runserver
(consumer_io) $ ...
(consumer_io) $ deactivate
$ cd ../../experiments
$ workon experiments
(experiments) $ python somethingelse.py
(experiments) $ ...
THE RIGHT WAY: PIP

Use pip to install packages into virtualenvs.

(experiments) $ pip install Django==1.4




pip is like easy_install, but much better.
THE RIGHT WAY:
        PIP+VIRTUALENV
SCENARIO:
You use Django 1.3 for work, but you want to
experiment with Django 1.4.

With pip and virtualenv, you can switch between
1.3 and 1.4 on the same computer.
PIP REQUIREMENTS FILES
You should pin your dependencies in requirements.txt!
 $ pip install -r requirements.txt

 # Your requirements.txt file
 Flask==0.8
 glue==0.2.5
 Pillow==1.7.7
 Django==1.4


Use pip install PackageName==1.0.4 for
experimentation only.
AFTER INSTALLATION?
Once installed, you can import Python code
from modules:
from collections import deque


Or from submodules:
from os.path import abspath
WRITING REUSABLE
     CODE
  How code reuse works in Python
MODULES
A module is a file containing Python
definitions and statements.

Like this:

# divisible.py

def is_even(x):
    """ Returns True if x is even, and
        False if x is odd. """

    return x % 2 == 0
PACKAGES
A Python package is a collection of modules.
sound/
    __init__.py
    formats/
        __init__.py
        wav.py
        aiff.py
    effects/
        __init__.py
        echo.py
        surround.py
PACKAGES
A sample import from this package:
from sound.formats.wav import read_wav


sound/
    __init__.py
    formats/
        __init__.py
        wav.py
        aiff.py
    effects/
        __init__.py
        echo.py
        surround.py
INTRA-PACKAGE IMPORTS
Relative imports work between submodules of
a package:
from . import echo
from .. import formats
from ..filters import equalizer
INTRA-PACKAGE IMPORTS
Absolute imports work between submodules of
a package:
# Use this from anywhere in the package
from sound.effects import echo
          package root
IMPORTING FROM
    OUTSIDE A PACKAGE
• Can’t use absolute/relative imports
• What to do? One of these:
   • Good: Add the package to PYTHONPATH
     [edit env var or use sys.path.append()]

   • Better: Install the package into your active
     virtualenv.

                                               Audrey Roy
                                                @audreyr
BETTER PACKAGING

• Recommended reading: “The Hitchhiker’s
  Guide To Packaging”

 • http://guide.python-distribute.org
 • Learn to make packages that are
    downloadable & installable from PyPI


                                           Audrey Roy
                                            @audreyr
THANK YOU


• Find me if you have questions
• Introduce yourself - I’d love to meet you!
• Twitter: @audreyr
• Email: audreyr@cartwheelweb.com

                                           Audrey Roy
                                            @audreyr

More Related Content

What's hot

Python course syllabus
Python course syllabusPython course syllabus
Python course syllabusSugantha T
 
Chap1V2019: Cours en C++
Chap1V2019: Cours en C++Chap1V2019: Cours en C++
Chap1V2019: Cours en C++Aziz Darouichi
 
Cours : les listes chainées Prof. KHALIFA MANSOURI
Cours : les listes chainées  Prof. KHALIFA MANSOURI Cours : les listes chainées  Prof. KHALIFA MANSOURI
Cours : les listes chainées Prof. KHALIFA MANSOURI Mansouri Khalifa
 
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014Scott Wlaschin
 
Python NumPy Tutorial | NumPy Array | Edureka
Python NumPy Tutorial | NumPy Array | EdurekaPython NumPy Tutorial | NumPy Array | Edureka
Python NumPy Tutorial | NumPy Array | EdurekaEdureka!
 
FormationPython2019.pptx
FormationPython2019.pptxFormationPython2019.pptx
FormationPython2019.pptxLamissGhoul1
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and PackagesDamian T. Gordon
 
Introduction à Python - Achraf Kacimi El Hassani
Introduction à Python - Achraf Kacimi El HassaniIntroduction à Python - Achraf Kacimi El Hassani
Introduction à Python - Achraf Kacimi El HassaniShellmates
 
Basic data types in python
Basic data types in pythonBasic data types in python
Basic data types in pythonsunilchute1
 
組み込みでこそC++を使う10の理由
組み込みでこそC++を使う10の理由組み込みでこそC++を使う10の理由
組み込みでこそC++を使う10の理由kikairoya
 
Python
PythonPython
PythonTiago
 
Python for Delphi Developers - Part 1 Introduction
Python for Delphi Developers - Part 1 IntroductionPython for Delphi Developers - Part 1 Introduction
Python for Delphi Developers - Part 1 IntroductionEmbarcadero Technologies
 

What's hot (20)

Python course syllabus
Python course syllabusPython course syllabus
Python course syllabus
 
Chap1V2019: Cours en C++
Chap1V2019: Cours en C++Chap1V2019: Cours en C++
Chap1V2019: Cours en C++
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
Cours : les listes chainées Prof. KHALIFA MANSOURI
Cours : les listes chainées  Prof. KHALIFA MANSOURI Cours : les listes chainées  Prof. KHALIFA MANSOURI
Cours : les listes chainées Prof. KHALIFA MANSOURI
 
Pandas
PandasPandas
Pandas
 
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
 
Python NumPy Tutorial | NumPy Array | Edureka
Python NumPy Tutorial | NumPy Array | EdurekaPython NumPy Tutorial | NumPy Array | Edureka
Python NumPy Tutorial | NumPy Array | Edureka
 
FormationPython2019.pptx
FormationPython2019.pptxFormationPython2019.pptx
FormationPython2019.pptx
 
Introduction to numpy
Introduction to numpyIntroduction to numpy
Introduction to numpy
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
Introduction à Python - Achraf Kacimi El Hassani
Introduction à Python - Achraf Kacimi El HassaniIntroduction à Python - Achraf Kacimi El Hassani
Introduction à Python - Achraf Kacimi El Hassani
 
Effective Modern C++
Effective Modern C++Effective Modern C++
Effective Modern C++
 
Basic data types in python
Basic data types in pythonBasic data types in python
Basic data types in python
 
組み込みでこそC++を使う10の理由
組み込みでこそC++を使う10の理由組み込みでこそC++を使う10の理由
組み込みでこそC++を使う10の理由
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Python
PythonPython
Python
 
Python for Delphi Developers - Part 1 Introduction
Python for Delphi Developers - Part 1 IntroductionPython for Delphi Developers - Part 1 Introduction
Python for Delphi Developers - Part 1 Introduction
 
Klee and angr
Klee and angrKlee and angr
Klee and angr
 
Cours pointeurs
Cours pointeursCours pointeurs
Cours pointeurs
 
Python
PythonPython
Python
 

Viewers also liked

Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in PythonSujith Kumar
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonSujith Kumar
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python amiable_indian
 
Python的50道陰影
Python的50道陰影Python的50道陰影
Python的50道陰影Tim (文昌)
 
連淡水阿嬤都聽得懂的 機器學習入門 scikit-learn
連淡水阿嬤都聽得懂的機器學習入門 scikit-learn 連淡水阿嬤都聽得懂的機器學習入門 scikit-learn
連淡水阿嬤都聽得懂的 機器學習入門 scikit-learn Cicilia Lee
 
常用內建模組
常用內建模組常用內建模組
常用內建模組Justin Lin
 
型態與運算子
型態與運算子型態與運算子
型態與運算子Justin Lin
 
Python 起步走
Python 起步走Python 起步走
Python 起步走Justin Lin
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesMatt Harrison
 
[系列活動] Python 程式語言起步走
[系列活動] Python 程式語言起步走[系列活動] Python 程式語言起步走
[系列活動] Python 程式語言起步走台灣資料科學年會
 
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹台灣資料科學年會
 

Viewers also liked (15)

Python 2-基本語法
Python 2-基本語法Python 2-基本語法
Python 2-基本語法
 
Python 2 vs. Python 3
Python 2 vs. Python 3Python 2 vs. Python 3
Python 2 vs. Python 3
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Python的50道陰影
Python的50道陰影Python的50道陰影
Python的50道陰影
 
連淡水阿嬤都聽得懂的 機器學習入門 scikit-learn
連淡水阿嬤都聽得懂的機器學習入門 scikit-learn 連淡水阿嬤都聽得懂的機器學習入門 scikit-learn
連淡水阿嬤都聽得懂的 機器學習入門 scikit-learn
 
常用內建模組
常用內建模組常用內建模組
常用內建模組
 
型態與運算子
型態與運算子型態與運算子
型態與運算子
 
進階主題
進階主題進階主題
進階主題
 
Python 起步走
Python 起步走Python 起步走
Python 起步走
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
[系列活動] Python 程式語言起步走
[系列活動] Python 程式語言起步走[系列活動] Python 程式語言起步走
[系列活動] Python 程式語言起步走
 
[系列活動] Python爬蟲實戰
[系列活動] Python爬蟲實戰[系列活動] Python爬蟲實戰
[系列活動] Python爬蟲實戰
 
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
 

Similar to Python Tricks That You Can't Live Without

PyCourse - Self driving python course
PyCourse - Self driving python coursePyCourse - Self driving python course
PyCourse - Self driving python courseEran Shlomo
 
Intro to Python for C# Developers
Intro to Python for C# DevelopersIntro to Python for C# Developers
Intro to Python for C# DevelopersSarah Dutkiewicz
 
Python testing like a pro by Keith Yang
Python testing like a pro by Keith YangPython testing like a pro by Keith Yang
Python testing like a pro by Keith YangPYCON MY PLT
 
Clean Manifests with Puppet::Tidy
Clean Manifests with Puppet::TidyClean Manifests with Puppet::Tidy
Clean Manifests with Puppet::TidyPuppet
 
Code with Style - PyOhio
Code with Style - PyOhioCode with Style - PyOhio
Code with Style - PyOhioClayton Parker
 
Python Programming1.ppt
Python Programming1.pptPython Programming1.ppt
Python Programming1.pptRehnawilson1
 
Puppet Camp Sydney 2015: The (Im)perfect Puppet Module
Puppet Camp Sydney 2015: The (Im)perfect Puppet ModulePuppet Camp Sydney 2015: The (Im)perfect Puppet Module
Puppet Camp Sydney 2015: The (Im)perfect Puppet ModulePuppet
 
Packaging perl (LPW2010)
Packaging perl (LPW2010)Packaging perl (LPW2010)
Packaging perl (LPW2010)p3castro
 
How to Write a Popular Python Library by Accident
How to Write a Popular Python Library by AccidentHow to Write a Popular Python Library by Accident
How to Write a Popular Python Library by AccidentDaniel Greenfeld
 
Package manages and Puppet - PuppetConf 2015
Package manages and Puppet - PuppetConf 2015Package manages and Puppet - PuppetConf 2015
Package manages and Puppet - PuppetConf 2015ice799
 
Dave Anderson of Ammeon at PuppetCamp Dublin '12
Dave Anderson of Ammeon at PuppetCamp Dublin '12Dave Anderson of Ammeon at PuppetCamp Dublin '12
Dave Anderson of Ammeon at PuppetCamp Dublin '12Puppet
 
The Python Book_ The ultimate guide to coding with Python ( PDFDrive ).pdf
The Python Book_ The ultimate guide to coding with Python ( PDFDrive ).pdfThe Python Book_ The ultimate guide to coding with Python ( PDFDrive ).pdf
The Python Book_ The ultimate guide to coding with Python ( PDFDrive ).pdfssuser8b3cdd
 
Python on a chip
Python on a chipPython on a chip
Python on a chipstoggi
 
200,000 Lines Later: Our Journey to Manageable Puppet Code
200,000 Lines Later: Our Journey to Manageable Puppet Code200,000 Lines Later: Our Journey to Manageable Puppet Code
200,000 Lines Later: Our Journey to Manageable Puppet CodeDavid Danzilio
 
code review, style guides and tools for pythin
code review, style guides and tools for pythincode review, style guides and tools for pythin
code review, style guides and tools for pythinuniversité d'el jadida
 

Similar to Python Tricks That You Can't Live Without (20)

PyCourse - Self driving python course
PyCourse - Self driving python coursePyCourse - Self driving python course
PyCourse - Self driving python course
 
Intro to Python for C# Developers
Intro to Python for C# DevelopersIntro to Python for C# Developers
Intro to Python for C# Developers
 
Python testing like a pro by Keith Yang
Python testing like a pro by Keith YangPython testing like a pro by Keith Yang
Python testing like a pro by Keith Yang
 
Intro
IntroIntro
Intro
 
Python+gradle
Python+gradlePython+gradle
Python+gradle
 
Clean Manifests with Puppet::Tidy
Clean Manifests with Puppet::TidyClean Manifests with Puppet::Tidy
Clean Manifests with Puppet::Tidy
 
Code with Style - PyOhio
Code with Style - PyOhioCode with Style - PyOhio
Code with Style - PyOhio
 
Python Programming1.ppt
Python Programming1.pptPython Programming1.ppt
Python Programming1.ppt
 
Code with style
Code with styleCode with style
Code with style
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Puppet Camp Sydney 2015: The (Im)perfect Puppet Module
Puppet Camp Sydney 2015: The (Im)perfect Puppet ModulePuppet Camp Sydney 2015: The (Im)perfect Puppet Module
Puppet Camp Sydney 2015: The (Im)perfect Puppet Module
 
Packaging perl (LPW2010)
Packaging perl (LPW2010)Packaging perl (LPW2010)
Packaging perl (LPW2010)
 
How to Write a Popular Python Library by Accident
How to Write a Popular Python Library by AccidentHow to Write a Popular Python Library by Accident
How to Write a Popular Python Library by Accident
 
Package manages and Puppet - PuppetConf 2015
Package manages and Puppet - PuppetConf 2015Package manages and Puppet - PuppetConf 2015
Package manages and Puppet - PuppetConf 2015
 
Dave Anderson of Ammeon at PuppetCamp Dublin '12
Dave Anderson of Ammeon at PuppetCamp Dublin '12Dave Anderson of Ammeon at PuppetCamp Dublin '12
Dave Anderson of Ammeon at PuppetCamp Dublin '12
 
The Python Book_ The ultimate guide to coding with Python ( PDFDrive ).pdf
The Python Book_ The ultimate guide to coding with Python ( PDFDrive ).pdfThe Python Book_ The ultimate guide to coding with Python ( PDFDrive ).pdf
The Python Book_ The ultimate guide to coding with Python ( PDFDrive ).pdf
 
Python on a chip
Python on a chipPython on a chip
Python on a chip
 
200,000 Lines Later: Our Journey to Manageable Puppet Code
200,000 Lines Later: Our Journey to Manageable Puppet Code200,000 Lines Later: Our Journey to Manageable Puppet Code
200,000 Lines Later: Our Journey to Manageable Puppet Code
 
code review, style guides and tools for pythin
code review, style guides and tools for pythincode review, style guides and tools for pythin
code review, style guides and tools for pythin
 
05 python.pdf
05 python.pdf05 python.pdf
05 python.pdf
 

Recently uploaded

Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessWSO2
 
Deliver Latency Free Customer Experience
Deliver Latency Free Customer ExperienceDeliver Latency Free Customer Experience
Deliver Latency Free Customer ExperienceOpsTree solutions
 
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
 
WomenInAutomation2024: AI and Automation for eveyone
WomenInAutomation2024: AI and Automation for eveyoneWomenInAutomation2024: AI and Automation for eveyone
WomenInAutomation2024: AI and Automation for eveyoneUiPathCommunity
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
Which standard is best for your content?
Which standard is best for your content?Which standard is best for your content?
Which standard is best for your content?Rustici Software
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Jeffrey Haguewood
 
Bitdefender-CSG-Report-creat7534-interactive
Bitdefender-CSG-Report-creat7534-interactiveBitdefender-CSG-Report-creat7534-interactive
Bitdefender-CSG-Report-creat7534-interactivestartupro
 
Transcript: Green paths: Learning from publishers’ sustainability journeys - ...
Transcript: Green paths: Learning from publishers’ sustainability journeys - ...Transcript: Green paths: Learning from publishers’ sustainability journeys - ...
Transcript: Green paths: Learning from publishers’ sustainability journeys - ...BookNet Canada
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
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
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Women in Automation 2024: Career session - explore career paths in automation
Women in Automation 2024: Career session - explore career paths in automationWomen in Automation 2024: Career session - explore career paths in automation
Women in Automation 2024: Career session - explore career paths in automationDianaGray10
 
A PowerPoint Presentation on Vikram Lander pptx
A PowerPoint Presentation on Vikram Lander pptxA PowerPoint Presentation on Vikram Lander pptx
A PowerPoint Presentation on Vikram Lander pptxatharvdev2010
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024BookNet Canada
 
Laying the Data Foundations for Artificial Intelligence!
Laying the Data Foundations for Artificial Intelligence!Laying the Data Foundations for Artificial Intelligence!
Laying the Data Foundations for Artificial Intelligence!Memoori
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...amber724300
 
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
 
Software Security in the Real World w/Kelsey Hightower
Software Security in the Real World w/Kelsey HightowerSoftware Security in the Real World w/Kelsey Hightower
Software Security in the Real World w/Kelsey HightowerAnchore
 

Recently uploaded (20)

Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with Platformless
 
Deliver Latency Free Customer Experience
Deliver Latency Free Customer ExperienceDeliver Latency Free Customer Experience
Deliver Latency Free Customer Experience
 
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
 
WomenInAutomation2024: AI and Automation for eveyone
WomenInAutomation2024: AI and Automation for eveyoneWomenInAutomation2024: AI and Automation for eveyone
WomenInAutomation2024: AI and Automation for eveyone
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
Which standard is best for your content?
Which standard is best for your content?Which standard is best for your content?
Which standard is best for your content?
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
 
Bitdefender-CSG-Report-creat7534-interactive
Bitdefender-CSG-Report-creat7534-interactiveBitdefender-CSG-Report-creat7534-interactive
Bitdefender-CSG-Report-creat7534-interactive
 
Transcript: Green paths: Learning from publishers’ sustainability journeys - ...
Transcript: Green paths: Learning from publishers’ sustainability journeys - ...Transcript: Green paths: Learning from publishers’ sustainability journeys - ...
Transcript: Green paths: Learning from publishers’ sustainability journeys - ...
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
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
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Women in Automation 2024: Career session - explore career paths in automation
Women in Automation 2024: Career session - explore career paths in automationWomen in Automation 2024: Career session - explore career paths in automation
Women in Automation 2024: Career session - explore career paths in automation
 
A PowerPoint Presentation on Vikram Lander pptx
A PowerPoint Presentation on Vikram Lander pptxA PowerPoint Presentation on Vikram Lander pptx
A PowerPoint Presentation on Vikram Lander pptx
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024
Green paths: Learning from publishers’ sustainability journeys - Tech Forum 2024
 
Laying the Data Foundations for Artificial Intelligence!
Laying the Data Foundations for Artificial Intelligence!Laying the Data Foundations for Artificial Intelligence!
Laying the Data Foundations for Artificial Intelligence!
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
 
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
 
Software Security in the Real World w/Kelsey Hightower
Software Security in the Real World w/Kelsey HightowerSoftware Security in the Real World w/Kelsey Hightower
Software Security in the Real World w/Kelsey Hightower
 

Python Tricks That You Can't Live Without

  • 1. Audrey Roy audreyr@cartwheelweb.com http://www.audreymroy.com @audreyr PYCON PHILIPPINES 2012 PYTHON TRICKS THAT YOU CAN’T LIVE WITHOUT
  • 2. ABOUT ME • Principal at Cartwheel Web • Massachusetts Institute of Technology EECS (winter 2005) • Filipina-American and very proud to be here flickr.com/photos/chrisjrn/6102009780/
  • 3. I ♥ PYTHON • OpenComparison core dev, and contributor to various open-source projects • Co-founded PyLadies • Helped organize #pyconph • Python Software Foundation member • I even met my fiancé Daniel Greenfeld at PyCon! • I even met my fiancé Daniel Greenfeld at PyCon! • Audrey Roy @audreyr http://www.flickr.com/photos/47628826@N05/4374285165/
  • 4. OVERVIEW • Code readability • Linters and code checkers • Where to find free reusable Python libraries • How to package your code for reuse Audrey Roy @audreyr
  • 5. CODE READABILITY The #1 trick to being a great Python developer is writing clear, understandable code.
  • 6. CODE READABILITY • The best Python code is compact, but not too compact • Write self-documenting code • And document it anyway :) Audrey Roy @audreyr
  • 7. CODE READABILITY Can this be made cleaner? def is_even(x): if x % 2 == 0: return True else: return False
  • 8. CODE READABILITY Can this be made even cleaner? def is_even(x): if x % 2 == 0: return True return False
  • 9. CODE READABILITY That’s better, but what’s missing? def is_even(x): return x % 2 == 0
  • 10. CODE READABILITY Don’t forget your docstrings def is_even(x): """ Returns True if x is even, and False if x is odd. """ return x % 2 == 0
  • 11. ZEN OF PYTHON Keep in mind Python’s philosophy as you code. >>> 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. ...
  • 12. PEP8 • Python style guide • 4 spaces. No tabs! • Blank lines between function & class defs • Much more... Audrey Roy @audreyr
  • 13. TOOLS FOR CODE READABILITY Kind of like spell check, but for code
  • 14. SUBLIME TEXT 2 + PLUGINS SublimeLinter Highlights lines of code that are not PEP8-compliant. Catches potential style issues or errors. (also for CSS, JS, PHP, Ruby, etc.)
  • 15. SUBLIME TEXT 2 + PLUGINS By the way, Sublime Text 2 plugins are simple Python files To write a plugin, you put a Python file in Sublime’s “Packages” directory
  • 16. PEP8.PY A command-line PEP8 checker. $ pep8 test2.py test2.py:13:1: E302 expected 2 blank lines, found 1 test2.py:20:1: W391 blank line at end of file http://pypi.python.org/pypi/pep8
  • 17. PYLINT Advanced Python source code analyzer. $ pylint test2.py No config file found, using default configuration ************* Module test2 C: 1,0: Missing docstring F: 1,0: Unable to import 'django.db.models' C: 3,0: Invalid name "compa2lookup" (should match (([A-Z_][A- Z0-9_]*)|(__.*__))$) C: 13,0:p_expression_ID: Invalid name "p_expression_ID" (should match [a-z_][a-z0-9_]{2,30}$) C: 13,0:p_expression_ID: Invalid name "p" (should match [a-z_][a- z0-9_]{2,30}$) C: 13,20:p_expression_ID: Invalid name "p" (should match [a-z_][a- z0-9_]{2,30}$) C: 18,4:p_expression_ID: Invalid name "d" (should match [a-z_][a- z0-9_]{2,30}$) W: 19,11:p_expression_ID: Used * or ** magic http://pypi.python.org/pypi/pylint
  • 18. PYLINT Advanced Python source code analyzer. Report ====== 8 statements analysed. Messages by category -------------------- +-----------+-------+---------+-----------+ |type |number |previous |difference | +===========+=======+=========+===========+ |convention |6 |NC |NC | +-----------+-------+---------+-----------+ |refactor |0 |NC |NC | +-----------+-------+---------+-----------+ |warning |1 |NC |NC | +-----------+-------+---------+-----------+ http://pypi.python.org/pypi/pylint
  • 19. FINDING PYTHON LIBRARIES “Free stuff for Python developers!”
  • 20. FINDING CODE TO REUSE Where to get FREE reusable Python libraries: 1. Python Standard Library • Many great essentials, already on your system! • http://docs.python.org/library/index.html 2. Python Package Index • 21,000+ packages to download! • http://pypi.python.org/ Audrey Roy @audreyr
  • 21. WHY REUSE CODE? • Python helps you avoid reinventing the wheel • “Not Invented Here” syndrome Audrey Roy @audreyr
  • 22. MORE ABOUT THE PYTHON STDLIB A collection of highly useful modules • No need to install • Just import and start using them! Audrey Roy @audreyr
  • 23. STDLIB EXAMPLE: MATH >>> import math >>> math.ceil(2.03) 3.0 >>> math.floor(2.99) 2.0 >>> math.log(32,2) 5.0 >>> math.erf(0.5) 0.5204998778130465 Mathematical functions defined by the C standard
  • 24. STDLIB EXAMPLE: RANDOM >>> import random >>> random.random() 0.12863367604888531 >>> random.uniform(0,100) 25.374019279313988 >>> math.floor(random.uniform(0,100)) 77.0 >>> random.randrange(0,100) 69
  • 25. MORE ABOUT PYPI • PyPI is “Python Package Index” • 21,000+ packages • All created by community members like you • http://pypi.python.org Audrey Roy @audreyr
  • 26. PYPI EXAMPLES • You saw some great examples already from PyPI (Python Package Index) • pep8: Simple PEP8 syntax checker • pylint: Advanced source code analyzer Audrey Roy @audreyr
  • 27. STDLIB VS. PYPI • The stdlib is conservative • Few additions/changes/deprecations • On PyPI, anything goes! Audrey Roy @audreyr
  • 28. STDLIB VS. PYPI • Sometimes PyPI packages are better than the equivalent stdlib ones • e.g. requests is better than urllib2 • If in doubt, ask around Audrey Roy @audreyr
  • 29. INSTALLING PYTHON PACKAGES The wrong way, and the right way
  • 30. THE WRONG WAY • Systemwide installation of Python libraries is generally bad • You can make a mess of your system Audrey Roy @audreyr
  • 31. THE RIGHT WAY You really should be using these 2 tools: • pip - a good package installer • virtualenv - create isolated Python envs I strongly recommend virtualenvwrapper too. Audrey Roy @audreyr
  • 32. THE RIGHT WAY: VIRTUALENV Create isolated virtualenvs for different projects. $ workon consumer_io (consumer_io) $ cd consumer_io/proj/ (consumer_io) $ python manage.py runserver (consumer_io) $ ... (consumer_io) $ deactivate $ cd ../../experiments $ workon experiments (experiments) $ python somethingelse.py (experiments) $ ...
  • 33. THE RIGHT WAY: PIP Use pip to install packages into virtualenvs. (experiments) $ pip install Django==1.4 pip is like easy_install, but much better.
  • 34. THE RIGHT WAY: PIP+VIRTUALENV SCENARIO: You use Django 1.3 for work, but you want to experiment with Django 1.4. With pip and virtualenv, you can switch between 1.3 and 1.4 on the same computer.
  • 35. PIP REQUIREMENTS FILES You should pin your dependencies in requirements.txt! $ pip install -r requirements.txt # Your requirements.txt file Flask==0.8 glue==0.2.5 Pillow==1.7.7 Django==1.4 Use pip install PackageName==1.0.4 for experimentation only.
  • 36. AFTER INSTALLATION? Once installed, you can import Python code from modules: from collections import deque Or from submodules: from os.path import abspath
  • 37. WRITING REUSABLE CODE How code reuse works in Python
  • 38. MODULES A module is a file containing Python definitions and statements. Like this: # divisible.py def is_even(x): """ Returns True if x is even, and False if x is odd. """ return x % 2 == 0
  • 39. PACKAGES A Python package is a collection of modules. sound/ __init__.py formats/ __init__.py wav.py aiff.py effects/ __init__.py echo.py surround.py
  • 40. PACKAGES A sample import from this package: from sound.formats.wav import read_wav sound/ __init__.py formats/ __init__.py wav.py aiff.py effects/ __init__.py echo.py surround.py
  • 41. INTRA-PACKAGE IMPORTS Relative imports work between submodules of a package: from . import echo from .. import formats from ..filters import equalizer
  • 42. INTRA-PACKAGE IMPORTS Absolute imports work between submodules of a package: # Use this from anywhere in the package from sound.effects import echo package root
  • 43. IMPORTING FROM OUTSIDE A PACKAGE • Can’t use absolute/relative imports • What to do? One of these: • Good: Add the package to PYTHONPATH [edit env var or use sys.path.append()] • Better: Install the package into your active virtualenv. Audrey Roy @audreyr
  • 44. BETTER PACKAGING • Recommended reading: “The Hitchhiker’s Guide To Packaging” • http://guide.python-distribute.org • Learn to make packages that are downloadable & installable from PyPI Audrey Roy @audreyr
  • 45. THANK YOU • Find me if you have questions • Introduce yourself - I’d love to meet you! • Twitter: @audreyr • Email: audreyr@cartwheelweb.com Audrey Roy @audreyr

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. The stdlib comes installed by default. Either with your system Python or with the version of Python that you installed manually.\n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n
  77. \n
  78. \n
  79. \n
  80. \n
  81. \n
  82. \n
  83. \n
  84. \n
  85. \n
  86. \n
  87. \n
  88. \n
  89. \n
  90. \n
  91. \n
  92. \n
  93. \n
  94. \n
  95. \n
  96. \n
  97. \n
  98. \n
  99. \n
  100. \n
  101. \n
  102. \n
  103. \n
  104. \n
  105. \n
  106. \n
  107. \n
  108. \n
  109. \n
  110. \n
  111. \n
  112. \n
  113. \n