Files
RustPython/extra_tests/snippets/stdlib_struct_complex.py
T
Kwak Byoung Min 5f18b9cd56 Support Python 3.14 complex values in struct formats (#8829)
Accept F/D through the existing buffer packing implementation and restore
its complex round-trip test. Fix exact __complex__ results warning as
subclasses so valid conversions also work with warnings treated as errors.

Codex assisted with implementation, regression coverage, and review.

Tested: CPython 3.14.7 comparison; struct/memoryview/complex/cmath; workspace and C-API tests; Clippy; pytest; prek
Assisted-by: Codex:gpt-6-astra
2026-09-26 22:57:24 +09:00

31 lines
863 B
Python

import struct
import sys
import warnings
from testutils import assert_raises
class ComplexLike:
def __complex__(self):
return 1 + 2j
class ComplexSubclass(complex):
def __complex__(self):
raise AssertionError("complex subclasses use their stored value")
with warnings.catch_warnings():
warnings.simplefilter("error")
for code in ("F", "D"):
expected = struct.pack(code, 1 + 2j)
assert struct.pack(code, ComplexLike()) == expected
assert struct.pack(code, ComplexSubclass(1, 2)) == expected
native = "<" if sys.byteorder == "little" else ">"
swapped = ">" if sys.byteorder == "little" else "<"
for value in (complex(1e300, 0), complex(0, 1e300)):
assert struct.pack(native + "F", value) == struct.pack("@F", value)
with assert_raises(OverflowError):
struct.pack(swapped + "F", value)