[Numpy-discussion] Exception handling in ufuncs

Bock, Oliver BGI SYD Oliver.Bock@barclaysglobal....
Mon Nov 19 20:42:30 CST 2007

Is it possible to trap non-floating point exceptions?  For example, I
store strings in ndarrays as objects, but I would like the result of
invalid operations to be None.

from numpy import *
a = array(["a", "b"], dtype=object)
b = array(["A", None], dtype=object)
print a + b
Traceback (most recent call last):
  File "C:\workspace\AlphaExplorer\ae1\test\_fiddle.py", line 225, in ?
    print a + b
TypeError: cannot concatenate 'str' and 'NoneType' objects

I have tried seterr() and seterrcall(), but these are not triggered
(which did not surprise me because the documentation says they are used
for floating point exceptions).

Of course I can always write my own ufunc, but if a better way exists...

def f(a, b):
    if a is None or b is None:
        return None
    return a + b
print vectorize(f, otypes=[object])(a, b) 
This message and any attachments are confidential, proprietary, and may be privileged.  If this message was misdirected, Barclays Global Investors (BGI) does not waive any confidentiality or privilege.  If you are not the intended recipient, please notify us immediately and destroy the message without disclosing its contents to anyone.  Any distribution, use or copying of this e-mail or the information it contains by other than an intended recipient is unauthorized.  The views and opinions expressed in this e-mail message are the author's own and may not reflect the views and opinions of BGI, unless the author is authorized by BGI to express such views or opinions on its behalf.  All email sent to or from this address is subject to electronic storage and review by BGI.  Although BGI operates anti-virus programs, it does not accept responsibility for any damage whatsoever caused by viruses being passed.

More information about the Numpy-discussion mailing list