Online Book Reader

Home Category

Learning Python - Mark Lutz [598]

By Root 1655 0


The Dead Parrot Sketch. Here’s how I implemented this one (file parrot.py). Notice how the line method in the Actor superclass works: by accessing self attributes twice, it sends Python back to the instance twice, and hence invokes two inheritance searches—self.name and self.says() find information in the specific subclasses:class Actor:

def line(self): print(self.name + ':', repr(self.says()))

class Customer(Actor):

name = 'customer'

def says(self): return "that's one ex-bird!"

class Clerk(Actor):

name = 'clerk'

def says(self): return "no it isn't..."

class Parrot(Actor):

name = 'parrot'

def says(self): return None

class Scene:

def __init__(self):

self.clerk = Clerk() # Embed some instances

self.customer = Customer() # Scene is a composite

self.subject = Parrot()

def action(self):

self.customer.line() # Delegate to embedded

self.clerk.line()

self.subject.line()

Part VII, Exceptions and Tools

See Test Your Knowledge: Part VII Exercises in Chapter 35 for the exercises.

try/except. My version of the oops function (file oops.py) follows. As for the noncoding questions, changing oops to raise a KeyError instead of an IndexError means that the try handler won’t catch the exception (it “percolates” to the top level and triggers Python’s default error message). The names KeyError and IndexError come from the outermost built-in names scope. Import builtins (__builtin__ in Python 2.6) and pass it as an argument to the dir function to see for yourself:def oops():

raise IndexError()

def doomed():

try:

oops()

except IndexError:

print('caught an index error!')

else:

print('no error caught...')

if __name__ == '__main__': doomed()

% python oops.py

caught an index error!

Exception objects and lists. Here’s the way I extended this module for an exception of my own:class MyError(Exception): pass

def oops():

raise MyError('Spam!')

def doomed():

try:

oops()

except IndexError:

print('caught an index error!')

except MyError as data:

print('caught error:', MyError, data)

else:

print('no error caught...')

if __name__ == '__main__':

doomed()

% python oops.py

caught error: Spam!

Like all class exceptions, the instance comes back as the extra data; the error message shows both the class (<...>) and its instance (Spam!). The instance must be inheriting both an __init__ and a __repr__ or __str__ from Python’s Exception class, or it would print like the class does. See Chapter 34 for details on how this works in built-in exception classes.

Error handling. Here’s one way to solve this one (file safe2.py). I did my tests in a file, rather than interactively, but the results are about the same.import sys, traceback

def safe(entry, *args):

try:

entry(*args) # Catch everything else

except:

traceback.print_exc()

print('Got', sys.exc_info()[0], sys.exc_info()[1])

import oops

safe(oops.oops)

% python safe2.py

Traceback (innermost last):

File "safe2.py", line 5, in safe

entry(*args) # Catch everything else

File "oops.py", line 4, in oops

raise MyError, 'world'

hello: world

Got hello world

Here are a few examples for you to study as time allows; for more, see follow-up books and the Web:# Find the largest Python source file in a single directory

import os, glob

dirname = r'C:\Python30\Lib'

allsizes = []

allpy = glob.glob(dirname + os.sep + '*.py')

for filename in allpy:

filesize = os.path.getsize(filename)

allsizes.append((filesize, filename))

allsizes.sort()

print(allsizes[:2])

print(allsizes[-2:])

# Find the largest Python source file in an entire directory tree

import sys, os, pprint

if sys.platform[:3] == 'win':

dirname = r'C:\Python30\Lib'

else:

dirname = '/usr/lib/python'

allsizes = []

for (thisDir, subsHere, filesHere) in os.walk(dirname):

for filename in filesHere:

if filename.endswith('.py'):

fullname = os.path.join(thisDir, filename)

fullsize = os.path.getsize(fullname)

allsizes.append((fullsize, fullname))

allsizes.sort()

pprint.pprint(allsizes[:2])

pprint.pprint(allsizes[-2:])

Return Main Page Previous Page Next Page

®Online Book Reader