Skip to content

Commit acfa776

Browse files
ashm-devvstinner
andauthored
gh-157176: Make time.struct_time type immutable (#157179)
Co-authored-by: Victor Stinner <vstinner@python.org>
1 parent 1610807 commit acfa776

3 files changed

Lines changed: 11 additions & 4 deletions

File tree

‎Lib/test/test_structseq.py‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import textwrap
77
import time
88
import unittest
9+
from test import support
910
from test.support import script_helper
1011

1112

@@ -351,9 +352,9 @@ def test_reference_cycle(self):
351352
# was cleared first, the structseq instance would crash in the
352353
# destructor.
353354
script_helper.assert_python_ok("-c", textwrap.dedent(r"""
354-
import time
355-
t = time.gmtime()
356-
type(t).refcyle = t
355+
import os
356+
t = os.stat('.')
357+
type(t).refcycle = t
357358
"""))
358359

359360
def test_replace_gc_tracked(self):
@@ -365,5 +366,8 @@ def test_replace_gc_tracked(self):
365366

366367
self.assertTrue(gc.is_tracked(replaced_struct))
367368

369+
def test_struct_time_type_immutable(self):
370+
support.check_immutable_type(self, type(time.gmtime()))
371+
368372
if __name__ == "__main__":
369373
unittest.main()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Make the :class:`time.struct_time` type immutable to prevent reference cycles between the type and its instances. Patch by Shamil Abdulaev.

‎Modules/timemodule.c‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#include "pycore_moduleobject.h" // _PyModule_GetState()
66
#include "pycore_namespace.h" // _PyNamespace_New()
77
#include "pycore_runtime.h" // _Py_ID()
8+
#include "pycore_structseq.h" // _PyStructSequence_NewType()
89
#include "pycore_time.h" // _PyTimeFraction
910

1011
#include <time.h> // clock()
@@ -2164,7 +2165,8 @@ time_exec(PyObject *module)
21642165
}
21652166

21662167
// struct_time type
2167-
state->struct_time_type = PyStructSequence_NewType(&struct_time_type_desc);
2168+
state->struct_time_type = _PyStructSequence_NewType(
2169+
&struct_time_type_desc, Py_TPFLAGS_IMMUTABLETYPE);
21682170
if (state->struct_time_type == NULL) {
21692171
return -1;
21702172
}

0 commit comments

Comments
 (0)