SlideShare ist ein Scribd-Unternehmen logo
1 von 45
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

오토인코더의 모든 것
오토인코더의 모든 것오토인코더의 모든 것
오토인코더의 모든 것
NAVER Engineering
 

Was ist angesagt? (20)

Data Augmentation
Data AugmentationData Augmentation
Data Augmentation
 
Regularization in deep learning
Regularization in deep learningRegularization in deep learning
Regularization in deep learning
 
Pytorch
PytorchPytorch
Pytorch
 
Best Python Libraries For Data Science & Machine Learning | Edureka
Best Python Libraries For Data Science & Machine Learning | EdurekaBest Python Libraries For Data Science & Machine Learning | Edureka
Best Python Libraries For Data Science & Machine Learning | Edureka
 
Chain-of-thought Prompting.pptx
Chain-of-thought Prompting.pptxChain-of-thought Prompting.pptx
Chain-of-thought Prompting.pptx
 
Introduction to Computer Vision using OpenCV
Introduction to Computer Vision using OpenCVIntroduction to Computer Vision using OpenCV
Introduction to Computer Vision using OpenCV
 
Real-time object detection coz YOLO!
Real-time object detection coz YOLO!Real-time object detection coz YOLO!
Real-time object detection coz YOLO!
 
Neural Networks with Google TensorFlow
Neural Networks with Google TensorFlowNeural Networks with Google TensorFlow
Neural Networks with Google TensorFlow
 
Deep Learning for Computer Vision: Image Classification (UPC 2016)
Deep Learning for Computer Vision: Image Classification (UPC 2016)Deep Learning for Computer Vision: Image Classification (UPC 2016)
Deep Learning for Computer Vision: Image Classification (UPC 2016)
 
Attention is All You Need (Transformer)
Attention is All You Need (Transformer)Attention is All You Need (Transformer)
Attention is All You Need (Transformer)
 
오토인코더의 모든 것
오토인코더의 모든 것오토인코더의 모든 것
오토인코더의 모든 것
 
딥러닝 기본 원리의 이해
딥러닝 기본 원리의 이해딥러닝 기본 원리의 이해
딥러닝 기본 원리의 이해
 
Neural Networks: Multilayer Perceptron
Neural Networks: Multilayer PerceptronNeural Networks: Multilayer Perceptron
Neural Networks: Multilayer Perceptron
 
[Paper Reading] Attention is All You Need
[Paper Reading] Attention is All You Need[Paper Reading] Attention is All You Need
[Paper Reading] Attention is All You Need
 
Decision Tree.pptx
Decision Tree.pptxDecision Tree.pptx
Decision Tree.pptx
 
Machine Learning - Object Detection and Classification
Machine Learning - Object Detection and ClassificationMachine Learning - Object Detection and Classification
Machine Learning - Object Detection and Classification
 
Computer Vision.pptx
Computer Vision.pptxComputer Vision.pptx
Computer Vision.pptx
 
Naive Bayes
Naive BayesNaive Bayes
Naive Bayes
 
Loss Functions for Deep Learning - Javier Ruiz Hidalgo - UPC Barcelona 2018
Loss Functions for Deep Learning - Javier Ruiz Hidalgo - UPC Barcelona 2018Loss Functions for Deep Learning - Javier Ruiz Hidalgo - UPC Barcelona 2018
Loss Functions for Deep Learning - Javier Ruiz Hidalgo - UPC Barcelona 2018
 
1 seaborn introduction
1 seaborn introduction 1 seaborn introduction
1 seaborn introduction
 

Andere mochten auch

[系列活動] Python 程式語言起步走
[系列活動] Python 程式語言起步走[系列活動] Python 程式語言起步走
[系列活動] Python 程式語言起步走
台灣資料科學年會
 
[系列活動] Python爬蟲實戰
[系列活動] Python爬蟲實戰[系列活動] Python爬蟲實戰
[系列活動] Python爬蟲實戰
台灣資料科學年會
 
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
台灣資料科學年會
 

Andere mochten auch (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爬蟲實戰
 
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
[系列活動] 無所不在的自然語言處理—基礎概念、技術與工具介紹
 

Ähnlich wie Python Tricks That You Can't Live Without

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
 

Ähnlich wie 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
 

KĂźrzlich hochgeladen

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
Christopher Logan Kennedy
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

KĂźrzlich hochgeladen (20)

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

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

Hinweis der Redaktion

  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