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

Apache Zeppelin on Kubernetes with Spark and Kafka - meetup @twitter
Apache Zeppelin on Kubernetes with Spark and Kafka - meetup @twitterApache Zeppelin on Kubernetes with Spark and Kafka - meetup @twitter
Apache Zeppelin on Kubernetes with Spark and Kafka - meetup @twitterApache Zeppelin
 
queue & its applications
queue & its applicationsqueue & its applications
queue & its applicationssomendra kumar
 
MongoDB Fundamentals
MongoDB FundamentalsMongoDB Fundamentals
MongoDB FundamentalsMongoDB
 
Operator Overloading In Python
Operator Overloading In PythonOperator Overloading In Python
Operator Overloading In PythonSimplilearn
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Paige Bailey
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data StructureMeghaj Mallick
 
Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListPTCL
 
Variables & Data Types In Python | Edureka
Variables & Data Types In Python | EdurekaVariables & Data Types In Python | Edureka
Variables & Data Types In Python | EdurekaEdureka!
 
Hadoop Distributed File System
Hadoop Distributed File SystemHadoop Distributed File System
Hadoop Distributed File Systemelliando dias
 
Control_Statements_in_Python.pptx
Control_Statements_in_Python.pptxControl_Statements_in_Python.pptx
Control_Statements_in_Python.pptxKoteswari Kasireddy
 

What's hot (20)

Apache Zeppelin on Kubernetes with Spark and Kafka - meetup @twitter
Apache Zeppelin on Kubernetes with Spark and Kafka - meetup @twitterApache Zeppelin on Kubernetes with Spark and Kafka - meetup @twitter
Apache Zeppelin on Kubernetes with Spark and Kafka - meetup @twitter
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
queue & its applications
queue & its applicationsqueue & its applications
queue & its applications
 
MongoDB Fundamentals
MongoDB FundamentalsMongoDB Fundamentals
MongoDB Fundamentals
 
Python: Polymorphism
Python: PolymorphismPython: Polymorphism
Python: Polymorphism
 
Linked list
Linked listLinked list
Linked list
 
Operator Overloading In Python
Operator Overloading In PythonOperator Overloading In Python
Operator Overloading In Python
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
 
Linear data structure concepts
Linear data structure conceptsLinear data structure concepts
Linear data structure concepts
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data Structure
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
 
Queue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked ListQueue Implementation Using Array & Linked List
Queue Implementation Using Array & Linked List
 
Variables & Data Types In Python | Edureka
Variables & Data Types In Python | EdurekaVariables & Data Types In Python | Edureka
Variables & Data Types In Python | Edureka
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Linked List
Linked ListLinked List
Linked List
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Hadoop Distributed File System
Hadoop Distributed File SystemHadoop Distributed File System
Hadoop Distributed File System
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
 
Control_Statements_in_Python.pptx
Control_Statements_in_Python.pptxControl_Statements_in_Python.pptx
Control_Statements_in_Python.pptx
 

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

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 

Recently uploaded (20)

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 

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