# HG changeset patch # Parent cdc3837cb1fcfc4273b46e84c533ec7e91246b71 Issue 21071: Bytes for Struct format attribute and format string diff -r cdc3837cb1fc Doc/library/struct.rst --- a/Doc/library/struct.rst Tue Dec 16 03:21:54 2014 -0500 +++ b/Doc/library/struct.rst Tue Dec 16 22:37:18 2014 +0000 @@ -100,7 +100,8 @@ Format strings are the mechanism used to specify the expected layout when packing and unpacking data. They are built up from :ref:`format-characters`, which specify the type of data being packed/unpacked. In addition, there are -special characters for controlling the :ref:`struct-alignment`. +special characters for controlling the :ref:`struct-alignment`. They are +normally character strings, but ASCII byte strings are also acceptable. .. _struct-alignment: @@ -418,7 +419,8 @@ .. attribute:: format - The format string used to construct this Struct object. + The format string used to construct this Struct object, as an ASCII + byte string. .. attribute:: size diff -r cdc3837cb1fc Lib/test/test_struct.py --- a/Lib/test/test_struct.py Tue Dec 16 03:21:54 2014 -0500 +++ b/Lib/test/test_struct.py Tue Dec 16 22:37:18 2014 +0000 @@ -589,6 +589,15 @@ self.check_sizeof('20p', 1) self.check_sizeof('0s', 1) self.check_sizeof('0c', 0) + + def test_format_attr(self): + """Make sure the "format" attribute is a byte string""" + self.assertEqual(b"x", struct.Struct("x").format) + + def test_bytes_format(self): + """Make sure bytes strings are accepted as format strings""" + self.assertEqual(b"x", struct.Struct(b"x").format) + self.assertEqual(b"\x00", struct.pack(b"x")) class UnpackIteratorTest(unittest.TestCase): diff -r cdc3837cb1fc Modules/_struct.c --- a/Modules/_struct.c Tue Dec 16 03:21:54 2014 -0500 +++ b/Modules/_struct.c Tue Dec 16 22:37:18 2014 +0000 @@ -1949,7 +1949,8 @@ #define OFF(x) offsetof(PyStructObject, x) static PyGetSetDef s_getsetlist[] = { - {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL}, + {"format", (getter)s_get_format, (setter)NULL, + "struct format, as an ASCII byte string", NULL}, {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL}, {NULL} /* sentinel */ };