[Python-Dev] struct module and coercing floats to integers

Michael Urman murman at gmail.com
Sat Jul 29 05:14:58 CEST 2006


On 7/28/06, Bob Ippolito <bob at redivi.com> wrote:
> http://python.org/sf/1530559
>
> [1] 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.).

While it may be a bug, it's not as hard to run into, nor as illogical
as the presentation here makes it sound. The original code[1] took a
float value between 0 and 2, and wanted to use
    pack('>H', round(value * 32768))
The workaround is a trivial change
    pack('>H', int(round(value * 32768)))
but the timeframe is less than ideal, as working code will suddenly
stop and recieve only mildly helpful error message. The fact that
round returns a float rather than an int, while intentional, does not
feature prominently in one's mine when the first version yielded the
expected results.

I would appreciate option 2 which retains compatibility but warns that
the construct is bad. I will accept any of the options, as it's clear
that floats don't make sense. It's just unfortunate that the previous
implementation let them through in a way the new implementation does
not.

[1] http://www.sacredchao.net/quodlibet/changeset/3706

Michael
-- 
Michael Urman  http://www.tortall.net/mu/blog


More information about the Python-Dev mailing list