How to catch exceptions elegantly in this situation?

Jeremy Bowers jerf at jerf.org
Fri Oct 8 02:31:44 EDT 2004


On Thu, 07 Oct 2004 20:13:06 -0700, Saqib Ali wrote:

> Check out the following code fragment
> 
> Line  1: myDict = {}
> Line  2: a = 5
> Line  3: b = 2
> Line  4: c = 0
> Line  5: myDict["A"] = a + b + c
> Line  6: myDict["B"] = a - b - c
> Line  7: myDict["C"] = a * b * c
> Line  8: myDict["D"] = a / b / c
> Line  9: myDict["E"] = a ** b ** c
> Line 10: ...<etc>...
> Line 11: ...<etc>...
> Line 12: ...<etc>...

Can you give me more detail? What is the real problem?

For example, for the code you give above, I think I would do:

import operator
myDict = {}
a = 5
b = 2
c = 0

def doOp(key, op):
    try:
        tmp = op(a, b)
        myDict[key] = op(tmp, c)
    except: # probably ought to narrow this down
        pass

for key, op in (("A", operator.add), ("B", operator.sub),
                ("C", operator.mul), ("D", operator.div),
                ("E", operator.pow)):
    doOp(key, op)


but with a better idea of the problem domain I may be able to be more
helpful.

Of course, this may start you on the path to a better idea.

Another, more generic possibility is to wrap your operations in a
function, or a lambda, and pass them in to some object to be evaluated in
a safe context. Depending on the domain, you may find a clever way to
collapse the problem so it isn't so cumbersome. For my solution, I'm
expecting that "...<etc>..." represents many more lines.

Oh, and unofficially, I recommend either "import operator as op" or "from
operator import *". But you didn't hear that from me. (I find I'm slightly
less "import *" phobic than many around here, if the module is a vital
part of the flow of the code and net-net, the repeated invocation of the
module name impedes reading the code. In the above fragment, I think
"operator." meets that standard. If this were a small part of a large
module, I wouldn't do it.)



More information about the Python-list mailing list