[issue8300] Allow struct.pack to handle objects with an __index__ method.

Mark Dickinson report at bugs.python.org
Sat Apr 3 13:51:47 CEST 2010


New submission from Mark Dickinson <dickinsm at gmail.com>:

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.

----------
assignee: mark.dickinson
messages: 102245
nosy: mark.dickinson
severity: normal
status: open
title: Allow struct.pack to handle objects with an __index__ method.
versions: Python 3.2

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue8300>
_______________________________________


More information about the Python-bugs-list mailing list