Skip to content

struct.pack error messages are misleading and inconsistent #98248

Closed
@yanjs

Description

@yanjs

Bug report

1. Misleading error message

>>> import struct
>>> struct.pack(">Q", -1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
struct.error: int too large to convert

I don't think -1 is that large to convert to ulonglong, so the error message is wrong. The problem is that -1 is not in the range of ulonglong. The current error message is not helpful for users to debug.

Compared to other error messages:

Code

import struct
for endianness in "<>":
    for size in "BHILQ":
        try:
            fmt = endianness + size
            struct.pack(fmt, -1)
        except struct.error as e:
            print("Error msg of " + fmt + ":", e)

stdout

Error msg of <B: ubyte format requires 0 <= number <= 255
Error msg of <H: ushort format requires 0 <= number <= 65535
Error msg of <I: argument out of range
Error msg of <L: argument out of range
Error msg of <Q: argument out of range
Error msg of >B: ubyte format requires 0 <= number <= 255
Error msg of >H: argument out of range
Error msg of >I: argument out of range
Error msg of >L: argument out of range
Error msg of >Q: int too large to convert

2. Inconsistent error messages when packing into different integral types

See the output above.

A possible solution

I can create a PR to fix the 1st problem. For the 2nd problem, #28178 (comment) and #89197 (comment) said that the inconsistency can be fixed, so I can probably fix this in the same PR.

Your environment

  • CPython versions tested on: Python 3.12.0a0 (heads/main:ccab67b, Oct 12 2022, 15:25:20) [GCC 12.2.0] on linux
  • Operating system and architecture: Arch Linux 5.19.13.arch1-1, x86-64
  • Native endianness: Little-endian

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions