Accept the format keyword in Struct initialization (#9064)

Keep the existing conversion and initialization path while binding format as positional-or-keyword, matching Python 3.14.

Assisted-by: OpenAI Codex:model identifier unavailable
This commit is contained in:
youknowdot authored and GitHub committed 2026-10-10 19:31:54 +00:00
1 parent 92204385cd
commit 1ff5bbd920
2 files changed
+28 -3

No files matched your search

+10 -3
View File
@@ -289,10 +289,17 @@ pub(crate) mod _struct {
}
}
impl Initializer for PyStruct {
type Args = IntoStructFormatBytes;
#[derive(FromArgs)]
struct StructArgs {
#[pyarg(any)]
format: IntoStructFormatBytes,
}
fn init(zelf: &Py<Self>, fmt: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
impl Initializer for PyStruct {
type Args = StructArgs;
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
let fmt = args.format;
// The format is read before anything is replaced, so a format that
// cannot be read leaves the object as it was.
let spec = fmt.format_spec(vm)?;
+18
View File
@@ -184,3 +184,21 @@ assert struct.pack("<H", ClearFormats()) == b"\x2a\x00"
buffer = bytearray(2)
struct.pack_into("<H", buffer, 0, ClearFormats())
assert buffer == b"\x2a\x00"
# Struct's format is positional-or-keyword, including inherited initialization.
class KeywordStruct(struct.Struct):
pass
for cls in (struct.Struct, KeywordStruct):
for fmt in (">h", b">h"):
s = cls(format=fmt)
assert s.format == ">h"
assert s.pack(7) == b"\x00\x07"
s.__init__(format=">hh")
assert s.unpack(b"\x00\x01\x00\x02") == (1, 2)
with assert_raises(struct.error):
s.__init__(format="$")
assert s.format == ">hh"
assert s.pack(1, 2) == b"\x00\x01\x00\x02"