Skip to content

Commit df5df13

Browse files
corona10serhiy-storchaka
authored andcommitted
[3.6] bpo-12414: Update code_sizeof() to take in account co_extra memory. (#1168) (#1198)
1 parent 83a90b9 commit df5df13

4 files changed

Lines changed: 17 additions & 6 deletions

File tree

Lib/test/test_sys.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -913,13 +913,15 @@ def inner():
913913
return inner
914914
check(get_cell().__closure__[0], size('P'))
915915
# code
916-
check(get_cell().__code__, size('6i13P'))
917-
check(get_cell.__code__, size('6i13P'))
916+
def check_code_size(a, expected_size):
917+
self.assertGreaterEqual(sys.getsizeof(a), expected_size)
918+
check_code_size(get_cell().__code__, size('6i13P'))
919+
check_code_size(get_cell.__code__, size('6i13P'))
918920
def get_cell2(x):
919921
def inner():
920922
return x
921923
return inner
922-
check(get_cell2.__code__, size('6i13P') + 1)
924+
check_code_size(get_cell2.__code__, size('6i13P') + calcsize('n'))
923925
# complex
924926
check(complex(0,1), size('2d'))
925927
# method_descriptor (descriptor object)

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1060,6 +1060,7 @@ R. David Murray
10601060
Matti Mäki
10611061
Jörg Müller
10621062
Kaushik N
1063+
Dong-hee Na
10631064
Dale Nagata
10641065
John Nagle
10651066
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.6.2 release candidate 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-29949: Fix memory usage regression of set and frozenset object.
1418

1519
- bpo-29935: Fixed error messages in the index() method of tuple, list and deque

Objects/codeobject.c

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -446,11 +446,15 @@ code_dealloc(PyCodeObject *co)
446446
static PyObject *
447447
code_sizeof(PyCodeObject *co, void *unused)
448448
{
449-
Py_ssize_t res;
449+
Py_ssize_t res = _PyObject_SIZE(Py_TYPE(co));
450+
_PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) co->co_extra;
450451

451-
res = _PyObject_SIZE(Py_TYPE(co));
452452
if (co->co_cell2arg != NULL && co->co_cellvars != NULL)
453-
res += PyTuple_GET_SIZE(co->co_cellvars) * sizeof(unsigned char);
453+
res += PyTuple_GET_SIZE(co->co_cellvars) * sizeof(Py_ssize_t);
454+
455+
if (co_extra != NULL)
456+
res += co_extra->ce_size * sizeof(co_extra->ce_extras[0]);
457+
454458
return PyLong_FromSsize_t(res);
455459
}
456460

0 commit comments

Comments
 (0)