:mod:`struct` --- Interpret bytes as packed binary data
=======================================================
+.. testsetup:: *
+
+ from struct import *
+
.. module:: struct
:synopsis: Interpret bytes as packed binary data.
The calculated size of the struct (and hence of the bytes object produced
by the :meth:`pack` method) corresponding to :attr:`format`.
+ .. versionchanged:: 3.13 The *repr()* of structs has changed. It
+ is now:
+
+ >>> Struct('i')
+ Struct('i')
.. _half precision format: https://en.wikipedia.org/wiki/Half-precision_floating-point_format
test_error_propagation('N')
test_error_propagation('n')
+ def test_repr(self):
+ s = struct.Struct('=i2H')
+ self.assertEqual(repr(s), f'Struct({s.format!r})')
+
class UnpackIteratorTest(unittest.TestCase):
"""
Tests for iterative unpacking (struct.Struct.iter_unpack).
return PyLong_FromSize_t(size);
}
+static PyObject *
+s_repr(PyStructObject *self)
+{
+ PyObject* fmt = PyUnicode_FromStringAndSize(
+ PyBytes_AS_STRING(self->s_format), PyBytes_GET_SIZE(self->s_format));
+ if (fmt == NULL) {
+ return NULL;
+ }
+ PyObject* s = PyUnicode_FromFormat("%s(%R)", _PyType_Name(Py_TYPE(self)), fmt);
+ Py_DECREF(fmt);
+ return s;
+}
+
/* List of functions */
static struct PyMethodDef s_methods[] = {
{Py_tp_dealloc, s_dealloc},
{Py_tp_getattro, PyObject_GenericGetAttr},
{Py_tp_setattro, PyObject_GenericSetAttr},
+ {Py_tp_repr, s_repr},
{Py_tp_doc, (void*)s__doc__},
{Py_tp_traverse, s_traverse},
{Py_tp_clear, s_clear},