A struct for 2.4 that supports float's inf and nan?

Paul Hankin paul.hankin at gmail.com
Thu Sep 20 15:19:49 EDT 2007


On Sep 19, 9:58 pm, "Joshua J. Kugler" <jos... at eeinternet.com> wrote:
> I'm trying to put some values into a struct.  Some of these values are NaN
> and Inf due to the nature of the data.  As you well may know, struct (and
> other things) in Python <= 2.4 doesn't support inf and nan float values.
> You get the dreaded "SystemError: frexp() result out of range" error.
>
> Before I go and write my own little wrapper, has anyone out there written
> an "extended" struct that supports the inf and nan values?  I know this is
> fixed in 2.5, but using that isn't an option at this point, as users will
> be running older versions of python.
>
> I suppose I could get the relevant source from the 2.5 source and compile it
> as a custom package, but that wouldn't be very transparent for my users,
> and would probably be getting in way over my head. :)
>
> Ideas?  Suggestions?

Here's a wrapped pack:

import struct

pack_double_workaround = {
  'inf': struct.pack('Q', 0x7ff0000000000000L),
  '-inf': struct.pack('Q', 0xfff0000000000000L),
  'nan': struct.pack('Q', 0x7ff8000000000000L)
}

def pack_one_safe(f, a):
  if f == 'd' and str(f) in pack_double_workaround:
      return pack_double_workaround[str(f)]
  return struct.pack(f, a)

def pack(fmt, *args):
  return ''.join(pack_one_safe(f, a) for f, a in zip(fmt, args))

Unpacking is similar: unpack doubles with 'Q' and test the
long for equality with +-inf, and find nan's by checking bits
52 to 62. If the number's ok, unpack again using 'd'.

You can get python values for nan, -inf and inf by using
float('nan'), float('-inf'), float('inf').

I've not been able to properly test this, as struct seems
to work fine in Python 2.3 and 2.4 on MacOS X.

HTH
--
Paul Hankin




More information about the Python-list mailing list