Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit f11e522

Browse files
encukouestyxx
authored andcommittedJul 17, 2024
pythongh-117398: pythongh-119655: datetime: Init static state once & don't free it (pythonGH-119662)
- While datetime uses global state, only initialize it once. - While `capi` is static, don't free it (thanks @neonene in https://github.com/python/cpython/pull/119641/files#r1616710048)
1 parent 2ca5185 commit f11e522

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed
 

‎Modules/_datetimemodule.c

+13-5
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,9 @@ typedef struct {
4848

4949
/* The interned Unix epoch datetime instance */
5050
PyObject *epoch;
51+
52+
/* While we use a global state, we ensure it's only initialized once */
53+
int initialized;
5154
} datetime_state;
5255

5356
static datetime_state _datetime_global_state;
@@ -6841,6 +6844,12 @@ create_timezone_from_delta(int days, int sec, int ms, int normalize)
68416844
static int
68426845
init_state(datetime_state *st)
68436846
{
6847+
// While datetime uses global module "state", we unly initialize it once.
6848+
// The PyLong objects created here (once per process) are not decref'd.
6849+
if (st->initialized) {
6850+
return 0;
6851+
}
6852+
68446853
st->date_type = &PyDateTime_DateType;
68456854
st->datetime_type = &PyDateTime_DateTimeType;
68466855
st->delta_type = &PyDateTime_DeltaType;
@@ -6893,6 +6902,9 @@ init_state(datetime_state *st)
68936902
if (st->epoch == NULL) {
68946903
return -1;
68956904
}
6905+
6906+
st->initialized = 1;
6907+
68966908
return 0;
68976909
}
68986910

@@ -7005,12 +7017,8 @@ _datetime_exec(PyObject *module)
70057017
goto error;
70067018
}
70077019
PyObject *capsule = PyCapsule_New(capi, PyDateTime_CAPSULE_NAME, NULL);
7008-
if (capsule == NULL) {
7009-
PyMem_Free(capi);
7010-
goto error;
7011-
}
7020+
// (capsule == NULL) is handled by PyModule_Add
70127021
if (PyModule_Add(module, "datetime_CAPI", capsule) < 0) {
7013-
PyMem_Free(capi);
70147022
goto error;
70157023
}
70167024

0 commit comments

Comments
 (0)
Please sign in to comment.