[Numpy-discussion] numpy error handling
Tim Hochberg
tim.hochberg at cox.net
Sun Apr 2 08:41:24 EDT 2006
Rob Hooft wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Travis Oliphant wrote:
> | save = numpy.seterr(dividebyzero='warn')
> |
> | ...
> |
> | numpy.seterr(restore=save)
>
> Most of this discussion is outside of my scope, but I have programmed
> this kind of pattern in a different way before:
>
> ~ save = context.push(something)
> ~ ...
> ~ del save
>
> i.e. the destructor of the saved context object restores the old
> situation. In most cases it will be called by letting "save" go out of
> scope. I know that relying on timely object destruction can be
> troublesome when porting to Jython, but it is very convenient in CPython.
>
> If that goes too far, one could make a separate method on save:
>
> ~ save.pop()
>
> This can do sanity checking too (are we really at the top of the stack?
> Only called once?). The destructor should check whether pop has been
> called.
Well, the syntax that *I* really want is this:
class error_mode(object):
def __init__(self, all=None, overflow=None, underflow=None,
dividebyzero=None, invalid=None):
self._args = (overflow, overflow, underflow, dividebyzero,
invalid)
def __enter__(self):
self._save = numpy.seterr(*self._args)
def __exit__(self):
numpy.seterr(self._save)
That way, in a few months, I can do this:
with error_mode(overflow='raise'):
# do stuff
and it will be almost impossible to mess up. This syntax is lighter and
cleaner than a stack or relying on garbage collection to free the
resources. So, for my purposes, the simple syntax Travis proposes is
perfectly adequate and simpler to implement and get right than a stack
based approach. If 'with' wasn't coming down the pipe, I would push for
a stack, but I like Travis' proposal just fine.
YMMV of course.
-tim
More information about the NumPy-Discussion
mailing list