Skip to content

Commit 6f34060

Browse files
authored
gh-161184: Use a managed dict and weakref list for the io types (#161236)
1 parent c0f3fcf commit 6f34060

10 files changed

Lines changed: 111 additions & 128 deletions

File tree

‎Lib/test/test_io/test_general.py‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -898,6 +898,41 @@ def test_immutable_types(self):
898898
with self.assertRaisesRegex(TypeError, "immutable"):
899899
tp.foo = "bar"
900900

901+
def test_managed_dict(self):
902+
# The _io types use Py_TPFLAGS_MANAGED_DICT: there is no explicit
903+
# dict slot and instance attributes are stored as inline values.
904+
_testinternalcapi = import_helper.import_module("_testinternalcapi")
905+
_io = self._io
906+
no_dict = {_io.IncrementalNewlineDecoder, _io._BytesIOBuffer}
907+
for tp in self.types:
908+
with self.subTest(tp=tp):
909+
if tp in no_dict:
910+
self.assertEqual(tp.__dictoffset__, 0)
911+
else:
912+
self.assertEqual(tp.__dictoffset__, -1)
913+
914+
# Use fresh subclasses: each class has its own shared keys, which
915+
# may already be exhausted on the base types by earlier tests.
916+
class BytesIO(_io.BytesIO): pass
917+
class StringIO(_io.StringIO): pass
918+
class BufferedReader(_io.BufferedReader): pass
919+
class TextIOWrapper(_io.TextIOWrapper): pass
920+
class RawIO(_io._RawIOBase):
921+
def __init__(self):
922+
self.attr = 1
923+
instances = [
924+
BytesIO(b"data"),
925+
StringIO("data"),
926+
BufferedReader(_io.BytesIO(b"data")),
927+
TextIOWrapper(_io.BytesIO()),
928+
RawIO(),
929+
]
930+
for obj in instances:
931+
with self.subTest(obj=type(obj).__name__):
932+
obj.attr = 1
933+
self.assertTrue(_testinternalcapi.has_inline_values(obj))
934+
self.assertEqual(obj.__dict__["attr"], 1)
935+
901936
def test_class_hierarchy(self):
902937
def check_subs(types, base):
903938
for tp in types:

‎Lib/test/test_io/test_memoryio.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import io
1111
import _pyio as pyio
1212
import pickle
13+
import struct
1314
import sys
1415
import weakref
1516

@@ -1037,11 +1038,13 @@ def test_setstate(self):
10371038
@support.cpython_only
10381039
def test_sizeof(self):
10391040
if support.Py_GIL_DISABLED:
1040-
basesize = support.calcobjsize('P2n2Pni')
1041+
basesize = support.calcobjsize('P2nni')
10411042
else:
1042-
basesize = support.calcobjsize('P2n2Pn')
1043+
basesize = support.calcobjsize('P2nn')
10431044
check = self.check_sizeof
10441045
self.assertEqual(object.__sizeof__(io.BytesIO()), basesize)
1046+
# sys.getsizeof() includes the managed dict and weakref pre-header
1047+
basesize += 2 * struct.calcsize('P')
10451048
check(io.BytesIO(), basesize )
10461049
n = 1000 # use a variable to prevent constant folding
10471050
check(io.BytesIO(b'a' * n), basesize + sys.getsizeof(b'a' * n))
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
Speed up attribute access on instances of :mod:`io` classes and their
2+
subclasses by storing instance attributes and weak references in the object
3+
pre-header. The ``__dictoffset__`` and ``__weakrefoffset__`` attributes
4+
of these classes now report the managed offsets, and C extension types that
5+
subclass an :mod:`io` class can no longer declare their own ``__dictoffset__``
6+
or ``__weaklistoffset__`` member.

‎Modules/_io/bufferedio.c‎

Lines changed: 7 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,11 @@
99

1010
#include "Python.h"
1111
#include "pycore_call.h" // _PyObject_CallNoArgs()
12+
#include "pycore_critical_section.h" // _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED()
1213
#include "pycore_fileutils.h" // _PyFile_Flush
1314
#include "pycore_object.h" // _PyObject_GC_UNTRACK()
1415
#include "pycore_pyerrors.h" // _Py_FatalErrorFormat()
1516
#include "pycore_pylifecycle.h" // _Py_IsInterpreterFinalizing()
16-
#include "pycore_weakref.h" // FT_CLEAR_WEAKREFS()
1717

1818
#include "_iomodule.h"
1919

@@ -265,8 +265,6 @@ typedef struct {
265265
Py_ssize_t buffer_size;
266266
Py_ssize_t buffer_mask;
267267

268-
PyObject *dict;
269-
PyObject *weakreflist;
270268
} buffered;
271269

272270
#define buffered_CAST(op) ((buffered *)(op))
@@ -422,7 +420,7 @@ buffered_clear(PyObject *op)
422420
buffered *self = buffered_CAST(op);
423421
self->ok = 0;
424422
Py_CLEAR(self->raw);
425-
Py_CLEAR(self->dict);
423+
PyObject_ClearManagedDict(op);
426424
return 0;
427425
}
428426

@@ -436,7 +434,7 @@ buffered_dealloc(PyObject *op)
436434
return;
437435
_PyObject_GC_UNTRACK(self);
438436
self->ok = 0;
439-
FT_CLEAR_WEAKREFS(op, self->weakreflist);
437+
PyObject_ClearWeakRefs(op);
440438
if (self->buffer) {
441439
PyMem_Free(self->buffer);
442440
self->buffer = NULL;
@@ -472,8 +470,7 @@ buffered_traverse(PyObject *op, visitproc visit, void *arg)
472470
buffered *self = buffered_CAST(op);
473471
Py_VISIT(Py_TYPE(self));
474472
Py_VISIT(self->raw);
475-
Py_VISIT(self->dict);
476-
return 0;
473+
return PyObject_VisitManagedDict(op, visit, arg);
477474
}
478475

479476
/* Because this can call arbitrary code, it shouldn't be called when
@@ -2255,8 +2252,6 @@ typedef struct {
22552252
PyObject_HEAD
22562253
buffered *reader;
22572254
buffered *writer;
2258-
PyObject *dict;
2259-
PyObject *weakreflist;
22602255
} rwpair;
22612256

22622257
#define rwpair_CAST(op) ((rwpair *)(op))
@@ -2314,10 +2309,9 @@ bufferedrwpair_traverse(PyObject *op, visitproc visit, void *arg)
23142309
{
23152310
rwpair *self = rwpair_CAST(op);
23162311
Py_VISIT(Py_TYPE(self));
2317-
Py_VISIT(self->dict);
23182312
Py_VISIT(self->reader);
23192313
Py_VISIT(self->writer);
2320-
return 0;
2314+
return PyObject_VisitManagedDict(op, visit, arg);
23212315
}
23222316

23232317
static int
@@ -2326,7 +2320,7 @@ bufferedrwpair_clear(PyObject *op)
23262320
rwpair *self = rwpair_CAST(op);
23272321
Py_CLEAR(self->reader);
23282322
Py_CLEAR(self->writer);
2329-
Py_CLEAR(self->dict);
2323+
PyObject_ClearManagedDict(op);
23302324
return 0;
23312325
}
23322326

@@ -2336,7 +2330,7 @@ bufferedrwpair_dealloc(PyObject *op)
23362330
rwpair *self = rwpair_CAST(op);
23372331
PyTypeObject *tp = Py_TYPE(self);
23382332
_PyObject_GC_UNTRACK(self);
2339-
FT_CLEAR_WEAKREFS(op, self->weakreflist);
2333+
PyObject_ClearWeakRefs(op);
23402334
(void)bufferedrwpair_clear(op);
23412335
tp->tp_free(self);
23422336
Py_DECREF(tp);
@@ -2662,8 +2656,6 @@ static PyMethodDef bufferedreader_methods[] = {
26622656
static PyMemberDef bufferedreader_members[] = {
26632657
{"raw", _Py_T_OBJECT, offsetof(buffered, raw), Py_READONLY},
26642658
{"_finalizing", Py_T_BOOL, offsetof(buffered, finalizing), 0},
2665-
{"__weaklistoffset__", Py_T_PYSSIZET, offsetof(buffered, weakreflist), Py_READONLY},
2666-
{"__dictoffset__", Py_T_PYSSIZET, offsetof(buffered, dict), Py_READONLY},
26672659
{NULL}
26682660
};
26692661

@@ -2721,8 +2713,6 @@ static PyMethodDef bufferedwriter_methods[] = {
27212713
static PyMemberDef bufferedwriter_members[] = {
27222714
{"raw", _Py_T_OBJECT, offsetof(buffered, raw), Py_READONLY},
27232715
{"_finalizing", Py_T_BOOL, offsetof(buffered, finalizing), 0},
2724-
{"__weaklistoffset__", Py_T_PYSSIZET, offsetof(buffered, weakreflist), Py_READONLY},
2725-
{"__dictoffset__", Py_T_PYSSIZET, offsetof(buffered, dict), Py_READONLY},
27262716
{NULL}
27272717
};
27282718

@@ -2775,12 +2765,6 @@ static PyMethodDef bufferedrwpair_methods[] = {
27752765
{NULL, NULL}
27762766
};
27772767

2778-
static PyMemberDef bufferedrwpair_members[] = {
2779-
{"__weaklistoffset__", Py_T_PYSSIZET, offsetof(rwpair, weakreflist), Py_READONLY},
2780-
{"__dictoffset__", Py_T_PYSSIZET, offsetof(rwpair, dict), Py_READONLY},
2781-
{NULL}
2782-
};
2783-
27842768
static PyGetSetDef bufferedrwpair_getset[] = {
27852769
_IO_BUFFEREDRWPAIR_CLOSED_GETSETDEF
27862770
{NULL}
@@ -2792,7 +2776,6 @@ static PyType_Slot bufferedrwpair_slots[] = {
27922776
{Py_tp_traverse, bufferedrwpair_traverse},
27932777
{Py_tp_clear, bufferedrwpair_clear},
27942778
{Py_tp_methods, bufferedrwpair_methods},
2795-
{Py_tp_members, bufferedrwpair_members},
27962779
{Py_tp_getset, bufferedrwpair_getset},
27972780
{Py_tp_init, _io_BufferedRWPair___init__},
27982781
{0, NULL},
@@ -2839,8 +2822,6 @@ static PyMethodDef bufferedrandom_methods[] = {
28392822
static PyMemberDef bufferedrandom_members[] = {
28402823
{"raw", _Py_T_OBJECT, offsetof(buffered, raw), Py_READONLY},
28412824
{"_finalizing", Py_T_BOOL, offsetof(buffered, finalizing), 0},
2842-
{"__weaklistoffset__", Py_T_PYSSIZET, offsetof(buffered, weakreflist), Py_READONLY},
2843-
{"__dictoffset__", Py_T_PYSSIZET, offsetof(buffered, dict), Py_READONLY},
28442825
{NULL}
28452826
};
28462827

‎Modules/_io/bytesio.c‎

Lines changed: 20 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
#include "pycore_object.h"
66
#include "pycore_pyatomic_ft_wrappers.h"
77
#include "pycore_sysmodule.h" // _PySys_GetSizeOf()
8-
#include "pycore_weakref.h" // FT_CLEAR_WEAKREFS()
98

109
#include <stddef.h> // offsetof()
1110
#include "_iomodule.h"
@@ -21,8 +20,6 @@ typedef struct {
2120
PyObject *buf;
2221
Py_ssize_t pos;
2322
Py_ssize_t string_size;
24-
PyObject *dict;
25-
PyObject *weakreflist;
2623
Py_ssize_t exports;
2724
#ifdef Py_GIL_DISABLED
2825
int buf_shared;
@@ -974,11 +971,16 @@ _io_BytesIO___getstate___impl(bytesio *self)
974971

975972
if (initvalue == NULL)
976973
return NULL;
977-
if (self->dict == NULL) {
974+
if (_PyObject_IsInstanceDictEmpty((PyObject *)self)) {
978975
dict = Py_NewRef(Py_None);
979976
}
980977
else {
981-
dict = PyDict_Copy(self->dict);
978+
dict = PyObject_GenericGetDict((PyObject *)self, NULL);
979+
if (dict == NULL) {
980+
Py_DECREF(initvalue);
981+
return NULL;
982+
}
983+
Py_SETREF(dict, PyDict_Copy(dict));
982984
if (dict == NULL) {
983985
Py_DECREF(initvalue);
984986
return NULL;
@@ -1061,16 +1063,16 @@ _io_BytesIO___setstate___impl(bytesio *self, PyObject *state)
10611063
Py_TYPE(dict)->tp_name);
10621064
return NULL;
10631065
}
1064-
if (self->dict) {
1065-
/* Alternatively, we could replace the internal dictionary
1066-
completely. However, it seems more practical to just update it. */
1067-
if (PyDict_Update(self->dict, dict) < 0)
1068-
return NULL;
1066+
/* Alternatively, we could replace the internal dictionary
1067+
completely. However, it seems more practical to just update it. */
1068+
PyObject *self_dict = PyObject_GenericGetDict((PyObject *)self, NULL);
1069+
if (self_dict == NULL) {
1070+
return NULL;
10691071
}
1070-
else {
1071-
/* The LOAD_ATTR specializations read the dict slot lock-free
1072-
with an acquire load, so pair it with a release store. */
1073-
FT_ATOMIC_STORE_PTR_RELEASE(self->dict, Py_NewRef(dict));
1072+
int rc = PyDict_Update(self_dict, dict);
1073+
Py_DECREF(self_dict);
1074+
if (rc < 0) {
1075+
return NULL;
10741076
}
10751077
}
10761078

@@ -1089,8 +1091,8 @@ bytesio_dealloc(PyObject *op)
10891091
PyErr_Print();
10901092
}
10911093
Py_CLEAR(self->buf);
1092-
Py_CLEAR(self->dict);
1093-
FT_CLEAR_WEAKREFS(op, self->weakreflist);
1094+
PyObject_ClearManagedDict(op);
1095+
PyObject_ClearWeakRefs(op);
10941096
tp->tp_free(self);
10951097
Py_DECREF(tp);
10961098
}
@@ -1187,16 +1189,15 @@ bytesio_traverse(PyObject *op, visitproc visit, void *arg)
11871189
{
11881190
bytesio *self = bytesio_CAST(op);
11891191
Py_VISIT(Py_TYPE(self));
1190-
Py_VISIT(self->dict);
11911192
Py_VISIT(self->buf);
1192-
return 0;
1193+
return PyObject_VisitManagedDict(op, visit, arg);
11931194
}
11941195

11951196
static int
11961197
bytesio_clear(PyObject *op)
11971198
{
11981199
bytesio *self = bytesio_CAST(op);
1199-
Py_CLEAR(self->dict);
1200+
PyObject_ClearManagedDict(op);
12001201
if (FT_ATOMIC_LOAD_SSIZE_RELAXED(self->exports) == 0) {
12011202
Py_CLEAR(self->buf);
12021203
}
@@ -1239,12 +1240,6 @@ static struct PyMethodDef bytesio_methods[] = {
12391240
{NULL, NULL} /* sentinel */
12401241
};
12411242

1242-
static PyMemberDef bytesio_members[] = {
1243-
{"__weaklistoffset__", Py_T_PYSSIZET, offsetof(bytesio, weakreflist), Py_READONLY},
1244-
{"__dictoffset__", Py_T_PYSSIZET, offsetof(bytesio, dict), Py_READONLY},
1245-
{NULL}
1246-
};
1247-
12481243
static PyType_Slot bytesio_slots[] = {
12491244
{Py_tp_dealloc, bytesio_dealloc},
12501245
{Py_tp_doc, (void *)_io_BytesIO___init____doc__},
@@ -1253,7 +1248,6 @@ static PyType_Slot bytesio_slots[] = {
12531248
{Py_tp_iter, PyObject_SelfIter},
12541249
{Py_tp_iternext, bytesio_iternext},
12551250
{Py_tp_methods, bytesio_methods},
1256-
{Py_tp_members, bytesio_members},
12571251
{Py_tp_getset, bytesio_getsetlist},
12581252
{Py_tp_init, _io_BytesIO___init__},
12591253
{Py_tp_new, bytesio_new},

‎Modules/_io/fileio.c‎

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
#include "pycore_fileutils.h" // _Py_BEGIN_SUPPRESS_IPH
66
#include "pycore_object.h" // _PyObject_GC_UNTRACK()
77
#include "pycore_pyerrors.h" // _PyErr_ChainExceptions1()
8-
#include "pycore_weakref.h" // FT_CLEAR_WEAKREFS()
98

109
#include <stdbool.h> // bool
1110
#ifdef HAVE_UNISTD_H
@@ -81,8 +80,6 @@ typedef struct {
8180
modified outside of the fileio object / Python (ex. gh-90102, GH-121941,
8281
gh-109523). */
8382
struct _Py_stat_struct *stat_atopen;
84-
PyObject *weakreflist;
85-
PyObject *dict;
8683
} fileio;
8784

8885
#define PyFileIO_Check(state, op) (PyObject_TypeCheck((op), state->PyFileIO_Type))
@@ -221,7 +218,6 @@ fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
221218
self->truncate = 0;
222219
self->stat_atopen = NULL;
223220
self->closefd = 1;
224-
self->weakreflist = NULL;
225221
return (PyObject *) self;
226222
}
227223

@@ -562,15 +558,13 @@ fileio_traverse(PyObject *op, visitproc visit, void *arg)
562558
{
563559
fileio *self = PyFileIO_CAST(op);
564560
Py_VISIT(Py_TYPE(self));
565-
Py_VISIT(self->dict);
566-
return 0;
561+
return PyObject_VisitManagedDict(op, visit, arg);
567562
}
568563

569564
static int
570565
fileio_clear(PyObject *op)
571566
{
572-
fileio *self = PyFileIO_CAST(op);
573-
Py_CLEAR(self->dict);
567+
PyObject_ClearManagedDict(op);
574568
return 0;
575569
}
576570

@@ -588,7 +582,7 @@ fileio_dealloc(PyObject *op)
588582
PyMem_Free(self->stat_atopen);
589583
self->stat_atopen = NULL;
590584
}
591-
FT_CLEAR_WEAKREFS(op, self->weakreflist);
585+
PyObject_ClearWeakRefs(op);
592586
(void)fileio_clear(op);
593587

594588
PyTypeObject *tp = Py_TYPE(op);
@@ -1370,8 +1364,6 @@ static PyGetSetDef fileio_getsetlist[] = {
13701364

13711365
static PyMemberDef fileio_members[] = {
13721366
{"_finalizing", Py_T_BOOL, offsetof(fileio, finalizing), 0},
1373-
{"__weaklistoffset__", Py_T_PYSSIZET, offsetof(fileio, weakreflist), Py_READONLY},
1374-
{"__dictoffset__", Py_T_PYSSIZET, offsetof(fileio, dict), Py_READONLY},
13751367
{NULL}
13761368
};
13771369

0 commit comments

Comments
 (0)