Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python throws TypeError on issubclass() when issubclass() is never called

I have a piece of code that runs perfectly most of the time, but every once in awhile I get this error in the traceback:

File "/path/to/somefile.py", line 272, in somefile
    sm = -0.5 * (wv[0]**2. / sm2 + numpy.log(2. * numpy.pi * sm2))
TypeError: issubclass() arg 2 must be a class or tuple of classes

I know what issubclass() does and understand the error, but I never called it; that line in the code is pure arithmetic, so I don't know why this TypeError is raised in the first place. My only theory is that Numpy is calling it behind the scenes, but then the traceback should show the problematic line in the Numpy source, right? What's going on?

Updates:

wv is an array of floats and sm2 is a float scalar. The error is actually thrown by numpy.log, i.e. the (new) line

tmp = numpy.log(2. * numpy.pi * sm2)

No more information is provided in the error message, though.

More updates:

My current version of Numpy (from a Python prompt):

>>> import numpy
>>> numpy.__version__
'1.6.2'

I changed the problem line to

try:
    tmp = numpy.log(2. * numpy.pi * sm2)
except TypeError:
    print type(sm2), 2. * numpy.pi * sm2

and got the output

<type 'numpy.float64'> 0.0

So it makes sense that there would be some kind of error, but if I do this (at a Python prompt)

>>> import numpy
>>> numpy.log(0.)

I get the error I would expect (and am already handling in the code in question, via the warning module):

__main__:1: RuntimeWarning: divide by zero encountered in log
-inf
like image 951
emprice Avatar asked Jan 02 '13 19:01

emprice


1 Answers

This was an error in my code after all... As @seberg points out, this code works normally:

>>> import numpy
>>> import warnings
>>> numpy.log(0.)
__main__:1: RuntimeWarning: divide by zero encountered in log
-inf
>>> warnings.simplefilter("error", RuntimeWarning)    # not "RuntimeWarning"
>>> try:
...     numpy.log(0.)
... except RuntimeWarning:
...     print "caught"
...
caught

numpy.seterr provides an alternative to handling RuntimeWarning this way, though:

>>> import numpy
>>> numpy.seterr(all='raise')
{'over': 'warn', 'divide': 'warn', 'invalid': 'warn', 'under': 'ignore'}
>>> try:
...     numpy.log(0.)
... except FloatingPointError:
...     print "caught"
... 
caught

Either way, it works, though Python really should throw some kind of exception for passing a string instead of a class to warnings.simplefilter.

like image 63
emprice Avatar answered Oct 05 '22 09:10

emprice