Skip to content

Commit f87b85f

Browse files
authored
bpo-21071: struct.Struct.format type is now str (#845)
1 parent a4b091e commit f87b85f

File tree

5 files changed

+19
-2
lines changed

5 files changed

+19
-2
lines changed

Doc/library/struct.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,9 @@ The :mod:`struct` module also defines the following type:
443443

444444
The format string used to construct this Struct object.
445445

446+
.. versionchanged:: 3.7
447+
The format string type is now :class:`str` instead of :class:`bytes`.
448+
446449
.. attribute:: size
447450

448451
The calculated size of the struct (and hence of the bytes object produced

Doc/whatsnew/3.7.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,9 @@ Changes in the Python API
429429
``makedirs()``.
430430
(Contributed by Serhiy Storchaka in :issue:`19930`.)
431431

432+
* The :attr:`struct.Struct.format` type is now :class:`str` instead of
433+
:class:`bytes`. (Contributed by Victor Stinner in :issue:`21071`.)
434+
432435

433436
CPython bytecode changes
434437
------------------------

Lib/test/test_struct.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,14 @@ def test_issue29802(self):
618618
# Shouldn't crash.
619619
self.assertEqual(struct.unpack(b'b', b'a'), (b'a'[0],))
620620

621+
def test_format_attr(self):
622+
s = struct.Struct('=i2H')
623+
self.assertEqual(s.format, '=i2H')
624+
625+
# use a bytes string
626+
s2 = struct.Struct(s.format.encode())
627+
self.assertEqual(s2.format, s.format)
628+
621629

622630
class UnpackIteratorTest(unittest.TestCase):
623631
"""

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,9 @@ Extension Modules
374374
Library
375375
-------
376376

377+
- bpo-21071: struct.Struct.format type is now :class:`str` instead of
378+
:class:`bytes`.
379+
377380
- bpo-29212: Fix concurrent.futures.thread.ThreadPoolExecutor threads to have
378381
a non repr() based thread name by default when no thread_name_prefix is
379382
supplied. They will now identify themselves as "ThreadPoolExecutor-y_n".

Modules/_struct.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1957,8 +1957,8 @@ s_pack_into(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames
19571957
static PyObject *
19581958
s_get_format(PyStructObject *self, void *unused)
19591959
{
1960-
Py_INCREF(self->s_format);
1961-
return self->s_format;
1960+
return PyUnicode_FromStringAndSize(PyBytes_AS_STRING(self->s_format),
1961+
PyBytes_GET_SIZE(self->s_format));
19621962
}
19631963

19641964
static PyObject *

0 commit comments

Comments
 (0)