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

More Related Content

What's hot (20)

Polymorphism
PolymorphismPolymorphism
Polymorphism
Ahmed Za'anin
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Edureka!
 
Python-Encapsulation.pptx
Python-Encapsulation.pptxPython-Encapsulation.pptx
Python-Encapsulation.pptx
Karudaiyar Ganapathy
 
Container Network Interface: Network Plugins for Kubernetes and beyond
Container Network Interface: Network Plugins for Kubernetes and beyondContainer Network Interface: Network Plugins for Kubernetes and beyond
Container Network Interface: Network Plugins for Kubernetes and beyond
KubeAcademy
 
DevOps introduction
DevOps introductionDevOps introduction
DevOps introduction
Christian F. Nissen
 
Docker 사내교육 자료
Docker 사내교육 자료Docker 사내교육 자료
Docker 사내교육 자료
Juneyoung Oh
 
Kubernetes Architecture and Introduction
Kubernetes Architecture and IntroductionKubernetes Architecture and Introduction
Kubernetes Architecture and Introduction
Stefan Schimanski
 
Code Smells y SOLID: A qué huele tu código?
Code Smells y SOLID: A qué huele tu código?Code Smells y SOLID: A qué huele tu código?
Code Smells y SOLID: A qué huele tu código?
Johnny Ordóñez
 
Devops on AWS
Devops on AWSDevops on AWS
Devops on AWS
AWS Riyadh User Group
 
Ipc in linux
Ipc in linuxIpc in linux
Ipc in linux
Dr. C.V. Suresh Babu
 
PySpark 배우기 Ch 06. ML 패키지 소개하기
PySpark 배우기 Ch 06. ML 패키지 소개하기PySpark 배우기 Ch 06. ML 패키지 소개하기
PySpark 배우기 Ch 06. ML 패키지 소개하기
찬희 이
 
OSSNA18: Xen Beginners Training (exercise script)
OSSNA18: Xen Beginners Training (exercise script)OSSNA18: Xen Beginners Training (exercise script)
OSSNA18: Xen Beginners Training (exercise script)
The Linux Foundation
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple Inheritance
Damian T. Gordon
 
intro to DevOps
intro to DevOpsintro to DevOps
intro to DevOps
Mujahed Al-Tahle
 
Introduction to advanced python
Introduction to advanced pythonIntroduction to advanced python
Introduction to advanced python
Charles-Axel Dein
 
Phpunit testing
Phpunit testingPhpunit testing
Phpunit testing
Nikunj Bhatnagar
 
Encapsulamento com Descritores em Python
Encapsulamento com Descritores em PythonEncapsulamento com Descritores em Python
Encapsulamento com Descritores em Python
Luciano Ramalho
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
Ahsan Raja
 
devops
devops devops
devops
Somkiat Puisungnoen
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Edureka!
 
Container Network Interface: Network Plugins for Kubernetes and beyond
Container Network Interface: Network Plugins for Kubernetes and beyondContainer Network Interface: Network Plugins for Kubernetes and beyond
Container Network Interface: Network Plugins for Kubernetes and beyond
KubeAcademy
 
Docker 사내교육 자료
Docker 사내교육 자료Docker 사내교육 자료
Docker 사내교육 자료
Juneyoung Oh
 
Kubernetes Architecture and Introduction
Kubernetes Architecture and IntroductionKubernetes Architecture and Introduction
Kubernetes Architecture and Introduction
Stefan Schimanski
 
Code Smells y SOLID: A qué huele tu código?
Code Smells y SOLID: A qué huele tu código?Code Smells y SOLID: A qué huele tu código?
Code Smells y SOLID: A qué huele tu código?
Johnny Ordóñez
 
PySpark 배우기 Ch 06. ML 패키지 소개하기
PySpark 배우기 Ch 06. ML 패키지 소개하기PySpark 배우기 Ch 06. ML 패키지 소개하기
PySpark 배우기 Ch 06. ML 패키지 소개하기
찬희 이
 
OSSNA18: Xen Beginners Training (exercise script)
OSSNA18: Xen Beginners Training (exercise script)OSSNA18: Xen Beginners Training (exercise script)
OSSNA18: Xen Beginners Training (exercise script)
The Linux Foundation
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple Inheritance
Damian T. Gordon
 
Introduction to advanced python
Introduction to advanced pythonIntroduction to advanced python
Introduction to advanced python
Charles-Axel Dein
 
Encapsulamento com Descritores em Python
Encapsulamento com Descritores em PythonEncapsulamento com Descritores em Python
Encapsulamento com Descritores em Python
Luciano Ramalho
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
Ahsan Raja
 

Viewers also liked (14)

Python 2 vs. Python 3
Python 2 vs. Python 3Python 2 vs. Python 3
Python 2 vs. Python 3
Pablo Enfedaque
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
Sujith 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 Python
Sujith 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
 
進階主題
進階主題進階主題
進階主題
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 Minutes
Matt Harrison
 
[系列活動] Python 程式語言起步走
[系列活動] Python 程式語言起步走[系列活動] Python 程式語言起步走
[系列活動] Python 程式語言起步走
台灣資料科學年會
 
[系列活動] Python爬蟲實戰
[系列活動] Python爬蟲實戰[系列活動] Python爬蟲實戰
[系列活動] Python爬蟲實戰
台灣資料科學年會
 
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
台灣資料科學年會
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
Sujith 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 Python
Sujith 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 Minutes
Matt Harrison
 
[系列活動] Python 程式語言起步走
[系列活動] Python 程式語言起步走[系列活動] Python 程式語言起步走
[系列活動] Python 程式語言起步走
台灣資料科學年會
 
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
台灣資料科學年會
 
Ad

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
Eran Shlomo
 
Intro to Python for C# Developers
Intro to Python for C# DevelopersIntro to Python for C# Developers
Intro to Python for C# Developers
Sarah 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 Yang
PYCON MY PLT
 
Intro
IntroIntro
Intro
Daniel Greenfeld
 
Python+gradle
Python+gradlePython+gradle
Python+gradle
Stephen Holsapple
 
Clean Manifests with Puppet::Tidy
Clean Manifests with Puppet::TidyClean Manifests with Puppet::Tidy
Clean Manifests with Puppet::Tidy
Puppet
 
Code with Style - PyOhio
Code with Style - PyOhioCode with Style - PyOhio
Code with Style - PyOhio
Clayton Parker
 
Python Programming1.ppt
Python Programming1.pptPython Programming1.ppt
Python Programming1.ppt
Rehnawilson1
 
Code with style
Code with styleCode with style
Code with style
Clayton Parker
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
Daniel Greenfeld
 
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
Puppet
 
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 Accident
Daniel Greenfeld
 
Package manages and Puppet - PuppetConf 2015
Package manages and Puppet - PuppetConf 2015Package manages and Puppet - PuppetConf 2015
Package manages and Puppet - PuppetConf 2015
ice799
 
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
Puppet
 
20_Python_Libraries_You_Aren't_Using_But_Should.pdf
20_Python_Libraries_You_Aren't_Using_But_Should.pdf20_Python_Libraries_You_Aren't_Using_But_Should.pdf
20_Python_Libraries_You_Aren't_Using_But_Should.pdf
omonovasadbek0821
 
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
ssuser8b3cdd
 
Python on a chip
Python on a chipPython on a chip
Python on a chip
stoggi
 
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
David 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 pythin
université d'el jadida
 
PyCourse - Self driving python course
PyCourse - Self driving python coursePyCourse - Self driving python course
PyCourse - Self driving python course
Eran Shlomo
 
Intro to Python for C# Developers
Intro to Python for C# DevelopersIntro to Python for C# Developers
Intro to Python for C# Developers
Sarah 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 Yang
PYCON MY PLT
 
Clean Manifests with Puppet::Tidy
Clean Manifests with Puppet::TidyClean Manifests with Puppet::Tidy
Clean Manifests with Puppet::Tidy
Puppet
 
Code with Style - PyOhio
Code with Style - PyOhioCode with Style - PyOhio
Code with Style - PyOhio
Clayton Parker
 
Python Programming1.ppt
Python Programming1.pptPython Programming1.ppt
Python Programming1.ppt
Rehnawilson1
 
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
Puppet
 
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 Accident
Daniel Greenfeld
 
Package manages and Puppet - PuppetConf 2015
Package manages and Puppet - PuppetConf 2015Package manages and Puppet - PuppetConf 2015
Package manages and Puppet - PuppetConf 2015
ice799
 
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
Puppet
 
20_Python_Libraries_You_Aren't_Using_But_Should.pdf
20_Python_Libraries_You_Aren't_Using_But_Should.pdf20_Python_Libraries_You_Aren't_Using_But_Should.pdf
20_Python_Libraries_You_Aren't_Using_But_Should.pdf
omonovasadbek0821
 
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
ssuser8b3cdd
 
Python on a chip
Python on a chipPython on a chip
Python on a chip
stoggi
 
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
David 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 pythin
université d'el jadida
 
Ad

Recently uploaded (20)

The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 

Python Tricks That You Can't Live Without

  • 1. Audrey Roy [email protected] 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: [email protected] Audrey Roy @audreyr

Editor's Notes