[Python-Dev] struct module and coercing floats to integers
bob at redivi.com
Fri Jul 28 22:35:40 CEST 2006
It seems that the pre-2.5 struct module has some additional
undocumented behavior that didn't percolate into the new version:
Python 2.4 and previous will coerce floats to integers when necessary
as such without any kind of complaint:
$ python2.4 -c "import struct; print repr(struct.pack('>H',
Python 2.5 refuses to coerce float to int:
$ python2.5 -c "import struct; print repr(struct.pack('>H',
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/Users/bob/src/python/Lib/struct.py", line 63, in pack
TypeError: unsupported operand type(s) for &: 'float' and 'long'
The available options are to:
1. Reinstate the pre-2.5 weirdness
2. Reinstate the pre-2.5 weirdness with a DeprecationWarning
3. Break existing code that relies on undocumented behavior (seems
more like a bug than lack of specification)
Either 2 or 3 seems reasonable to me, with a preference for 3 because
none of my code depends on old bugs in the struct module :)
As far as precedent goes, the array module *used* to coerce floats
silently, but it's had a DeprecationWarning since at least Python 2.3
(but perhaps even earlier). Maybe it's time to promote that warning
to an exception for Python 2.5?
 The pre-2.5 behavior should really be considered a bug, the
documentation says "Return a string containing the values v1, v2, ...
packed according to the given format. The arguments must match the
values required by the format exactly." I wouldn't consider arbitrary
floating point numbers to match the value required by an integer
format exactly. Floats are not in general interchangeable with
integers in Python anyway (e.g. list indexes, etc.).
More information about the Python-Dev