Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

struct.pack error messages are misleading and inconsistent #98248

Labels
type-bug An unexpected behavior, bug, or error

Comments

Copy link
Contributor

Oct 13, 2022

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

type-bug An unexpected behavior, bug, or error label Oct 13, 2022
mdickinson pushed a commit that referenced this issue Dec 4, 2022
…98252)

Provide consistent and informative error messages in function struct.pack when its integral arguments are not in range.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type-bug An unexpected behavior, bug, or error
Projects
None yet
Development

No branches or pull requests

1 participant