pickle and infinity

Grant Edwards grante at visi.com
Wed Nov 29 12:32:37 EST 2006


On 2006-11-29, Bart Ogryczak <B.Ogryczak at gmail.com> wrote:

> I´ve got this problem with pickle, it seems it doesn´t handle
> correctly infinite values (nor does Python return
> overflow/underflow error). What could I do about it?

Here's what I did.  I'm sure it'll fall down on some systems,
but it works on Linux and Windows.

______________________________________________________________________
# unpickle can't handle nan/inf/ind floats, so we need to
# handle that ourselves

def myload_float(self):
    s = self.readline()[:-1]
    try:
        f = float(s)
    except ValueError:
        s = s.upper()
        if s in ["1.#INF", "INF"]:
            f = 1e300*1e300
        elif s in ["-1.#INF", "-INF"]:
            f = -1e300*1e300
        elif s in ["NAN","1.#QNAN","-1.#QNAN","QNAN","1.#IND","IND","-1.#IND"]:
            f = (1e300*1e300)/(1e300*1e300)
        else:
            raise ValueError, "Don't know what to do with "+`s`
    self.append(f)

# unpickle routine that overrides the float load method
    
def unpickle(f):
    unpickler = pickle.Unpickler(f)
    unpickler.dispatch[pickle.FLOAT] = myload_float
    return unpickler.load()
______________________________________________________________________

-- 
Grant Edwards                   grante             Yow!  I represent a
                                  at               sardine!!
                               visi.com            



More information about the Python-list mailing list