python introduction

53
Introduction to Python Master in Free Software   2009/2010 Joaquim Rocha <[email protected]> 23, April 2010

Upload: joaquim-rocha

Post on 19-May-2015

1.711 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Python introduction

Introduction to Python

Master in Free Software   2009/2010

Joaquim Rocha <[email protected]>

23, April 2010

Page 2: Python introduction

Master in Free Software | 2009­2010 2

What is it?

* General­purpose, high­level programming language

* Created by Guido van Rossum

Page 3: Python introduction

Master in Free Software | 2009­2010 3

What is it?

* Named after Monty Python's Flying Circus

* Managed by the Python Software Foundation

* Licensed under the Python Software Foundation license (Free Software and compatible with GPL)

Page 4: Python introduction

Master in Free Software | 2009­2010 4

How is it?

* Multi­paradigm

* Features garbage­collection

* Focuses on readability and productivity

* Strong introspection capabilities

Page 5: Python introduction

Master in Free Software | 2009­2010 5

How is it?

* Batteries included!

* Guido is often called Python's Benevolent Dictator For Life (BDFL) for he makes the final calls in Python's matters

Page 6: Python introduction

Master in Free Software | 2009­2010 6

Brief history

* Created in 1991 at the Stichting Mathematisch Centrum (Amsterdam)

* Designed as a scripting language for the Amoeba system

* January 1994: version 1.0

Page 7: Python introduction

Master in Free Software | 2009­2010 7

Brief history

* October 2000: version 2.0

* December 2001: version 2.2 (first release under PSF license)

* October 2008: version 2.6

* December 2008: version 3.0

Page 8: Python introduction

Master in Free Software | 2009­2010 8

Python Software Foundation License

* Free Software license (recognized by the Open Source Initiative)

* GPL-compatible

* http://python.org/psf/license/

* http://www.python.org/download/releases/2.6.2/license/

Page 9: Python introduction

Master in Free Software | 2009­2010 9

Companies using Python

* Google (and YouTube)

* NASA

* Philips

* Industrial Light & Magic

* EVE Online...

Page 10: Python introduction

Master in Free Software | 2009­2010 10

Projects using Python

* Django* Pitivi* Trac* Plone* Frets on Fire* Miro* OCRFeeder...

Page 11: Python introduction

Master in Free Software | 2009­2010 11

Some books on Python

* Programming Python (O'Reilly)

* Python in a Nutshell (O'Reilly)

* Dive Into Python (Apress)

* Expert Python Programming (Packt Publishing)

Page 12: Python introduction

Master in Free Software | 2009­2010 12

How to install it

* It's already installed in most mainstream distros

* If not, on Debian:

apt­get install python

Page 13: Python introduction

Master in Free Software | 2009­2010 13

Python Shell

$ pythonPython 2.6.4 (r264:75706, Dec  7 2009, 18:45:15)[GCC 4.4.1] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import thisThe Zen of Python, by Tim Peters...

Page 14: Python introduction

Master in Free Software | 2009­2010 14

Documentation

* Python is really well documented

  http://docs.python.org

* On Debian distros, install python2.6­doc to view it with Devhelp

Page 15: Python introduction

Master in Free Software | 2009­2010 15

Some helpful functions

* The help command displays the help on a symbol  >>> import os  >>> help(os.path)

* The dir command displays attributes or available names  >>> dir() # displays names in current scope  >>> dir(str) # displays attributes of the class and its bases

Page 16: Python introduction

Master in Free Software | 2009­2010 16

Python packages and modules

  # This is a module, and would be the execution script  myapp_run.py   myapp/ # A package      __init__.py # A special module      myappcode.py # A module      lib/ # A sub­package          __init__.py          util_functions.py # Another module

* The __init__.py is often empty but is what allows the package to be imported as a if it was a module.

Page 17: Python introduction

Master in Free Software | 2009­2010 17

Example of types

*  In Python everything is an object

* str : strings (there is also a string module, that most functions are now available in str)

  'This is a string'  “This is also a string!”  “””And this is a    multiline string...”””

Page 18: Python introduction

Master in Free Software | 2009­2010 18

Example of types

* int: integer numbers

  i = 12 + 4

* float: floating point numbers

  f = 0.45

Page 19: Python introduction

Master in Free Software | 2009­2010 19

Example of types

* bool: booleans

  b = True  e = b and c or d

* list: list objects

  list_var = ['foo', 45, False]

Page 20: Python introduction

Master in Free Software | 2009­2010 20

Example of types

* dict: dictionary objects

  d = {'type': 'person', 'age': 24,          10: 'just to show off an int key'}

...

Page 21: Python introduction

Master in Free Software | 2009­2010 21

Checking a type

 >>> type(some_object) # gives the object's type >>> isinstance('foo bar', str) # returns True

Page 22: Python introduction

Master in Free Software | 2009­2010 22

Castings

  int('5') # gives the integer 5

  str(5) # gives the string '5'

  bool('') # gives False

Page 23: Python introduction

Master in Free Software | 2009­2010 23

Whitespace indentation

* Python blocks are defined by indentation instead of curly brackets or begin/end statements.

* Failing to properly indent blocks raises indentation exceptions

Page 24: Python introduction

Master in Free Software | 2009­2010 24

Whitespace indentation

* If a new block is expected and none is to be defined, the pass keyword can be used

  if x is None:      pass

Page 25: Python introduction

Master in Free Software | 2009­2010 25

Control flow: if

  if x < 0:      print 'X is negative!'  elif x > 0:      print 'X is positive!'  else:      print 'X is zero...'

Page 26: Python introduction

Master in Free Software | 2009­2010 26

Control flow: for

  for x in range(10): # this is [0..9]      if x % 2 == 0:          continue      print x ** 2

Page 27: Python introduction

Master in Free Software | 2009­2010 27

Control flow: while

  fruits = ['bananas', 'apples', 'melon', 'grapes',                          'oranges']  i = 0  while i < len(fruits):      if len(fruits[i]) == 5:          break      i += 1

Page 28: Python introduction

Master in Free Software | 2009­2010 28

Functional programming

* Being multi­paradigm, Python also has functions common in functional programming

* It features lambda, map, filter, reduce, ...

 numbers = [1, 2, 3, 4]  map(lambda x: x ** 2, numbers) # gives [1, 4, 9, 16]

  filter(lambda x: x % 2 == 0, numbers) # gives [2, 4]

  reduce(lambda x, y: x + y, numbers) # gives 10

Page 29: Python introduction

Master in Free Software | 2009­2010 29

Functional programming

* List comprehension

  numbers = [1, 2, 3, 4, 5, 6, 7, 8]  even_numbers = [n for n in numbers \                                 if n % 2 == 0] 

Page 30: Python introduction

Master in Free Software | 2009­2010 30

Error handling: try / except* Equivalent to try, catch statements

  import random

  n = random.choice(['three', 1])  try:      a = 'three ' + n  except TypeError:      a = 3 + n  else: # else body is executed is try's body didn't raise an exception      a = 'The answer is ' + a  finally: # this is always executed      print a

Page 31: Python introduction

Master in Free Software | 2009­2010 31

Error handling: try / except

* Getting exception details

  try:      a = not_defined_var  except Exception as e:       # the "as" keyword exists since Python 2.6      # for Python 2.5, use “,” instead      print type(e)

Page 32: Python introduction

Master in Free Software | 2009­2010 32

Error handling: try / except

* Raising exceptions

  password = 'qwerty'  if password != 'ytrewq':      raise Exception('Wrong password!')

Page 33: Python introduction

Master in Free Software | 2009­2010 33

Imports

* Import a module:

  import datetime  d = datetime.date(2010, 4, 22)

* Import a single class from a module:

  from datetime import date  d = date(2010, 4, 22)

Page 34: Python introduction

Master in Free Software | 2009­2010 34

Imports

* Import more than one class from a module:

  from datetime import date, time  d = date(2010, 4, 22)  t = time(15, 45)

* Import a single module from another module:

  from os import path  notes_exist = path.exists('notes.txt')

Page 35: Python introduction

Master in Free Software | 2009­2010 35

Imports

* Import everything from a module:

  from datetime import *  t = time(15, 45)

* Rename imported items:

  from datetime import date  from mymodule import date as mydate  # otherwise it would have overridden the previous date

Page 36: Python introduction

Master in Free Software | 2009­2010 36

Functions

  def cube(number):      return number ** 3

  # optional arguments  def power_from_square(base, exponent = 2):      # every argument after an optional argument      # must be also optional      return base ** exponent

Page 37: Python introduction

Master in Free Software | 2009­2010 37

Functions

  # the exponent argument is optional  power(2) # returns 4  power(2, 3) # returns 8

  # named arguments can be used  power(base=8, exponent=4)

  # and can be even interchanged  power(exponent=2, base=4)

Page 38: Python introduction

Master in Free Software | 2009­2010 38

Object Oriented Programming

class Car:

      # this is a class variable      min_doors = 3

      # contructor      def __init__(self, model):          # this is an instance variable          self.model = model          # this is a private variable          self._color = 'white'

Page 39: Python introduction

Master in Free Software | 2009­2010 39

Object Oriented Programming

      # private method      def _is_black(self):          if self._color == 'black' or self._color == '#000':              return True          return False

      # public method      def set_color(self, color):          if color in ['black', 'white', 'red', 'blue']:              self._color = color

      def get_extense_name(self):          return 'A very fine %s %s' % (self.model, self._color)

Page 40: Python introduction

Master in Free Software | 2009­2010 40

Inheritance

  # this is how we say Car extends the Vehicle class  class Car(Vehicle):

      def __init__(self, model):          # we need to instantiate the superclass          Vehicle.__init__(self, tyres = 4)          self.model = model          …

Page 41: Python introduction

Master in Free Software | 2009­2010 41

Executing code

* Here is how is Python's main:

  if __name__ == '__main__':      a = 1      print a

* Execute it with:

  $ python print_one.py

Page 42: Python introduction

Master in Free Software | 2009­2010 42

Properties

* Properties abstract actions on an attribute, as get, set, del or doc

  # When you set/get person.name, it will do a customized set/get  class Person:      def __init__(self, name):          self.name = name      def _set_name(self, name):          self._name = str(name)      def _get_name(self):          return 'My name is ' + self._name      name = property(_get_name, _set_name)

Page 43: Python introduction

Master in Free Software | 2009­2010 43

Distributing your application

* Distutils allows to easily packages your application, install it, etc.

* Our app structure:

  SupApp/    setup.py    supaapp    data/      supaapp.png    src/      supaApp/

supaapp.py        lib/          util.py

Page 44: Python introduction

Master in Free Software | 2009­2010 44

Distributing your application* The magic script

  from distutils.core import setup  setup(name = 'SupaApp',             version = '0.5beta'             description = 'A supa­dupa app!'             author = 'Cookie Monster'             author_email = '[email protected]'             license = 'GPL v3',             packages = ['SupaApp', 'SupaApp.lib'],             package_dir = {'': 'src'},             scripts = ['supaapp'],             data_files = [('share/icons/hicolor/scalable/apps',                                              ['data/supaapp.png'])]       )

Page 45: Python introduction

Master in Free Software | 2009­2010 45

Distributing your application

* The MANIFEST.in generates the MANIFEST file which describes what's to be included in the package:

  include supaapp  recursive­include data *

Page 46: Python introduction

Master in Free Software | 2009­2010 46

Distributing your application

* How to generate a source package

  $ python setup.py sdist

* How to install an app

  $ python setup.py install

Page 47: Python introduction

Master in Free Software | 2009­2010 47

Docstrings

* Are nowadays written in ReStructuredText

* Documentation of a module:

  """This is a nice module.       It shows you how to document modules  """  class Person:      """This class represents a person.          A person can have a name and ...      """      def __init__(self, name):          "Instantiates a Person object with the given name"          self.name = name

Page 48: Python introduction

Master in Free Software | 2009­2010 48

Some useful modules

import sys# Available packages/modules must be under the folders# sys.path hasprint sys.path# shows the arguments given after the python commandprint sys.argv 

# get png image namesimport ospng_names = [os.path.splitext(f)[0] for f in \                           os.listdir('/home/user/images') if f.endswith('png')]

Page 49: Python introduction

Master in Free Software | 2009­2010 49

Some useful modules

* ElementTree is an easy to use XML library

from xml.etree import ElementTree as ETtree = ET.parse("index.html")print tree.findall('body/p')

Page 50: Python introduction

Master in Free Software | 2009­2010 50

Decorators

* Decorators are functions that control other functions

import sysimport os

def verbose(function):

    def wrapper(*args, **kwargs):         print 'Executing function: ', function.__name__         print 'Arguments: ', args         print 'Keyword Arguments: %s\n' % kwargs         return function(*args, **kwargs)    return wrapper

Page 51: Python introduction

Master in Free Software | 2009­2010 51

Decorators

@verbose # this is how you apply a decoratordef list_dir(directory):    for f in os.listdir(directory):         print f

if __name__ == '__main__':    # list the directory we specify as the first program's argument    list_dir(sys.argv[1])

Page 52: Python introduction

Master in Free Software | 2009­2010 52

Decorators

* Testing the decorator

  $ python decorator_example.py /home/user/Documents        Executing function:  list_dir     Arguments:  ('/home/user/Documents/',)     Keyword Arguments: {}

     notes.txt     python_presentation.odp     book_review.odt

Page 53: Python introduction

Master in Free Software | 2009­2010 53

PDB: The Python Debugger

* Calling pdb.set_trace function will stop the execution and let you use commands similar to GDB

def weird_function():    import pdb;    pdb.set_trace()

    # code that is to be analyzed...