Re: pickle and infinity



On 2006-11-29, Bart Ogryczak <B.Ogryczak@xxxxxxxxx> 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
.



Relevant Pages

  • pickling objects in jython
    ... The following sample code is to pickle and unpickle an object. ... but the unpickling fails in Jython and I receive an error stating that "A" is unsafe to unpickle. ...
    (comp.lang.python)
  • Pickling object inherited from dict
    ... If I pickle a class which inherits from dict, ... I don't get the same data again, if I unpickle ... def test_pickle: ...
    (comp.lang.python)