Skip to content

Commit 166959d

Browse files
authored
Fix sys.getsizeof (RustPython#4604)
1 parent e731e65 commit 166959d

File tree

4 files changed

+19
-9
lines changed

4 files changed

+19
-9
lines changed

Lib/test/test_ioctl.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,6 @@ def test_ioctl_mutate_2048(self):
6666
# Test with a larger buffer, just for the record.
6767
self._check_ioctl_mutate_len(2048)
6868

69-
# TODO: RUSTPYTHON
70-
@unittest.expectedFailure
7169
def test_ioctl_signed_unsigned_code_param(self):
7270
if not pty:
7371
raise unittest.SkipTest('pty module required')

Lib/test/test_ordered_dict.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -437,8 +437,6 @@ def test_move_to_end_issue25406(self):
437437
od.move_to_end('c')
438438
self.assertEqual(list(od), list('bac'))
439439

440-
# TODO: RUSTPYTHON
441-
@unittest.expectedFailure
442440
def test_sizeof(self):
443441
OrderedDict = self.OrderedDict
444442
# Wimpy test: Just verify the reported size is larger than a regular dict

vm/src/stdlib/sys.rs

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,12 @@ mod sys {
1717
types::PyStructSequence,
1818
version,
1919
vm::{Settings, VirtualMachine},
20-
AsObject, PyObjectRef, PyRef, PyRefExact, PyResult,
20+
AsObject, PyObject, PyObjectRef, PyRef, PyRefExact, PyResult,
2121
};
2222
use num_traits::ToPrimitive;
2323
use std::{
2424
env::{self, VarError},
25-
mem, path,
25+
path,
2626
sync::atomic::Ordering,
2727
};
2828

@@ -419,10 +419,23 @@ mod sys {
419419
vm.recursion_limit.get()
420420
}
421421

422+
#[derive(FromArgs)]
423+
struct GetsizeofArgs {
424+
obj: PyObjectRef,
425+
#[pyarg(any, optional)]
426+
default: Option<PyObjectRef>,
427+
}
428+
422429
#[pyfunction]
423-
fn getsizeof(obj: PyObjectRef) -> usize {
424-
// TODO: implement default optional argument.
425-
mem::size_of_val(&obj)
430+
fn getsizeof(args: GetsizeofArgs, vm: &VirtualMachine) -> PyResult {
431+
let sizeof = || -> PyResult<usize> {
432+
let res = vm.call_special_method(args.obj, identifier!(vm, __sizeof__), ())?;
433+
let res = res.try_index(vm)?.try_to_primitive::<usize>(vm)?;
434+
Ok(res + std::mem::size_of::<PyObject>())
435+
};
436+
sizeof()
437+
.map(|x| vm.ctx.new_int(x).into())
438+
.or_else(|err| args.default.ok_or(err))
426439
}
427440

428441
#[pyfunction]

vm/src/vm/context.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,7 @@ declare_const_name! {
202202
__str__,
203203
__sub__,
204204
__subclasscheck__,
205+
__sizeof__,
205206
__truediv__,
206207
__trunc__,
207208
__xor__,

0 commit comments

Comments
 (0)