Testing whether imported function failed

Robert Brewer fumanchu at amor.org
Tue Jun 8 12:46:49 EDT 2004


brianc at temple.edu wrote:
> I have to make a lot of calls to a C++ library binded to python. 
> The problem is that the functions/methods don't raise
> exceptions when they fail to do their job. Instead they return
> a 0 for a failure and a 1 for a successful completion.
> >>> do_something(object)
> 1
> >>> do_something(object)
> 0
> 
> I spent two days tracking down a bug that could have easily
> been found if the call loudly failed. Is there anyway to
> blanket test this integer 1/0 output so I can catch these
> errors before they become untraceable?

If *all* the functions have that behavior, you can wrap the C module
with another module easily. For example, given a simple module clib.py:

def do_something(obj):
    if obj:
        return 1
    else:
        return 0

...you can wrap it with another module (clibwrap.py) like this:

import clib

class LoudException(Exception): pass

def wrap(func):
    def wrapper(*args, **kwargs):
        success = func(*args, **kwargs)
        if not success:
            raise LoudException
    return wrapper

for name in dir(clib):
    func = getattr(clib, name)
    globals()[name] = wrap(func)

del func

...then in client code, write:

>>> import clibwrap
>>> clibwrap.do_something(1)
>>> clibwrap.do_something(0)
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "C:\Python23\Lib\site-packages\clibwrap.py", line 9, in wrapper
    raise LoudException
LoudException


If not every function in the original module has the 1/0 behavior, you
can do it selectively rather than generically in clibwrap.py.

Hope that helps!


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org




More information about the Python-list mailing list