[struct] Add struct.pack and struct.unpack polyfills (#156977)

Pull Request resolved: https://github.com/pytorch/pytorch/pull/156977
Approved by: https://github.com/XuehaiPan, https://github.com/jansel
ghstack dependencies: #156975
This commit is contained in:
Guilherme Leobas
2025-07-22 14:32:04 -03:00
committed by PyTorch MergeBot
parent 671e22a951
commit f5314f89c8
14 changed files with 29 additions and 0 deletions

View File

@ -30,6 +30,7 @@ if TYPE_CHECKING:
operator as operator,
os as os,
pytree as pytree,
struct as struct,
sys as sys,
)

View File

@ -19,6 +19,7 @@ POLYFILLED_MODULE_NAMES: tuple[str, ...] = (
"operator",
"os",
"pytree",
"struct",
"sys",
"fx",
"tensor",

View File

@ -0,0 +1,27 @@
"""
Python polyfills for struct
"""
from __future__ import annotations
import struct
from typing import Any
from typing_extensions import Buffer
from ..decorators import substitute_in_graph
__all__ = [
"pack",
"unpack",
]
@substitute_in_graph(struct.pack, can_constant_fold_through=True) # type: ignore[arg-type]
def pack(fmt: bytes | str, /, *v: Any) -> bytes:
return struct.pack(fmt, *v)
@substitute_in_graph(struct.unpack, can_constant_fold_through=True) # type: ignore[arg-type]
def unpack(format: bytes | str, buffer: Buffer, /) -> tuple[Any, ...]:
return struct.unpack(format, buffer)