Skip to content

Commit 272a62c

Browse files
committed
bpo-12414: Update code_sizeof() to take in account co_extra memory.
1 parent 55fe1ae commit 272a62c

File tree

4 files changed

+16
-5
lines changed

4 files changed

+16
-5
lines changed

Lib/test/test_sys.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -922,13 +922,15 @@ def inner():
922922
return inner
923923
check(get_cell().__closure__[0], size('P'))
924924
# code
925-
check(get_cell().__code__, size('6i13P'))
926-
check(get_cell.__code__, size('6i13P'))
925+
def check_code_size(a, expected_size):
926+
self.assertGreaterEqual(sys.getsizeof(a), expected_size)
927+
check_code_size(get_cell().__code__, size('6i13P'))
928+
check_code_size(get_cell.__code__, size('6i13P'))
927929
def get_cell2(x):
928930
def inner():
929931
return x
930932
return inner
931-
check(get_cell2.__code__, size('6i13P') + calcsize('n'))
933+
check_code_size(get_cell2.__code__, size('6i13P') + calcsize('n'))
932934
# complex
933935
check(complex(0,1), size('2d'))
934936
# method_descriptor (descriptor object)

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1063,6 +1063,7 @@ R. David Murray
10631063
Matti Mäki
10641064
Jörg Müller
10651065
Kaushik N
1066+
Dong-hee Na
10661067
Dale Nagata
10671068
John Nagle
10681069
Takahiro Nakayama

Misc/NEWS

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ What's New in Python 3.7.0 alpha 1?
1010
Core and Builtins
1111
-----------------
1212

13+
- bpo-12414: sys.getsizeof() on a code object now returns the sizes
14+
which includes the code struct and sizes of objects which it references.
15+
Patch by Dong-hee Na.
16+
1317
- bpo-29839: len() now raises ValueError rather than OverflowError if
1418
__len__() returned a large negative integer.
1519

Objects/codeobject.c

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -451,11 +451,15 @@ code_dealloc(PyCodeObject *co)
451451
static PyObject *
452452
code_sizeof(PyCodeObject *co, void *unused)
453453
{
454-
Py_ssize_t res;
454+
Py_ssize_t res = _PyObject_SIZE(Py_TYPE(co));
455+
_PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) co->co_extra;
455456

456-
res = _PyObject_SIZE(Py_TYPE(co));
457457
if (co->co_cell2arg != NULL && co->co_cellvars != NULL)
458458
res += PyTuple_GET_SIZE(co->co_cellvars) * sizeof(Py_ssize_t);
459+
460+
if (co_extra != NULL)
461+
res += co_extra->ce_size * sizeof(co_extra->ce_extras[0]);
462+
459463
return PyLong_FromSsize_t(res);
460464
}
461465

0 commit comments

Comments
 (0)