Message 102245 - Python tracker (original) (raw)

In Python 2.7, struct.pack with an integer format can handle non-integers that provide an int method (although this does raise a DeprecationWarning).

Python 2.7a4+ (trunk:79659:79661, Apr 3 2010, 11:28:19) [GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin Type "help", "copyright", "credits" or "license" for more information.

from struct import pack [35194 refs] pack('L', 3.1415) '\x03\x00\x00\x00\x00\x00\x00\x00' [35210 refs]

This behaviour isn't particularly desirable for floats or Decimal instances, but it's useful for integer-like objects.

In Python 3.x, there's no provision for handling integer-like objects than aren't actually integers.

I propose that in 3.x, struct.pack should try to convert any non-integer to an integer by using its index method, before packing.