# Listing 1: Überladen der Print-Funktion import sys def print(*args,sep='',end="\n",file=sys.stdout): __builtins__.print(*args) __builtins__.print(*args,file=open("log.file","a")) # Listing 2: With-Block mit Datei with open('/etc/passwd', 'r') as file: for line in file: print line, # file is closed # Listing 3: Schutz eines Code-Blocks with locked(myLock): # Code here executes with myLock held. The lock is # guaranteed to be released when the block is left class locked: def __init__(self, lock): self.lock = lock def __enter__(self): self.lock.acquire() def __exit__(self, type, value, tb): self.lock.release() # Listing 4: Import-Idiom try: import cPickle as pickle except ImportError: import pickle # Listing 5: Zu portierender Code print "sum of the integers: " , apply(lambda a,b,c: a+b+c , (2,3,4)) print "factorial of 10 :", reduce(lambda x,y: x*y, range(1,11) ) print "titles in text: ", filter( lambda word: word.istitle(),"This is a long Test".split()) print "titles in text: ", [ word for word in "This is a long Test".split() if word.istitle()] # Listing 6: Behebung der Deprecation-Warnung print "sum of the integers: " , (lambda a,b,c: a+b+c)(*(2,3,4)) import functools print "factorial of 10 :", functools.reduce(lambda x,y: x*y, range(1,11) ) print "titles in text: ", filter( lambda word: word.istitle(),"This is a long Test".split()) print "titles in text: ", [ word for word in "This is a long Test".split() if word.istitle()] # Listing 7: Nach Python 3.0 portierter Code print("sum of the integers: " , (lambda a,b,c: a+b+c)(*(2,3,4))) print("factorial of 10 :", reduce(lambda x,y: x*y, list(range(1,11)) )) print("titles in text: ", [word for word in "This is a long Test".split() if word.istitle()]) print("titles in text: ", [ word for word in "This is a long Test".split() if word.istitle()])