Effective Python Programming

ap> « back to results for ""
Below is a cache of http://www.interlink.com.au/anthony/tech/talks/OSCON2005/effective_r27.pdf. It's a snapshot of the page taken as our search engine crawled the Web.
The web site itself may have changed. You can check the current page or check for previous versions at the Internet Archive. Yahoo! is not affiliated with the authors of this page or responsible for its content.
Effective Python Programming
Effective Python Programming OSCON 2005
Effective Python Programming Effective Python Programming OSCON 2005
Effective Programming Get the job done Better, more maintainable code Use the language's strengths Python is not:

C++

Java

Perl

... Effective Python Programming OSCON 2005
Laziness In development, laziness can be good Do things right the first time Don't re-invent every wheel Death to NIH Effective Python Programming OSCON 2005
Effective != Efficient Effective does not necessarily mean
efficient Optimise for development time Then worry about performance We'll touch on efficient code, later Effective Python Programming OSCON 2005
Target Python 2.4 CPython Effective Python Programming OSCON 2005
Python Fundamentals Learning by tinkering Everything's an object Namespaces EAFP Duck Typing Effective Python Programming OSCON 2005
Short Attention Span Theatre Key things to remember Even if you sleep through the rest,
you'll still get something Effective Python Programming OSCON 2005
S.A.S. Theatre Rule #1: Dictionaries Rule #2: See Rule #1 Effective Python Programming OSCON 2005
Programming with the hood up Introspection Experimentation Effective Python Programming OSCON 2005
Interactive Python

bonanza% python

Python 2.4.1 (#2, Mar 30 2005, 21:51:10)

[GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2

Type "help", "copyright", "credits" or "license" ...

>>>
Effective Python Programming OSCON 2005
help and dir help(obj) formats docstrings dir(obj) shows attributes Effective Python Programming OSCON 2005
help

>>> import os

>>> help(os.popen)

Help on built-in function popen in module posix:


popen(...)

popen(command [, mode='r' [, bufsize]]) -> pipe


Open a pipe to/from a command returning a file
object.
Effective Python Programming OSCON 2005
help...

>>> help(8)

Help on int object:


class int(object)

| int(x[, base]) -> integer

|

| Convert a string or number to an integer, if

| possible. A floating point argument will be

| truncated towards zero (this does not include a

| string representation of a floating point

| number!) When converting a string, use

| the optional base. It is an error to supply a Effective Python Programming OSCON 2005
dir


>>> import popen2

>>> dir(popen2)

['MAXFD', 'Popen3', 'Popen4', '__all__',
'__builtins__', '__doc__', '__file__', '__name__',
'_active', '_cleanup', '_test', 'os', 'popen2',
'popen3', 'popen4', 'sys']
Effective Python Programming OSCON 2005
Everything is an object ints, strings, files functions, modules, classes Variables are just labels Effective Python Programming OSCON 2005
Objects vs Names Variables are references Just a name referring to an object Stored in a namespace

(defaults to the local namespace) Effective Python Programming OSCON 2005
Namespaces... Namespaces are dictionaries!

>>> import sys

>>> def foo(a=1, b=2):

... c = "hello"

... print sys._getframe().f_locals

...

>>>

>>> foo(a=4)

{'a': 4, 'c': 'hello', 'b': 2}
Effective Python Programming OSCON 2005
Namespace lookup Classic locals module globals built-ins Effective Python Programming OSCON 2005
Assignment Assignment goes to local namespace Unless 'global' statement Effective Python Programming OSCON 2005
global global only for assignment not needed for getting a value globals are slower! Effective Python Programming OSCON 2005
Namespaces nested scopes statically nested scopes

(nested function definitions) useful for lambda:

def createUpdater(self):

return lambda foo, bar: self.update(foo,bar) nested function calls

example later of this Effective Python Programming OSCON 2005
EAFP Easier to Ask Forgiveness than
Permission Very basic Python concept Effective Python Programming OSCON 2005
Permission... Permission:

if hasattr(obj, 'value'):

value = obj.value

else:

value = None Forgiveness:

try:

read = obj.value

except AttributeError:

value = None Effective Python Programming OSCON 2005
EAFP Exceptions are expensive Checks can also be expensive Case-by-case how often is it expected
to fail? Effective Python Programming OSCON 2005
Python Typing Weak vs Strong Static vs Dynamic C++/Java: strong static typing Python: strong dynamic typing Effective Python Programming OSCON 2005
Duck-Typing Walks like a duck ... quacks like a duck ... it's a duck Effective Python Programming OSCON 2005
Duck-Typing File-like objects Might only need 'read()' Effective Python Programming OSCON 2005
Duck-Typing File objects

def getData(obj):

data = obj.read()

print data

f = open('file.txt')

getData(f)
Actually, that data file was gzipped:

import gzip

f = gzip.GzipFile('file.txt.gz')

getData(f)



Effective Python Programming OSCON 2005
More Duck-Typing The mapping interface (dictionary) Start with a dictionary Slot in a different implementation e.g. network, database, ... Effective Python Programming OSCON 2005
Interfaces zope.interface PyProtocols Assert that an object implements an
interface Documentation Adaptation Future Python Effective Python Programming OSCON 2005
Structured Programming Effective Python Programming OSCON 2005
Control Flow Iterators Generators for/else try/finally try/except/else switch statement Effective Python Programming OSCON 2005
S.A.S. Theatre! enumerate

for n in range(len(sequence)):

element = sequence[n] instead:

for n, element in enumerate(sequence): enumerate returns an iterator

>>> print enumerate([])

<enumerate object at 0xb7df418c>
Effective Python Programming OSCON 2005
Basic control flow while for try/except Effective Python Programming OSCON 2005
Iterators Returns the next item each time No need to have all items in memory More flexible Effective Python Programming OSCON 2005
Files are iterators Returns a line

>>> for line in open('/etc/resolv.conf'):

... print "got line '%s'"%(line.strip())

...

got line 'nameserver 210.15.254.240'

got line 'nameserver 210.15.254.241'

got line 'nameserver 203.10.110.101'

got line 'nameserver 203.17.103.1'
Effective Python Programming OSCON 2005
Creating iterators iter() built-in turns a sequence into an iterator classes can have an __iter__ method
that returns an iterator Effective Python Programming OSCON 2005
More flexible for loops Call .next() to get the next item


iterobj = iter(sequence)

for item in iterobj:

if item == 'extended':

item = item + iterobj.next()
Effective Python Programming OSCON 2005
Token streams

tokens=['text:hello','style:bold','text:world',
'text:goodbye','style:italic','text:world']

tokens = iter(tokens)

for tok in tokens:

what,value = tok.split(':',1)

if what == 'text':

handlePlainToken(value)

elif what == 'style':

what, value = tok.next().split(':', 1)

if style == 'bold':

handleBoldToken(value)

elif style == 'italic':

handleItalicToken(value) Effective Python Programming OSCON 2005
Push Iterator Sometimes you want to check the next
item, but not always consume it Push it back onto the iterator! Like stdio's getc()/ungetc() Effective Pytho