Phase objects: simple decent error reporting for Python programsFor a lot of the sort of utility programs I write in Python, the only thing the program can really do when it runs into an operating system level error is report whatever the problem is and exit. So programs start out as one big try:/except: block:
The problem with this is that the error reported, while accurate, is basically without context; you don't know what the program was doing when it reported 'permission denied' or whatever. So simple programs mutate slightly to keep track of what they are doing in a variable:
(Well, my simple programs do, since I have no desire to wrap each separate operation that might fail in its own try:/except: block. That's too much work.) The problem with this approach is that it doesn't work very well when
your program grows subroutines, because updating a global variable to
track the phase is a pain. The solution I have adopted is to create a
special class to track what phase of execution the program is in; with
my typical (lack of) imagination, I call this class
class Phase(object):
def __init__(self):
self.phase = ["starting",]
def __call__(self, ph):
self.phase = [ph, ]
def __str__(self):
return ": ".join(self.phase)
def push(self, ph):
self.phase.append(ph)
def pop(self):
self.phase.pop()
It is used as My programs just make a single global (4 comments.)
|
These are my WanderingThoughts GettingAround This is part of CSpace, and is written by ChrisSiebenmann. * * * Atom feeds are available; see the bottom of most pages. Categories: links, linux, programming, python, snark, solaris, spam, sysadmin, tech, unix, web |