[New-bugs-announce] [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)
[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>

More information about the New-bugs-announce mailing list