Introduction to Python Master in Free Software 2009/2010 Joaquim Rocha <[email protected]> 23, April 2010
Introduction to Python
Master in Free Software 2009/2010
Joaquim Rocha <[email protected]>
23, April 2010
Master in Free Software | 20092010 2
What is it?
* Generalpurpose, highlevel programming language
* Created by Guido van Rossum
Master in Free Software | 20092010 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)
Master in Free Software | 20092010 4
How is it?
* Multiparadigm
* Features garbagecollection
* Focuses on readability and productivity
* Strong introspection capabilities
Master in Free Software | 20092010 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
Master in Free Software | 20092010 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
Master in Free Software | 20092010 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
Master in Free Software | 20092010 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/
Master in Free Software | 20092010 9
Companies using Python
* Google (and YouTube)
* NASA
* Philips
* Industrial Light & Magic
* EVE Online...
Master in Free Software | 20092010 10
Projects using Python
* Django* Pitivi* Trac* Plone* Frets on Fire* Miro* OCRFeeder...
Master in Free Software | 20092010 11
Some books on Python
* Programming Python (O'Reilly)
* Python in a Nutshell (O'Reilly)
* Dive Into Python (Apress)
* Expert Python Programming (Packt Publishing)
Master in Free Software | 20092010 12
How to install it
* It's already installed in most mainstream distros
* If not, on Debian:
aptget install python
Master in Free Software | 20092010 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...
Master in Free Software | 20092010 14
Documentation
* Python is really well documented
http://docs.python.org
* On Debian distros, install python2.6doc to view it with Devhelp
Master in Free Software | 20092010 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
Master in Free Software | 20092010 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 subpackage __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.
Master in Free Software | 20092010 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...”””
Master in Free Software | 20092010 18
Example of types
* int: integer numbers
i = 12 + 4
* float: floating point numbers
f = 0.45
Master in Free Software | 20092010 19
Example of types
* bool: booleans
b = True e = b and c or d
* list: list objects
list_var = ['foo', 45, False]
Master in Free Software | 20092010 20
Example of types
* dict: dictionary objects
d = {'type': 'person', 'age': 24, 10: 'just to show off an int key'}
...
Master in Free Software | 20092010 21
Checking a type
>>> type(some_object) # gives the object's type >>> isinstance('foo bar', str) # returns True
Master in Free Software | 20092010 22
Castings
int('5') # gives the integer 5
str(5) # gives the string '5'
bool('') # gives False
Master in Free Software | 20092010 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
Master in Free Software | 20092010 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
Master in Free Software | 20092010 25
Control flow: if
if x < 0: print 'X is negative!' elif x > 0: print 'X is positive!' else: print 'X is zero...'
Master in Free Software | 20092010 26
Control flow: for
for x in range(10): # this is [0..9] if x % 2 == 0: continue print x ** 2
Master in Free Software | 20092010 27
Control flow: while
fruits = ['bananas', 'apples', 'melon', 'grapes', 'oranges'] i = 0 while i < len(fruits): if len(fruits[i]) == 5: break i += 1
Master in Free Software | 20092010 28
Functional programming
* Being multiparadigm, 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
Master in Free Software | 20092010 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]
Master in Free Software | 20092010 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
Master in Free Software | 20092010 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)
Master in Free Software | 20092010 32
Error handling: try / except
* Raising exceptions
password = 'qwerty' if password != 'ytrewq': raise Exception('Wrong password!')
Master in Free Software | 20092010 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)
Master in Free Software | 20092010 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')
Master in Free Software | 20092010 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
Master in Free Software | 20092010 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
Master in Free Software | 20092010 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)
Master in Free Software | 20092010 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'
Master in Free Software | 20092010 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)
Master in Free Software | 20092010 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 …
Master in Free Software | 20092010 41
Executing code
* Here is how is Python's main:
if __name__ == '__main__': a = 1 print a
* Execute it with:
$ python print_one.py
Master in Free Software | 20092010 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)
Master in Free Software | 20092010 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
Master in Free Software | 20092010 44
Distributing your application* The magic script
from distutils.core import setup setup(name = 'SupaApp', version = '0.5beta' description = 'A supadupa 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'])] )
Master in Free Software | 20092010 45
Distributing your application
* The MANIFEST.in generates the MANIFEST file which describes what's to be included in the package:
include supaapp recursiveinclude data *
Master in Free Software | 20092010 46
Distributing your application
* How to generate a source package
$ python setup.py sdist
* How to install an app
$ python setup.py install
Master in Free Software | 20092010 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
Master in Free Software | 20092010 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')]
Master in Free Software | 20092010 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')
Master in Free Software | 20092010 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
Master in Free Software | 20092010 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])
Master in Free Software | 20092010 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
Master in Free Software | 20092010 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...