struct.pack oddity

Larry Bates lbates at websafe.com
Tue Mar 13 14:02:48 EDT 2007


Erik Johnson wrote:
> "Dave Opstad" <dave.opstad at monotypeimaging.com> wrote in message
> news:45f6bd4a$0$6972$afc38c87 at ...
>> Is the lack of a struct.error when the byte-order mark is at the start
>> of the format intentional? This seems like a bug to me, but maybe
>> there's a subtlety here I'm not seeing.
> 
>     I am by no means any sort of expert on this module, but for what it's
> worth, the behaviour is basically the same for my Python 2.4.3 under Cygwin
> (except that there is no deprecation warning) and I agree with you: this
> seems like a bug to me. Or maybe not technically a bug, but the behaviour
> could be improved. I would expect to get the same struct.error in all three
> cases:
> 
> $ python
> Python 2.4.3 (#1, May 18 2006, 07:40:45)
> [GCC 3.3.3 (cygwin special)] on cygwin
> Type "help", "copyright", "credits" or "license" for more information.
>>>> from struct import *
>>>> pack('H', 100000)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> struct.error: short format requires 0<=number<=USHRT_MAX
>>>> pack('>H', 100000)
> '\x86\xa0'
>>>> pack('<H', 100000)
> '\xa0\x86'
> 
>     There used to be a form at the bottom left of the main site:
> www.python.org for reporting bugs, but that now seems to be used only for
> reporting stuff about the web site itself.  The struct module comes from
> struct.dll, so I can't see any comments about who wrote or maintains that
> module.
> 
>     Barring anyone else disagreeing with classifying it as a bug, I would
> suggest reporting it. Proper procedure for reporting a bug appears to be
> covered in section B of the Python Library Reference:
> http://docs.python.org/lib/reporting-bugs.html
> 
> Hope that helps,
> -ej
> 
> 
It looks like you have multiple "issues".

1) You can't put 100000 into a half-word.  The limit is 2**16
or 65535. On Python 2.5 I get:

>>> struct.pack('H', 100000)
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "C:\Python25\lib\struct.py", line 63, in pack
    return o.pack(*args)
error: short format requires 0 <= number <= USHRT_MAX
>>> struct.pack('H', 65535)
'\xff\xff'
>>> struct.pack('>H', 100000)
C:\Python25\Lib\struct.py:63: DeprecationWarning: 'H' format requires 0 <=
number <= 65535
  return o.pack(*args)
'\x86\xa0'
>>> struct.pack('<H', 100000)
'\xa0\x86'
>>>

On the last try, struct.pack('<H', 100000) I would classify
that as an oversight/bug but its not something that you should
be trying to do because it doesn't make sense anyway.

-Larry



More information about the Python-list mailing list