Python
Python
Python
Henning Schulzrinne
Department of Computer
Science
Columbia University
Feb 15, 2015
Introduction
Most recent popular
(scripting/extension) language
although origin ~1991
object-oriented
rather than add-on (OOTcl)
Feb 15, 2015
Advanced
Python philosophy
Coherence
not hard to read, write and maintain
power
scope
rapid development + large systems
objects
integration
hybrid systems
Feb 15, 2015
Advanced
Python features
Lutz, Programming Python
no compiling or linking
no type declarations
automatic memory
management
garbage collection
fast development
object-oriented programming
"programming-in-the-large"
support
dynamic reloading of C
Feb 15, 2015
modules
Python features
Lutz, Programming Python
access to interpreter
information
metaprogramming,
introspective objects
wide portability
cross-platform programming
without ports
Advanced
Python
elements from C++, Modula-3
(modules), ABC, Icon (slicing)
same family as Perl, Tcl, Scheme,
REXX, BASIC dialects
Advanced
Uses of Python
shell tools
system admin tools, command line programs
extension-language work
rapid prototyping and development
language-based modules
instead of special-purpose parsers
Advanced
Advanced
Using python
/usr/local/bin/python
#! /usr/bin/env python
interactive use
Python 1.6 (#1, Sep 24 2000, 20:40:45) [GCC 2.95.1 19990816 (release)] on sunos5
Copyright (c) 1995-2000 Corporation for National Research Initiatives.
All Rights Reserved.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.
>>>
Advanced
Python structure
modules: Python source files or C
extensions
import, top-level via from, reload
statements
control flow
create objects
indentation matters instead of {}
objects
everything is an object
automatically reclaimed when no longer needed
Advanced
First example
#!/usr/local/bin/python
# import systems module
import sys
marker = '::::::'
for name in sys.argv[1:]:
input = open(name, 'r')
print marker + name
print input.read()
Advanced
Basic operations
Assignment:
size = 40
a = b = c = 3
Numbers
integer, float
complex numbers: 1j+3, abs(z)
Strings
'hello world', 'it\'s hot'
"bye world"
continuation via \ or use """ long text """"
Advanced
String operations
concatenate with + or neighbors
word = 'Help' + x
word = 'Help' 'a'
subscripting of strings
'Hello'[2] 'l'
slice: 'Hello'[1:2] 'el'
word[-1] last character
len(word) 5
immutable: cannot assign to subscript
Advanced
Lists
lists can be heterogeneous
a = ['spam', 'eggs', 100, 1234, 2*2]
a[2] =
a[0:2]
a[0:0]
len(a)
a[2] + 23
= [1,12]
= []
5
Advanced
Basic programming
a,b = 0, 1
# non-zero = true
while b < 10:
# formatted output, without \n
print b,
# multiple assignment
a,b = b, a+b
Advanced
Control flow: if
x = int(raw_input("Please enter #:"))
if x < 0:
x = 0
print 'Negative changed to zero'
elif x == 0:
print 'Zero'
elif x == 1:
print 'Single'
else:
print 'More'
no case statement
Feb 15, 2015
Advanced
Advanced
Advanced
Do nothing
pass does nothing
syntactic filler
while 1:
pass
Advanced
Defining functions
def fib(n):
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b
>>> fib(2000)
Advanced
Advanced
Keyword arguments
last arguments can be given as
keywords
def parrot(voltage, state='a stiff', action='voom',
type='Norwegian blue'):
print "-- This parrot wouldn't", action,
print "if you put", voltage, "Volts through it."
print "Lovely plumage, the ", type
print "-- It's", state, "!"
parrot(1000)
parrot(action='VOOOM', voltage=100000)
Advanced
Lambda forms
anonymous functions
may not work in older versions
def make_incrementor(n):
return lambda x: x + n
f = make_incrementor(42)
f(0)
f(1)
Feb 15, 2015
Advanced
List methods
append(x)
extend(L)
append all items in list (like Tcl lappend)
insert(i,x)
remove(x)
pop([i]), pop()
create stack (FIFO), or queue (LIFO) pop(0)
index(x)
return the index for value x
Advanced
List methods
count(x)
how many times x appears in list
sort()
sort items in place
reverse()
reverse list
Advanced
Functional programming
tools
filter(function, sequence)
def f(x): return x%2 != 0 and x%3 0
filter(f, range(2,25))
map(function, sequence)
call function for each item
return list of return values
reduce(function, sequence)
Advanced
Advanced
List comprehensions
cross products:
>>> vec1 = [2,4,6]
>>> vec2 = [4,3,-9]
>>> [x*y for x in vec1 for y in vec2]
[8,6,-18, 16,12,-36, 24,18,-54]
>>> [x+y for x in vec1 and y in vec2]
[6,5,-7,8,7,-5,10,9,-3]
>>> [vec1[i]*vec2[i] for i in
range(len(vec1))]
[8,12,-54]
Feb 15, 2015
Advanced
List comprehensions
can also use if:
>>> [3*x for x in vec if x > 3]
[12, 18]
>>> [3*x for x in vec if x < 2]
[]
Advanced
Advanced
>>> t
(123, 543, 'bar')
Feb 15, 2015
Advanced
Tuples
Tuples may be nested
>>> u = t, (1,2)
>>> u
((123, 542, 'bar'), (1,2))
kind of like structs, but no element
names:
(x,y) coordinates
database records
Advanced
Tuples
Empty tuples: ()
>>> empty = ()
>>> len(empty)
0
Advanced
Tuples
sequence unpacking distribute
elements across variables
>>> t = 123, 543, 'bar'
>>> x, y, z = t
>>> x
123
Advanced
Dictionaries
like Tcl or awk associative arrays
indexed by keys
keys are any immutable type: e.g.,
tuples
but not lists (mutable!)
uses 'key: value' notation
>>> tel = {'hgs' : 7042, 'lennox': 7018}
>>> tel['cs'] = 7000
>>> tel
Feb 15, 2015
Advanced
Dictionaries
no particular order
delete elements with del
>>> del tel['foo']
Advanced
Conditions
can check for sequence membership
with is and is not:
>>> if (4 in vec):
... print '4 is'
Advanced
Conditions
Can assign comparison to variable:
>>> s1,s2,s3='', 'foo', 'bar'
>>> non_null = s1 or s2 or s3
>>> non_null
foo
Advanced
Comparing sequences
unlike C, can compare sequences
(lists, tuples, ...)
lexicographical comparison:
Advanced
Comparing sequences
(1,2,3) < (1,2,4)
[1,2,3] < [1,2,4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1,2,3) == (1.0,2.0,3.0)
(1,2) < (1,2,-1)
Advanced
Modules
collection of functions and variables,
typically in scripts
definitions can be imported
file name is module name + .py
e.g., create module fibo.py
def fib(n): # write Fib. series up to n
...
def fib2(n): # return Fib. series up to n
Feb 15, 2015
Advanced
Modules
import module:
import fibo
Advanced
Modules
function definition + executable
statements
executed only when module is imported
modules have private symbol tables
avoids name clash for global variables
accessible as module.globalname
can import into name space:
>>> from fibo import fib, fib2
>>> fib(500)
Advanced
Advanced
Advanced
Standard modules
system-dependent list
always sys module
>>> import sys
>>> sys.p1
'>>> '
>>> sys.p2
'... '
>>> sys.path.append('/some/directory')
Advanced
Module listing
use dir() for each module
>>> dir(fibo)
['___name___', 'fib', 'fib2']
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__st
din__', '__stdout__', '_getframe', 'argv', 'builtin_module_names', 'byteorder',
'copyright', 'displayhook', 'dllhandle', 'exc_info', 'exc_type', 'excepthook', '
exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getrecursionlimit', '
getrefcount', 'hexversion', 'last_type', 'last_value', 'maxint', 'maxunicode', '
modules', 'path', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setpr
ofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version',
'version_info', 'warnoptions', 'winver']
Advanced
Classes
mixture of C++ and Modula-3
multiple base classes
derived class can override any methods of
its base class(es)
method can call the method of a base
class with the same name
objects have private data
C++ terms:
all class members are public
all member functions are virtual
no constructors or destructors (not needed)
Advanced
Classes
classes (and data types) are
objects
built-in types cannot be used as
base classes by user
arithmetic operators, subscripting
can be redefined for class
instances (like C++, unlike Java)
Advanced
Class definitions
Class ClassName:
<statement-1>
...
<statement-N>
must be executed
can be executed conditionally (see
Tcl)
creates new namespace
Feb 15, 2015
Advanced
Namespaces
mapping from name to object:
built-in names (abs())
global names in module
local names in function invocation
Advanced
Namespaces
scope = textual region of Python program
where a namespace is directly accessible
(without dot)
innermost scope (first) = local names
middle scope = current module's global names
outermost scope (last) = built-in names
Advanced
Class objects
obj.name references (plus module!):
class MyClass:
"A simple example class"
i = 123
def f(self):
return 'hello world'
>>> MyClass.i
123
Advanced
Class objects
class instantiation:
>>> x = MyClass()
>>> x.f()
'hello world'
Advanced
Instance objects
attribute references
data attributes (C++/Java data
members)
created dynamically
x.counter = 1
while x.counter < 10:
x.counter = x.counter * 2
print x.counter
del x.counter
Feb 15, 2015
Advanced
Method objects
Called immediately:
x.f()
can be referenced:
xf = x.f
while 1:
print xf()
Advanced
Notes on classes
Data attributes override method
attributes with the same name
no real hiding not usable to
implement pure abstract data types
clients (users) of an object can add
data attributes
first argument of method usually
called self
'self' has no special meaning (cf. Java)
Feb 15, 2015
Advanced
Another example
bag.py
class Bag:
def __init__(self):
self.data = []
def add(self, x):
self.data.append(x)
def addtwice(self,x):
self.add(x)
self.add(x)
Advanced
Advanced
Inheritance
class DerivedClassName(BaseClassName)
<statement-1>
...
<statement-N>
Advanced
Multiple inheritance
class DerivedClass(Base1,Base2,Base3):
<statement>
depth-first, left-to-right
problem: class derived from two
classes with a common base class
Advanced
Private variables
No real support, but textual
replacement (name mangling)
__var is replaced by
_classname_var
prevents only accidental
modification, not true protection
Advanced
~ C structs
Empty class definition:
class Employee:
pass
john = Employee()
john.name = 'John Doe'
john.dept = 'CS'
john.salary = 1000
Feb 15, 2015
Advanced
Exceptions
syntax (parsing) errors
while 1 print 'Hello World'
File "<stdin>", line 1
while 1 print 'Hello World'
^
SyntaxError:
invalid syntax
exceptions
run-time errors
e.g., ZeroDivisionError,
NameError, TypeError
Feb 15, 2015
Advanced
Handling exceptions
while 1:
try:
x = int(raw_input("Please enter a number: "))
break
except ValueError:
print "Not a valid number"
Advanced
Handling exceptions
try.py
import sys
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'lines:', len(f.readlines())
f.close
e.g., as python try.py *.py
Advanced
Language comparison
Tcl
Perl
development
regexp
extensible
embeddable
easy GUI
(Tk)
net/web
enterpris cross-platform
e
I18N
thread-safe
Speed
breadth
database access
Advanced